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         QualType DT = OldAT->getDeducedType();
3617         if (DT.isNull()) {
3618           New->setType(SubstAutoTypeDependent(New->getType()));
3619           NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3620         } else {
3621           New->setType(SubstAutoType(New->getType(), DT));
3622           NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3623         }
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           << (NewFDisConst
8509                   ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8510                                                  .getConstQualifierLoc())
8511                   : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8512                                                    .getRParenLoc()
8513                                                    .getLocWithOffset(1),
8514                                                " const"));
8515     } else
8516       SemaRef.Diag(FD->getLocation(),
8517                    IsMember ? diag::note_member_def_close_match
8518                             : diag::note_local_decl_close_match);
8519   }
8520   return nullptr;
8521 }
8522 
8523 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8524   switch (D.getDeclSpec().getStorageClassSpec()) {
8525   default: llvm_unreachable("Unknown storage class!");
8526   case DeclSpec::SCS_auto:
8527   case DeclSpec::SCS_register:
8528   case DeclSpec::SCS_mutable:
8529     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8530                  diag::err_typecheck_sclass_func);
8531     D.getMutableDeclSpec().ClearStorageClassSpecs();
8532     D.setInvalidType();
8533     break;
8534   case DeclSpec::SCS_unspecified: break;
8535   case DeclSpec::SCS_extern:
8536     if (D.getDeclSpec().isExternInLinkageSpec())
8537       return SC_None;
8538     return SC_Extern;
8539   case DeclSpec::SCS_static: {
8540     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8541       // C99 6.7.1p5:
8542       //   The declaration of an identifier for a function that has
8543       //   block scope shall have no explicit storage-class specifier
8544       //   other than extern
8545       // See also (C++ [dcl.stc]p4).
8546       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8547                    diag::err_static_block_func);
8548       break;
8549     } else
8550       return SC_Static;
8551   }
8552   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8553   }
8554 
8555   // No explicit storage class has already been returned
8556   return SC_None;
8557 }
8558 
8559 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8560                                            DeclContext *DC, QualType &R,
8561                                            TypeSourceInfo *TInfo,
8562                                            StorageClass SC,
8563                                            bool &IsVirtualOkay) {
8564   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8565   DeclarationName Name = NameInfo.getName();
8566 
8567   FunctionDecl *NewFD = nullptr;
8568   bool isInline = D.getDeclSpec().isInlineSpecified();
8569 
8570   if (!SemaRef.getLangOpts().CPlusPlus) {
8571     // Determine whether the function was written with a
8572     // prototype. This true when:
8573     //   - there is a prototype in the declarator, or
8574     //   - the type R of the function is some kind of typedef or other non-
8575     //     attributed reference to a type name (which eventually refers to a
8576     //     function type).
8577     bool HasPrototype =
8578       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8579       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8580 
8581     NewFD = FunctionDecl::Create(
8582         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8583         SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8584         ConstexprSpecKind::Unspecified,
8585         /*TrailingRequiresClause=*/nullptr);
8586     if (D.isInvalidType())
8587       NewFD->setInvalidDecl();
8588 
8589     return NewFD;
8590   }
8591 
8592   ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8593 
8594   ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8595   if (ConstexprKind == ConstexprSpecKind::Constinit) {
8596     SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8597                  diag::err_constexpr_wrong_decl_kind)
8598         << static_cast<int>(ConstexprKind);
8599     ConstexprKind = ConstexprSpecKind::Unspecified;
8600     D.getMutableDeclSpec().ClearConstexprSpec();
8601   }
8602   Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8603 
8604   // Check that the return type is not an abstract class type.
8605   // For record types, this is done by the AbstractClassUsageDiagnoser once
8606   // the class has been completely parsed.
8607   if (!DC->isRecord() &&
8608       SemaRef.RequireNonAbstractType(
8609           D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8610           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8611     D.setInvalidType();
8612 
8613   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8614     // This is a C++ constructor declaration.
8615     assert(DC->isRecord() &&
8616            "Constructors can only be declared in a member context");
8617 
8618     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8619     return CXXConstructorDecl::Create(
8620         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8621         TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(),
8622         isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8623         InheritedConstructor(), TrailingRequiresClause);
8624 
8625   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8626     // This is a C++ destructor declaration.
8627     if (DC->isRecord()) {
8628       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8629       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8630       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8631           SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8632           SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8633           /*isImplicitlyDeclared=*/false, ConstexprKind,
8634           TrailingRequiresClause);
8635 
8636       // If the destructor needs an implicit exception specification, set it
8637       // now. FIXME: It'd be nice to be able to create the right type to start
8638       // with, but the type needs to reference the destructor declaration.
8639       if (SemaRef.getLangOpts().CPlusPlus11)
8640         SemaRef.AdjustDestructorExceptionSpec(NewDD);
8641 
8642       IsVirtualOkay = true;
8643       return NewDD;
8644 
8645     } else {
8646       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8647       D.setInvalidType();
8648 
8649       // Create a FunctionDecl to satisfy the function definition parsing
8650       // code path.
8651       return FunctionDecl::Create(
8652           SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8653           TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8654           /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8655     }
8656 
8657   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8658     if (!DC->isRecord()) {
8659       SemaRef.Diag(D.getIdentifierLoc(),
8660            diag::err_conv_function_not_member);
8661       return nullptr;
8662     }
8663 
8664     SemaRef.CheckConversionDeclarator(D, R, SC);
8665     if (D.isInvalidType())
8666       return nullptr;
8667 
8668     IsVirtualOkay = true;
8669     return CXXConversionDecl::Create(
8670         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8671         TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8672         ExplicitSpecifier, ConstexprKind, SourceLocation(),
8673         TrailingRequiresClause);
8674 
8675   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8676     if (TrailingRequiresClause)
8677       SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8678                    diag::err_trailing_requires_clause_on_deduction_guide)
8679           << TrailingRequiresClause->getSourceRange();
8680     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8681 
8682     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8683                                          ExplicitSpecifier, NameInfo, R, TInfo,
8684                                          D.getEndLoc());
8685   } else if (DC->isRecord()) {
8686     // If the name of the function is the same as the name of the record,
8687     // then this must be an invalid constructor that has a return type.
8688     // (The parser checks for a return type and makes the declarator a
8689     // constructor if it has no return type).
8690     if (Name.getAsIdentifierInfo() &&
8691         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8692       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8693         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8694         << SourceRange(D.getIdentifierLoc());
8695       return nullptr;
8696     }
8697 
8698     // This is a C++ method declaration.
8699     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8700         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8701         TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8702         ConstexprKind, SourceLocation(), TrailingRequiresClause);
8703     IsVirtualOkay = !Ret->isStatic();
8704     return Ret;
8705   } else {
8706     bool isFriend =
8707         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8708     if (!isFriend && SemaRef.CurContext->isRecord())
8709       return nullptr;
8710 
8711     // Determine whether the function was written with a
8712     // prototype. This true when:
8713     //   - we're in C++ (where every function has a prototype),
8714     return FunctionDecl::Create(
8715         SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8716         SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8717         true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8718   }
8719 }
8720 
8721 enum OpenCLParamType {
8722   ValidKernelParam,
8723   PtrPtrKernelParam,
8724   PtrKernelParam,
8725   InvalidAddrSpacePtrKernelParam,
8726   InvalidKernelParam,
8727   RecordKernelParam
8728 };
8729 
8730 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8731   // Size dependent types are just typedefs to normal integer types
8732   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8733   // integers other than by their names.
8734   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8735 
8736   // Remove typedefs one by one until we reach a typedef
8737   // for a size dependent type.
8738   QualType DesugaredTy = Ty;
8739   do {
8740     ArrayRef<StringRef> Names(SizeTypeNames);
8741     auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8742     if (Names.end() != Match)
8743       return true;
8744 
8745     Ty = DesugaredTy;
8746     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8747   } while (DesugaredTy != Ty);
8748 
8749   return false;
8750 }
8751 
8752 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8753   if (PT->isDependentType())
8754     return InvalidKernelParam;
8755 
8756   if (PT->isPointerType() || PT->isReferenceType()) {
8757     QualType PointeeType = PT->getPointeeType();
8758     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8759         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8760         PointeeType.getAddressSpace() == LangAS::Default)
8761       return InvalidAddrSpacePtrKernelParam;
8762 
8763     if (PointeeType->isPointerType()) {
8764       // This is a pointer to pointer parameter.
8765       // Recursively check inner type.
8766       OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8767       if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8768           ParamKind == InvalidKernelParam)
8769         return ParamKind;
8770 
8771       return PtrPtrKernelParam;
8772     }
8773 
8774     // C++ for OpenCL v1.0 s2.4:
8775     // Moreover the types used in parameters of the kernel functions must be:
8776     // Standard layout types for pointer parameters. The same applies to
8777     // reference if an implementation supports them in kernel parameters.
8778     if (S.getLangOpts().OpenCLCPlusPlus &&
8779         !S.getOpenCLOptions().isAvailableOption(
8780             "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8781         !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8782         !PointeeType->isStandardLayoutType())
8783       return InvalidKernelParam;
8784 
8785     return PtrKernelParam;
8786   }
8787 
8788   // OpenCL v1.2 s6.9.k:
8789   // Arguments to kernel functions in a program cannot be declared with the
8790   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8791   // uintptr_t or a struct and/or union that contain fields declared to be one
8792   // of these built-in scalar types.
8793   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8794     return InvalidKernelParam;
8795 
8796   if (PT->isImageType())
8797     return PtrKernelParam;
8798 
8799   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8800     return InvalidKernelParam;
8801 
8802   // OpenCL extension spec v1.2 s9.5:
8803   // This extension adds support for half scalar and vector types as built-in
8804   // types that can be used for arithmetic operations, conversions etc.
8805   if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8806       PT->isHalfType())
8807     return InvalidKernelParam;
8808 
8809   // Look into an array argument to check if it has a forbidden type.
8810   if (PT->isArrayType()) {
8811     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8812     // Call ourself to check an underlying type of an array. Since the
8813     // getPointeeOrArrayElementType returns an innermost type which is not an
8814     // array, this recursive call only happens once.
8815     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8816   }
8817 
8818   // C++ for OpenCL v1.0 s2.4:
8819   // Moreover the types used in parameters of the kernel functions must be:
8820   // Trivial and standard-layout types C++17 [basic.types] (plain old data
8821   // types) for parameters passed by value;
8822   if (S.getLangOpts().OpenCLCPlusPlus &&
8823       !S.getOpenCLOptions().isAvailableOption(
8824           "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8825       !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8826     return InvalidKernelParam;
8827 
8828   if (PT->isRecordType())
8829     return RecordKernelParam;
8830 
8831   return ValidKernelParam;
8832 }
8833 
8834 static void checkIsValidOpenCLKernelParameter(
8835   Sema &S,
8836   Declarator &D,
8837   ParmVarDecl *Param,
8838   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8839   QualType PT = Param->getType();
8840 
8841   // Cache the valid types we encounter to avoid rechecking structs that are
8842   // used again
8843   if (ValidTypes.count(PT.getTypePtr()))
8844     return;
8845 
8846   switch (getOpenCLKernelParameterType(S, PT)) {
8847   case PtrPtrKernelParam:
8848     // OpenCL v3.0 s6.11.a:
8849     // A kernel function argument cannot be declared as a pointer to a pointer
8850     // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8851     if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
8852       S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8853       D.setInvalidType();
8854       return;
8855     }
8856 
8857     ValidTypes.insert(PT.getTypePtr());
8858     return;
8859 
8860   case InvalidAddrSpacePtrKernelParam:
8861     // OpenCL v1.0 s6.5:
8862     // __kernel function arguments declared to be a pointer of a type can point
8863     // to one of the following address spaces only : __global, __local or
8864     // __constant.
8865     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8866     D.setInvalidType();
8867     return;
8868 
8869     // OpenCL v1.2 s6.9.k:
8870     // Arguments to kernel functions in a program cannot be declared with the
8871     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8872     // uintptr_t or a struct and/or union that contain fields declared to be
8873     // one of these built-in scalar types.
8874 
8875   case InvalidKernelParam:
8876     // OpenCL v1.2 s6.8 n:
8877     // A kernel function argument cannot be declared
8878     // of event_t type.
8879     // Do not diagnose half type since it is diagnosed as invalid argument
8880     // type for any function elsewhere.
8881     if (!PT->isHalfType()) {
8882       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8883 
8884       // Explain what typedefs are involved.
8885       const TypedefType *Typedef = nullptr;
8886       while ((Typedef = PT->getAs<TypedefType>())) {
8887         SourceLocation Loc = Typedef->getDecl()->getLocation();
8888         // SourceLocation may be invalid for a built-in type.
8889         if (Loc.isValid())
8890           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8891         PT = Typedef->desugar();
8892       }
8893     }
8894 
8895     D.setInvalidType();
8896     return;
8897 
8898   case PtrKernelParam:
8899   case ValidKernelParam:
8900     ValidTypes.insert(PT.getTypePtr());
8901     return;
8902 
8903   case RecordKernelParam:
8904     break;
8905   }
8906 
8907   // Track nested structs we will inspect
8908   SmallVector<const Decl *, 4> VisitStack;
8909 
8910   // Track where we are in the nested structs. Items will migrate from
8911   // VisitStack to HistoryStack as we do the DFS for bad field.
8912   SmallVector<const FieldDecl *, 4> HistoryStack;
8913   HistoryStack.push_back(nullptr);
8914 
8915   // At this point we already handled everything except of a RecordType or
8916   // an ArrayType of a RecordType.
8917   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8918   const RecordType *RecTy =
8919       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8920   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8921 
8922   VisitStack.push_back(RecTy->getDecl());
8923   assert(VisitStack.back() && "First decl null?");
8924 
8925   do {
8926     const Decl *Next = VisitStack.pop_back_val();
8927     if (!Next) {
8928       assert(!HistoryStack.empty());
8929       // Found a marker, we have gone up a level
8930       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8931         ValidTypes.insert(Hist->getType().getTypePtr());
8932 
8933       continue;
8934     }
8935 
8936     // Adds everything except the original parameter declaration (which is not a
8937     // field itself) to the history stack.
8938     const RecordDecl *RD;
8939     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8940       HistoryStack.push_back(Field);
8941 
8942       QualType FieldTy = Field->getType();
8943       // Other field types (known to be valid or invalid) are handled while we
8944       // walk around RecordDecl::fields().
8945       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8946              "Unexpected type.");
8947       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8948 
8949       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8950     } else {
8951       RD = cast<RecordDecl>(Next);
8952     }
8953 
8954     // Add a null marker so we know when we've gone back up a level
8955     VisitStack.push_back(nullptr);
8956 
8957     for (const auto *FD : RD->fields()) {
8958       QualType QT = FD->getType();
8959 
8960       if (ValidTypes.count(QT.getTypePtr()))
8961         continue;
8962 
8963       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8964       if (ParamType == ValidKernelParam)
8965         continue;
8966 
8967       if (ParamType == RecordKernelParam) {
8968         VisitStack.push_back(FD);
8969         continue;
8970       }
8971 
8972       // OpenCL v1.2 s6.9.p:
8973       // Arguments to kernel functions that are declared to be a struct or union
8974       // do not allow OpenCL objects to be passed as elements of the struct or
8975       // union.
8976       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8977           ParamType == InvalidAddrSpacePtrKernelParam) {
8978         S.Diag(Param->getLocation(),
8979                diag::err_record_with_pointers_kernel_param)
8980           << PT->isUnionType()
8981           << PT;
8982       } else {
8983         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8984       }
8985 
8986       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8987           << OrigRecDecl->getDeclName();
8988 
8989       // We have an error, now let's go back up through history and show where
8990       // the offending field came from
8991       for (ArrayRef<const FieldDecl *>::const_iterator
8992                I = HistoryStack.begin() + 1,
8993                E = HistoryStack.end();
8994            I != E; ++I) {
8995         const FieldDecl *OuterField = *I;
8996         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8997           << OuterField->getType();
8998       }
8999 
9000       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9001         << QT->isPointerType()
9002         << QT;
9003       D.setInvalidType();
9004       return;
9005     }
9006   } while (!VisitStack.empty());
9007 }
9008 
9009 /// Find the DeclContext in which a tag is implicitly declared if we see an
9010 /// elaborated type specifier in the specified context, and lookup finds
9011 /// nothing.
9012 static DeclContext *getTagInjectionContext(DeclContext *DC) {
9013   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9014     DC = DC->getParent();
9015   return DC;
9016 }
9017 
9018 /// Find the Scope in which a tag is implicitly declared if we see an
9019 /// elaborated type specifier in the specified context, and lookup finds
9020 /// nothing.
9021 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9022   while (S->isClassScope() ||
9023          (LangOpts.CPlusPlus &&
9024           S->isFunctionPrototypeScope()) ||
9025          ((S->getFlags() & Scope::DeclScope) == 0) ||
9026          (S->getEntity() && S->getEntity()->isTransparentContext()))
9027     S = S->getParent();
9028   return S;
9029 }
9030 
9031 NamedDecl*
9032 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9033                               TypeSourceInfo *TInfo, LookupResult &Previous,
9034                               MultiTemplateParamsArg TemplateParamListsRef,
9035                               bool &AddToScope) {
9036   QualType R = TInfo->getType();
9037 
9038   assert(R->isFunctionType());
9039   if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9040     Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9041 
9042   SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9043   for (TemplateParameterList *TPL : TemplateParamListsRef)
9044     TemplateParamLists.push_back(TPL);
9045   if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9046     if (!TemplateParamLists.empty() &&
9047         Invented->getDepth() == TemplateParamLists.back()->getDepth())
9048       TemplateParamLists.back() = Invented;
9049     else
9050       TemplateParamLists.push_back(Invented);
9051   }
9052 
9053   // TODO: consider using NameInfo for diagnostic.
9054   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9055   DeclarationName Name = NameInfo.getName();
9056   StorageClass SC = getFunctionStorageClass(*this, D);
9057 
9058   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9059     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9060          diag::err_invalid_thread)
9061       << DeclSpec::getSpecifierName(TSCS);
9062 
9063   if (D.isFirstDeclarationOfMember())
9064     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9065                            D.getIdentifierLoc());
9066 
9067   bool isFriend = false;
9068   FunctionTemplateDecl *FunctionTemplate = nullptr;
9069   bool isMemberSpecialization = false;
9070   bool isFunctionTemplateSpecialization = false;
9071 
9072   bool isDependentClassScopeExplicitSpecialization = false;
9073   bool HasExplicitTemplateArgs = false;
9074   TemplateArgumentListInfo TemplateArgs;
9075 
9076   bool isVirtualOkay = false;
9077 
9078   DeclContext *OriginalDC = DC;
9079   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9080 
9081   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9082                                               isVirtualOkay);
9083   if (!NewFD) return nullptr;
9084 
9085   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9086     NewFD->setTopLevelDeclInObjCContainer();
9087 
9088   // Set the lexical context. If this is a function-scope declaration, or has a
9089   // C++ scope specifier, or is the object of a friend declaration, the lexical
9090   // context will be different from the semantic context.
9091   NewFD->setLexicalDeclContext(CurContext);
9092 
9093   if (IsLocalExternDecl)
9094     NewFD->setLocalExternDecl();
9095 
9096   if (getLangOpts().CPlusPlus) {
9097     bool isInline = D.getDeclSpec().isInlineSpecified();
9098     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9099     bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9100     isFriend = D.getDeclSpec().isFriendSpecified();
9101     if (isFriend && !isInline && D.isFunctionDefinition()) {
9102       // C++ [class.friend]p5
9103       //   A function can be defined in a friend declaration of a
9104       //   class . . . . Such a function is implicitly inline.
9105       NewFD->setImplicitlyInline();
9106     }
9107 
9108     // If this is a method defined in an __interface, and is not a constructor
9109     // or an overloaded operator, then set the pure flag (isVirtual will already
9110     // return true).
9111     if (const CXXRecordDecl *Parent =
9112           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9113       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9114         NewFD->setPure(true);
9115 
9116       // C++ [class.union]p2
9117       //   A union can have member functions, but not virtual functions.
9118       if (isVirtual && Parent->isUnion()) {
9119         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9120         NewFD->setInvalidDecl();
9121       }
9122     }
9123 
9124     SetNestedNameSpecifier(*this, NewFD, D);
9125     isMemberSpecialization = false;
9126     isFunctionTemplateSpecialization = false;
9127     if (D.isInvalidType())
9128       NewFD->setInvalidDecl();
9129 
9130     // Match up the template parameter lists with the scope specifier, then
9131     // determine whether we have a template or a template specialization.
9132     bool Invalid = false;
9133     TemplateParameterList *TemplateParams =
9134         MatchTemplateParametersToScopeSpecifier(
9135             D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9136             D.getCXXScopeSpec(),
9137             D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9138                 ? D.getName().TemplateId
9139                 : nullptr,
9140             TemplateParamLists, isFriend, isMemberSpecialization,
9141             Invalid);
9142     if (TemplateParams) {
9143       // Check that we can declare a template here.
9144       if (CheckTemplateDeclScope(S, TemplateParams))
9145         NewFD->setInvalidDecl();
9146 
9147       if (TemplateParams->size() > 0) {
9148         // This is a function template
9149 
9150         // A destructor cannot be a template.
9151         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9152           Diag(NewFD->getLocation(), diag::err_destructor_template);
9153           NewFD->setInvalidDecl();
9154         }
9155 
9156         // If we're adding a template to a dependent context, we may need to
9157         // rebuilding some of the types used within the template parameter list,
9158         // now that we know what the current instantiation is.
9159         if (DC->isDependentContext()) {
9160           ContextRAII SavedContext(*this, DC);
9161           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9162             Invalid = true;
9163         }
9164 
9165         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9166                                                         NewFD->getLocation(),
9167                                                         Name, TemplateParams,
9168                                                         NewFD);
9169         FunctionTemplate->setLexicalDeclContext(CurContext);
9170         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9171 
9172         // For source fidelity, store the other template param lists.
9173         if (TemplateParamLists.size() > 1) {
9174           NewFD->setTemplateParameterListsInfo(Context,
9175               ArrayRef<TemplateParameterList *>(TemplateParamLists)
9176                   .drop_back(1));
9177         }
9178       } else {
9179         // This is a function template specialization.
9180         isFunctionTemplateSpecialization = true;
9181         // For source fidelity, store all the template param lists.
9182         if (TemplateParamLists.size() > 0)
9183           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9184 
9185         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9186         if (isFriend) {
9187           // We want to remove the "template<>", found here.
9188           SourceRange RemoveRange = TemplateParams->getSourceRange();
9189 
9190           // If we remove the template<> and the name is not a
9191           // template-id, we're actually silently creating a problem:
9192           // the friend declaration will refer to an untemplated decl,
9193           // and clearly the user wants a template specialization.  So
9194           // we need to insert '<>' after the name.
9195           SourceLocation InsertLoc;
9196           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9197             InsertLoc = D.getName().getSourceRange().getEnd();
9198             InsertLoc = getLocForEndOfToken(InsertLoc);
9199           }
9200 
9201           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9202             << Name << RemoveRange
9203             << FixItHint::CreateRemoval(RemoveRange)
9204             << FixItHint::CreateInsertion(InsertLoc, "<>");
9205           Invalid = true;
9206         }
9207       }
9208     } else {
9209       // Check that we can declare a template here.
9210       if (!TemplateParamLists.empty() && isMemberSpecialization &&
9211           CheckTemplateDeclScope(S, TemplateParamLists.back()))
9212         NewFD->setInvalidDecl();
9213 
9214       // All template param lists were matched against the scope specifier:
9215       // this is NOT (an explicit specialization of) a template.
9216       if (TemplateParamLists.size() > 0)
9217         // For source fidelity, store all the template param lists.
9218         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9219     }
9220 
9221     if (Invalid) {
9222       NewFD->setInvalidDecl();
9223       if (FunctionTemplate)
9224         FunctionTemplate->setInvalidDecl();
9225     }
9226 
9227     // C++ [dcl.fct.spec]p5:
9228     //   The virtual specifier shall only be used in declarations of
9229     //   nonstatic class member functions that appear within a
9230     //   member-specification of a class declaration; see 10.3.
9231     //
9232     if (isVirtual && !NewFD->isInvalidDecl()) {
9233       if (!isVirtualOkay) {
9234         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9235              diag::err_virtual_non_function);
9236       } else if (!CurContext->isRecord()) {
9237         // 'virtual' was specified outside of the class.
9238         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9239              diag::err_virtual_out_of_class)
9240           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9241       } else if (NewFD->getDescribedFunctionTemplate()) {
9242         // C++ [temp.mem]p3:
9243         //  A member function template shall not be virtual.
9244         Diag(D.getDeclSpec().getVirtualSpecLoc(),
9245              diag::err_virtual_member_function_template)
9246           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9247       } else {
9248         // Okay: Add virtual to the method.
9249         NewFD->setVirtualAsWritten(true);
9250       }
9251 
9252       if (getLangOpts().CPlusPlus14 &&
9253           NewFD->getReturnType()->isUndeducedType())
9254         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9255     }
9256 
9257     if (getLangOpts().CPlusPlus14 &&
9258         (NewFD->isDependentContext() ||
9259          (isFriend && CurContext->isDependentContext())) &&
9260         NewFD->getReturnType()->isUndeducedType()) {
9261       // If the function template is referenced directly (for instance, as a
9262       // member of the current instantiation), pretend it has a dependent type.
9263       // This is not really justified by the standard, but is the only sane
9264       // thing to do.
9265       // FIXME: For a friend function, we have not marked the function as being
9266       // a friend yet, so 'isDependentContext' on the FD doesn't work.
9267       const FunctionProtoType *FPT =
9268           NewFD->getType()->castAs<FunctionProtoType>();
9269       QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9270       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9271                                              FPT->getExtProtoInfo()));
9272     }
9273 
9274     // C++ [dcl.fct.spec]p3:
9275     //  The inline specifier shall not appear on a block scope function
9276     //  declaration.
9277     if (isInline && !NewFD->isInvalidDecl()) {
9278       if (CurContext->isFunctionOrMethod()) {
9279         // 'inline' is not allowed on block scope function declaration.
9280         Diag(D.getDeclSpec().getInlineSpecLoc(),
9281              diag::err_inline_declaration_block_scope) << Name
9282           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9283       }
9284     }
9285 
9286     // C++ [dcl.fct.spec]p6:
9287     //  The explicit specifier shall be used only in the declaration of a
9288     //  constructor or conversion function within its class definition;
9289     //  see 12.3.1 and 12.3.2.
9290     if (hasExplicit && !NewFD->isInvalidDecl() &&
9291         !isa<CXXDeductionGuideDecl>(NewFD)) {
9292       if (!CurContext->isRecord()) {
9293         // 'explicit' was specified outside of the class.
9294         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9295              diag::err_explicit_out_of_class)
9296             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9297       } else if (!isa<CXXConstructorDecl>(NewFD) &&
9298                  !isa<CXXConversionDecl>(NewFD)) {
9299         // 'explicit' was specified on a function that wasn't a constructor
9300         // or conversion function.
9301         Diag(D.getDeclSpec().getExplicitSpecLoc(),
9302              diag::err_explicit_non_ctor_or_conv_function)
9303             << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9304       }
9305     }
9306 
9307     ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9308     if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9309       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9310       // are implicitly inline.
9311       NewFD->setImplicitlyInline();
9312 
9313       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9314       // be either constructors or to return a literal type. Therefore,
9315       // destructors cannot be declared constexpr.
9316       if (isa<CXXDestructorDecl>(NewFD) &&
9317           (!getLangOpts().CPlusPlus20 ||
9318            ConstexprKind == ConstexprSpecKind::Consteval)) {
9319         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9320             << static_cast<int>(ConstexprKind);
9321         NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9322                                     ? ConstexprSpecKind::Unspecified
9323                                     : ConstexprSpecKind::Constexpr);
9324       }
9325       // C++20 [dcl.constexpr]p2: An allocation function, or a
9326       // deallocation function shall not be declared with the consteval
9327       // specifier.
9328       if (ConstexprKind == ConstexprSpecKind::Consteval &&
9329           (NewFD->getOverloadedOperator() == OO_New ||
9330            NewFD->getOverloadedOperator() == OO_Array_New ||
9331            NewFD->getOverloadedOperator() == OO_Delete ||
9332            NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9333         Diag(D.getDeclSpec().getConstexprSpecLoc(),
9334              diag::err_invalid_consteval_decl_kind)
9335             << NewFD;
9336         NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9337       }
9338     }
9339 
9340     // If __module_private__ was specified, mark the function accordingly.
9341     if (D.getDeclSpec().isModulePrivateSpecified()) {
9342       if (isFunctionTemplateSpecialization) {
9343         SourceLocation ModulePrivateLoc
9344           = D.getDeclSpec().getModulePrivateSpecLoc();
9345         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9346           << 0
9347           << FixItHint::CreateRemoval(ModulePrivateLoc);
9348       } else {
9349         NewFD->setModulePrivate();
9350         if (FunctionTemplate)
9351           FunctionTemplate->setModulePrivate();
9352       }
9353     }
9354 
9355     if (isFriend) {
9356       if (FunctionTemplate) {
9357         FunctionTemplate->setObjectOfFriendDecl();
9358         FunctionTemplate->setAccess(AS_public);
9359       }
9360       NewFD->setObjectOfFriendDecl();
9361       NewFD->setAccess(AS_public);
9362     }
9363 
9364     // If a function is defined as defaulted or deleted, mark it as such now.
9365     // We'll do the relevant checks on defaulted / deleted functions later.
9366     switch (D.getFunctionDefinitionKind()) {
9367     case FunctionDefinitionKind::Declaration:
9368     case FunctionDefinitionKind::Definition:
9369       break;
9370 
9371     case FunctionDefinitionKind::Defaulted:
9372       NewFD->setDefaulted();
9373       break;
9374 
9375     case FunctionDefinitionKind::Deleted:
9376       NewFD->setDeletedAsWritten();
9377       break;
9378     }
9379 
9380     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9381         D.isFunctionDefinition()) {
9382       // C++ [class.mfct]p2:
9383       //   A member function may be defined (8.4) in its class definition, in
9384       //   which case it is an inline member function (7.1.2)
9385       NewFD->setImplicitlyInline();
9386     }
9387 
9388     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9389         !CurContext->isRecord()) {
9390       // C++ [class.static]p1:
9391       //   A data or function member of a class may be declared static
9392       //   in a class definition, in which case it is a static member of
9393       //   the class.
9394 
9395       // Complain about the 'static' specifier if it's on an out-of-line
9396       // member function definition.
9397 
9398       // MSVC permits the use of a 'static' storage specifier on an out-of-line
9399       // member function template declaration and class member template
9400       // declaration (MSVC versions before 2015), warn about this.
9401       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9402            ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9403              cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9404            (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9405            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9406         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9407     }
9408 
9409     // C++11 [except.spec]p15:
9410     //   A deallocation function with no exception-specification is treated
9411     //   as if it were specified with noexcept(true).
9412     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9413     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9414          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9415         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9416       NewFD->setType(Context.getFunctionType(
9417           FPT->getReturnType(), FPT->getParamTypes(),
9418           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9419   }
9420 
9421   // Filter out previous declarations that don't match the scope.
9422   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9423                        D.getCXXScopeSpec().isNotEmpty() ||
9424                        isMemberSpecialization ||
9425                        isFunctionTemplateSpecialization);
9426 
9427   // Handle GNU asm-label extension (encoded as an attribute).
9428   if (Expr *E = (Expr*) D.getAsmLabel()) {
9429     // The parser guarantees this is a string.
9430     StringLiteral *SE = cast<StringLiteral>(E);
9431     NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9432                                         /*IsLiteralLabel=*/true,
9433                                         SE->getStrTokenLoc(0)));
9434   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9435     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9436       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9437     if (I != ExtnameUndeclaredIdentifiers.end()) {
9438       if (isDeclExternC(NewFD)) {
9439         NewFD->addAttr(I->second);
9440         ExtnameUndeclaredIdentifiers.erase(I);
9441       } else
9442         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9443             << /*Variable*/0 << NewFD;
9444     }
9445   }
9446 
9447   // Copy the parameter declarations from the declarator D to the function
9448   // declaration NewFD, if they are available.  First scavenge them into Params.
9449   SmallVector<ParmVarDecl*, 16> Params;
9450   unsigned FTIIdx;
9451   if (D.isFunctionDeclarator(FTIIdx)) {
9452     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9453 
9454     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9455     // function that takes no arguments, not a function that takes a
9456     // single void argument.
9457     // We let through "const void" here because Sema::GetTypeForDeclarator
9458     // already checks for that case.
9459     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9460       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9461         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9462         assert(Param->getDeclContext() != NewFD && "Was set before ?");
9463         Param->setDeclContext(NewFD);
9464         Params.push_back(Param);
9465 
9466         if (Param->isInvalidDecl())
9467           NewFD->setInvalidDecl();
9468       }
9469     }
9470 
9471     if (!getLangOpts().CPlusPlus) {
9472       // In C, find all the tag declarations from the prototype and move them
9473       // into the function DeclContext. Remove them from the surrounding tag
9474       // injection context of the function, which is typically but not always
9475       // the TU.
9476       DeclContext *PrototypeTagContext =
9477           getTagInjectionContext(NewFD->getLexicalDeclContext());
9478       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9479         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9480 
9481         // We don't want to reparent enumerators. Look at their parent enum
9482         // instead.
9483         if (!TD) {
9484           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9485             TD = cast<EnumDecl>(ECD->getDeclContext());
9486         }
9487         if (!TD)
9488           continue;
9489         DeclContext *TagDC = TD->getLexicalDeclContext();
9490         if (!TagDC->containsDecl(TD))
9491           continue;
9492         TagDC->removeDecl(TD);
9493         TD->setDeclContext(NewFD);
9494         NewFD->addDecl(TD);
9495 
9496         // Preserve the lexical DeclContext if it is not the surrounding tag
9497         // injection context of the FD. In this example, the semantic context of
9498         // E will be f and the lexical context will be S, while both the
9499         // semantic and lexical contexts of S will be f:
9500         //   void f(struct S { enum E { a } f; } s);
9501         if (TagDC != PrototypeTagContext)
9502           TD->setLexicalDeclContext(TagDC);
9503       }
9504     }
9505   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9506     // When we're declaring a function with a typedef, typeof, etc as in the
9507     // following example, we'll need to synthesize (unnamed)
9508     // parameters for use in the declaration.
9509     //
9510     // @code
9511     // typedef void fn(int);
9512     // fn f;
9513     // @endcode
9514 
9515     // Synthesize a parameter for each argument type.
9516     for (const auto &AI : FT->param_types()) {
9517       ParmVarDecl *Param =
9518           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9519       Param->setScopeInfo(0, Params.size());
9520       Params.push_back(Param);
9521     }
9522   } else {
9523     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9524            "Should not need args for typedef of non-prototype fn");
9525   }
9526 
9527   // Finally, we know we have the right number of parameters, install them.
9528   NewFD->setParams(Params);
9529 
9530   if (D.getDeclSpec().isNoreturnSpecified())
9531     NewFD->addAttr(C11NoReturnAttr::Create(Context,
9532                                            D.getDeclSpec().getNoreturnSpecLoc(),
9533                                            AttributeCommonInfo::AS_Keyword));
9534 
9535   // Functions returning a variably modified type violate C99 6.7.5.2p2
9536   // because all functions have linkage.
9537   if (!NewFD->isInvalidDecl() &&
9538       NewFD->getReturnType()->isVariablyModifiedType()) {
9539     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9540     NewFD->setInvalidDecl();
9541   }
9542 
9543   // Apply an implicit SectionAttr if '#pragma clang section text' is active
9544   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9545       !NewFD->hasAttr<SectionAttr>())
9546     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9547         Context, PragmaClangTextSection.SectionName,
9548         PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9549 
9550   // Apply an implicit SectionAttr if #pragma code_seg is active.
9551   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9552       !NewFD->hasAttr<SectionAttr>()) {
9553     NewFD->addAttr(SectionAttr::CreateImplicit(
9554         Context, CodeSegStack.CurrentValue->getString(),
9555         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9556         SectionAttr::Declspec_allocate));
9557     if (UnifySection(CodeSegStack.CurrentValue->getString(),
9558                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9559                          ASTContext::PSF_Read,
9560                      NewFD))
9561       NewFD->dropAttr<SectionAttr>();
9562   }
9563 
9564   // Apply an implicit CodeSegAttr from class declspec or
9565   // apply an implicit SectionAttr from #pragma code_seg if active.
9566   if (!NewFD->hasAttr<CodeSegAttr>()) {
9567     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9568                                                                  D.isFunctionDefinition())) {
9569       NewFD->addAttr(SAttr);
9570     }
9571   }
9572 
9573   // Handle attributes.
9574   ProcessDeclAttributes(S, NewFD, D);
9575 
9576   if (getLangOpts().OpenCL) {
9577     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9578     // type declaration will generate a compilation error.
9579     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9580     if (AddressSpace != LangAS::Default) {
9581       Diag(NewFD->getLocation(),
9582            diag::err_opencl_return_value_with_address_space);
9583       NewFD->setInvalidDecl();
9584     }
9585   }
9586 
9587   if (!getLangOpts().CPlusPlus) {
9588     // Perform semantic checking on the function declaration.
9589     if (!NewFD->isInvalidDecl() && NewFD->isMain())
9590       CheckMain(NewFD, D.getDeclSpec());
9591 
9592     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9593       CheckMSVCRTEntryPoint(NewFD);
9594 
9595     if (!NewFD->isInvalidDecl())
9596       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9597                                                   isMemberSpecialization));
9598     else if (!Previous.empty())
9599       // Recover gracefully from an invalid redeclaration.
9600       D.setRedeclaration(true);
9601     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9602             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9603            "previous declaration set still overloaded");
9604 
9605     // Diagnose no-prototype function declarations with calling conventions that
9606     // don't support variadic calls. Only do this in C and do it after merging
9607     // possibly prototyped redeclarations.
9608     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9609     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9610       CallingConv CC = FT->getExtInfo().getCC();
9611       if (!supportsVariadicCall(CC)) {
9612         // Windows system headers sometimes accidentally use stdcall without
9613         // (void) parameters, so we relax this to a warning.
9614         int DiagID =
9615             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9616         Diag(NewFD->getLocation(), DiagID)
9617             << FunctionType::getNameForCallConv(CC);
9618       }
9619     }
9620 
9621    if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9622        NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9623      checkNonTrivialCUnion(NewFD->getReturnType(),
9624                            NewFD->getReturnTypeSourceRange().getBegin(),
9625                            NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9626   } else {
9627     // C++11 [replacement.functions]p3:
9628     //  The program's definitions shall not be specified as inline.
9629     //
9630     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9631     //
9632     // Suppress the diagnostic if the function is __attribute__((used)), since
9633     // that forces an external definition to be emitted.
9634     if (D.getDeclSpec().isInlineSpecified() &&
9635         NewFD->isReplaceableGlobalAllocationFunction() &&
9636         !NewFD->hasAttr<UsedAttr>())
9637       Diag(D.getDeclSpec().getInlineSpecLoc(),
9638            diag::ext_operator_new_delete_declared_inline)
9639         << NewFD->getDeclName();
9640 
9641     // If the declarator is a template-id, translate the parser's template
9642     // argument list into our AST format.
9643     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9644       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9645       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9646       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9647       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9648                                          TemplateId->NumArgs);
9649       translateTemplateArguments(TemplateArgsPtr,
9650                                  TemplateArgs);
9651 
9652       HasExplicitTemplateArgs = true;
9653 
9654       if (NewFD->isInvalidDecl()) {
9655         HasExplicitTemplateArgs = false;
9656       } else if (FunctionTemplate) {
9657         // Function template with explicit template arguments.
9658         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9659           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9660 
9661         HasExplicitTemplateArgs = false;
9662       } else {
9663         assert((isFunctionTemplateSpecialization ||
9664                 D.getDeclSpec().isFriendSpecified()) &&
9665                "should have a 'template<>' for this decl");
9666         // "friend void foo<>(int);" is an implicit specialization decl.
9667         isFunctionTemplateSpecialization = true;
9668       }
9669     } else if (isFriend && isFunctionTemplateSpecialization) {
9670       // This combination is only possible in a recovery case;  the user
9671       // wrote something like:
9672       //   template <> friend void foo(int);
9673       // which we're recovering from as if the user had written:
9674       //   friend void foo<>(int);
9675       // Go ahead and fake up a template id.
9676       HasExplicitTemplateArgs = true;
9677       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9678       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9679     }
9680 
9681     // We do not add HD attributes to specializations here because
9682     // they may have different constexpr-ness compared to their
9683     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9684     // may end up with different effective targets. Instead, a
9685     // specialization inherits its target attributes from its template
9686     // in the CheckFunctionTemplateSpecialization() call below.
9687     if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9688       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9689 
9690     // If it's a friend (and only if it's a friend), it's possible
9691     // that either the specialized function type or the specialized
9692     // template is dependent, and therefore matching will fail.  In
9693     // this case, don't check the specialization yet.
9694     if (isFunctionTemplateSpecialization && isFriend &&
9695         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9696          TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9697              TemplateArgs.arguments()))) {
9698       assert(HasExplicitTemplateArgs &&
9699              "friend function specialization without template args");
9700       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9701                                                        Previous))
9702         NewFD->setInvalidDecl();
9703     } else if (isFunctionTemplateSpecialization) {
9704       if (CurContext->isDependentContext() && CurContext->isRecord()
9705           && !isFriend) {
9706         isDependentClassScopeExplicitSpecialization = true;
9707       } else if (!NewFD->isInvalidDecl() &&
9708                  CheckFunctionTemplateSpecialization(
9709                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9710                      Previous))
9711         NewFD->setInvalidDecl();
9712 
9713       // C++ [dcl.stc]p1:
9714       //   A storage-class-specifier shall not be specified in an explicit
9715       //   specialization (14.7.3)
9716       FunctionTemplateSpecializationInfo *Info =
9717           NewFD->getTemplateSpecializationInfo();
9718       if (Info && SC != SC_None) {
9719         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9720           Diag(NewFD->getLocation(),
9721                diag::err_explicit_specialization_inconsistent_storage_class)
9722             << SC
9723             << FixItHint::CreateRemoval(
9724                                       D.getDeclSpec().getStorageClassSpecLoc());
9725 
9726         else
9727           Diag(NewFD->getLocation(),
9728                diag::ext_explicit_specialization_storage_class)
9729             << FixItHint::CreateRemoval(
9730                                       D.getDeclSpec().getStorageClassSpecLoc());
9731       }
9732     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9733       if (CheckMemberSpecialization(NewFD, Previous))
9734           NewFD->setInvalidDecl();
9735     }
9736 
9737     // Perform semantic checking on the function declaration.
9738     if (!isDependentClassScopeExplicitSpecialization) {
9739       if (!NewFD->isInvalidDecl() && NewFD->isMain())
9740         CheckMain(NewFD, D.getDeclSpec());
9741 
9742       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9743         CheckMSVCRTEntryPoint(NewFD);
9744 
9745       if (!NewFD->isInvalidDecl())
9746         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9747                                                     isMemberSpecialization));
9748       else if (!Previous.empty())
9749         // Recover gracefully from an invalid redeclaration.
9750         D.setRedeclaration(true);
9751     }
9752 
9753     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9754             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9755            "previous declaration set still overloaded");
9756 
9757     NamedDecl *PrincipalDecl = (FunctionTemplate
9758                                 ? cast<NamedDecl>(FunctionTemplate)
9759                                 : NewFD);
9760 
9761     if (isFriend && NewFD->getPreviousDecl()) {
9762       AccessSpecifier Access = AS_public;
9763       if (!NewFD->isInvalidDecl())
9764         Access = NewFD->getPreviousDecl()->getAccess();
9765 
9766       NewFD->setAccess(Access);
9767       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9768     }
9769 
9770     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9771         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9772       PrincipalDecl->setNonMemberOperator();
9773 
9774     // If we have a function template, check the template parameter
9775     // list. This will check and merge default template arguments.
9776     if (FunctionTemplate) {
9777       FunctionTemplateDecl *PrevTemplate =
9778                                      FunctionTemplate->getPreviousDecl();
9779       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9780                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9781                                     : nullptr,
9782                             D.getDeclSpec().isFriendSpecified()
9783                               ? (D.isFunctionDefinition()
9784                                    ? TPC_FriendFunctionTemplateDefinition
9785                                    : TPC_FriendFunctionTemplate)
9786                               : (D.getCXXScopeSpec().isSet() &&
9787                                  DC && DC->isRecord() &&
9788                                  DC->isDependentContext())
9789                                   ? TPC_ClassTemplateMember
9790                                   : TPC_FunctionTemplate);
9791     }
9792 
9793     if (NewFD->isInvalidDecl()) {
9794       // Ignore all the rest of this.
9795     } else if (!D.isRedeclaration()) {
9796       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9797                                        AddToScope };
9798       // Fake up an access specifier if it's supposed to be a class member.
9799       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9800         NewFD->setAccess(AS_public);
9801 
9802       // Qualified decls generally require a previous declaration.
9803       if (D.getCXXScopeSpec().isSet()) {
9804         // ...with the major exception of templated-scope or
9805         // dependent-scope friend declarations.
9806 
9807         // TODO: we currently also suppress this check in dependent
9808         // contexts because (1) the parameter depth will be off when
9809         // matching friend templates and (2) we might actually be
9810         // selecting a friend based on a dependent factor.  But there
9811         // are situations where these conditions don't apply and we
9812         // can actually do this check immediately.
9813         //
9814         // Unless the scope is dependent, it's always an error if qualified
9815         // redeclaration lookup found nothing at all. Diagnose that now;
9816         // nothing will diagnose that error later.
9817         if (isFriend &&
9818             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9819              (!Previous.empty() && CurContext->isDependentContext()))) {
9820           // ignore these
9821         } else if (NewFD->isCPUDispatchMultiVersion() ||
9822                    NewFD->isCPUSpecificMultiVersion()) {
9823           // ignore this, we allow the redeclaration behavior here to create new
9824           // versions of the function.
9825         } else {
9826           // The user tried to provide an out-of-line definition for a
9827           // function that is a member of a class or namespace, but there
9828           // was no such member function declared (C++ [class.mfct]p2,
9829           // C++ [namespace.memdef]p2). For example:
9830           //
9831           // class X {
9832           //   void f() const;
9833           // };
9834           //
9835           // void X::f() { } // ill-formed
9836           //
9837           // Complain about this problem, and attempt to suggest close
9838           // matches (e.g., those that differ only in cv-qualifiers and
9839           // whether the parameter types are references).
9840 
9841           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9842                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9843             AddToScope = ExtraArgs.AddToScope;
9844             return Result;
9845           }
9846         }
9847 
9848         // Unqualified local friend declarations are required to resolve
9849         // to something.
9850       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9851         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9852                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9853           AddToScope = ExtraArgs.AddToScope;
9854           return Result;
9855         }
9856       }
9857     } else if (!D.isFunctionDefinition() &&
9858                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9859                !isFriend && !isFunctionTemplateSpecialization &&
9860                !isMemberSpecialization) {
9861       // An out-of-line member function declaration must also be a
9862       // definition (C++ [class.mfct]p2).
9863       // Note that this is not the case for explicit specializations of
9864       // function templates or member functions of class templates, per
9865       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9866       // extension for compatibility with old SWIG code which likes to
9867       // generate them.
9868       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9869         << D.getCXXScopeSpec().getRange();
9870     }
9871   }
9872 
9873   // If this is the first declaration of a library builtin function, add
9874   // attributes as appropriate.
9875   if (!D.isRedeclaration() &&
9876       NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9877     if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9878       if (unsigned BuiltinID = II->getBuiltinID()) {
9879         if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9880           // Validate the type matches unless this builtin is specified as
9881           // matching regardless of its declared type.
9882           if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9883             NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9884           } else {
9885             ASTContext::GetBuiltinTypeError Error;
9886             LookupNecessaryTypesForBuiltin(S, BuiltinID);
9887             QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9888 
9889             if (!Error && !BuiltinType.isNull() &&
9890                 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9891                     NewFD->getType(), BuiltinType))
9892               NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9893           }
9894         } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9895                    Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9896           // FIXME: We should consider this a builtin only in the std namespace.
9897           NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9898         }
9899       }
9900     }
9901   }
9902 
9903   ProcessPragmaWeak(S, NewFD);
9904   checkAttributesAfterMerging(*this, *NewFD);
9905 
9906   AddKnownFunctionAttributes(NewFD);
9907 
9908   if (NewFD->hasAttr<OverloadableAttr>() &&
9909       !NewFD->getType()->getAs<FunctionProtoType>()) {
9910     Diag(NewFD->getLocation(),
9911          diag::err_attribute_overloadable_no_prototype)
9912       << NewFD;
9913 
9914     // Turn this into a variadic function with no parameters.
9915     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9916     FunctionProtoType::ExtProtoInfo EPI(
9917         Context.getDefaultCallingConvention(true, false));
9918     EPI.Variadic = true;
9919     EPI.ExtInfo = FT->getExtInfo();
9920 
9921     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9922     NewFD->setType(R);
9923   }
9924 
9925   // If there's a #pragma GCC visibility in scope, and this isn't a class
9926   // member, set the visibility of this function.
9927   if (!DC->isRecord() && NewFD->isExternallyVisible())
9928     AddPushedVisibilityAttribute(NewFD);
9929 
9930   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9931   // marking the function.
9932   AddCFAuditedAttribute(NewFD);
9933 
9934   // If this is a function definition, check if we have to apply optnone due to
9935   // a pragma.
9936   if(D.isFunctionDefinition())
9937     AddRangeBasedOptnone(NewFD);
9938 
9939   // If this is the first declaration of an extern C variable, update
9940   // the map of such variables.
9941   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9942       isIncompleteDeclExternC(*this, NewFD))
9943     RegisterLocallyScopedExternCDecl(NewFD, S);
9944 
9945   // Set this FunctionDecl's range up to the right paren.
9946   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9947 
9948   if (D.isRedeclaration() && !Previous.empty()) {
9949     NamedDecl *Prev = Previous.getRepresentativeDecl();
9950     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9951                                    isMemberSpecialization ||
9952                                        isFunctionTemplateSpecialization,
9953                                    D.isFunctionDefinition());
9954   }
9955 
9956   if (getLangOpts().CUDA) {
9957     IdentifierInfo *II = NewFD->getIdentifier();
9958     if (II && II->isStr(getCudaConfigureFuncName()) &&
9959         !NewFD->isInvalidDecl() &&
9960         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9961       if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9962         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9963             << getCudaConfigureFuncName();
9964       Context.setcudaConfigureCallDecl(NewFD);
9965     }
9966 
9967     // Variadic functions, other than a *declaration* of printf, are not allowed
9968     // in device-side CUDA code, unless someone passed
9969     // -fcuda-allow-variadic-functions.
9970     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9971         (NewFD->hasAttr<CUDADeviceAttr>() ||
9972          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9973         !(II && II->isStr("printf") && NewFD->isExternC() &&
9974           !D.isFunctionDefinition())) {
9975       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9976     }
9977   }
9978 
9979   MarkUnusedFileScopedDecl(NewFD);
9980 
9981 
9982 
9983   if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9984     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9985     if (SC == SC_Static) {
9986       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9987       D.setInvalidType();
9988     }
9989 
9990     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9991     if (!NewFD->getReturnType()->isVoidType()) {
9992       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9993       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9994           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9995                                 : FixItHint());
9996       D.setInvalidType();
9997     }
9998 
9999     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
10000     for (auto Param : NewFD->parameters())
10001       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10002 
10003     if (getLangOpts().OpenCLCPlusPlus) {
10004       if (DC->isRecord()) {
10005         Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10006         D.setInvalidType();
10007       }
10008       if (FunctionTemplate) {
10009         Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10010         D.setInvalidType();
10011       }
10012     }
10013   }
10014 
10015   if (getLangOpts().CPlusPlus) {
10016     if (FunctionTemplate) {
10017       if (NewFD->isInvalidDecl())
10018         FunctionTemplate->setInvalidDecl();
10019       return FunctionTemplate;
10020     }
10021 
10022     if (isMemberSpecialization && !NewFD->isInvalidDecl())
10023       CompleteMemberSpecialization(NewFD, Previous);
10024   }
10025 
10026   for (const ParmVarDecl *Param : NewFD->parameters()) {
10027     QualType PT = Param->getType();
10028 
10029     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10030     // types.
10031     if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
10032       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10033         QualType ElemTy = PipeTy->getElementType();
10034           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10035             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10036             D.setInvalidType();
10037           }
10038       }
10039     }
10040   }
10041 
10042   // Here we have an function template explicit specialization at class scope.
10043   // The actual specialization will be postponed to template instatiation
10044   // time via the ClassScopeFunctionSpecializationDecl node.
10045   if (isDependentClassScopeExplicitSpecialization) {
10046     ClassScopeFunctionSpecializationDecl *NewSpec =
10047                          ClassScopeFunctionSpecializationDecl::Create(
10048                                 Context, CurContext, NewFD->getLocation(),
10049                                 cast<CXXMethodDecl>(NewFD),
10050                                 HasExplicitTemplateArgs, TemplateArgs);
10051     CurContext->addDecl(NewSpec);
10052     AddToScope = false;
10053   }
10054 
10055   // Diagnose availability attributes. Availability cannot be used on functions
10056   // that are run during load/unload.
10057   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10058     if (NewFD->hasAttr<ConstructorAttr>()) {
10059       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10060           << 1;
10061       NewFD->dropAttr<AvailabilityAttr>();
10062     }
10063     if (NewFD->hasAttr<DestructorAttr>()) {
10064       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10065           << 2;
10066       NewFD->dropAttr<AvailabilityAttr>();
10067     }
10068   }
10069 
10070   // Diagnose no_builtin attribute on function declaration that are not a
10071   // definition.
10072   // FIXME: We should really be doing this in
10073   // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10074   // the FunctionDecl and at this point of the code
10075   // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10076   // because Sema::ActOnStartOfFunctionDef has not been called yet.
10077   if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10078     switch (D.getFunctionDefinitionKind()) {
10079     case FunctionDefinitionKind::Defaulted:
10080     case FunctionDefinitionKind::Deleted:
10081       Diag(NBA->getLocation(),
10082            diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10083           << NBA->getSpelling();
10084       break;
10085     case FunctionDefinitionKind::Declaration:
10086       Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10087           << NBA->getSpelling();
10088       break;
10089     case FunctionDefinitionKind::Definition:
10090       break;
10091     }
10092 
10093   return NewFD;
10094 }
10095 
10096 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
10097 /// when __declspec(code_seg) "is applied to a class, all member functions of
10098 /// the class and nested classes -- this includes compiler-generated special
10099 /// member functions -- are put in the specified segment."
10100 /// The actual behavior is a little more complicated. The Microsoft compiler
10101 /// won't check outer classes if there is an active value from #pragma code_seg.
10102 /// The CodeSeg is always applied from the direct parent but only from outer
10103 /// classes when the #pragma code_seg stack is empty. See:
10104 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10105 /// available since MS has removed the page.
10106 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10107   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10108   if (!Method)
10109     return nullptr;
10110   const CXXRecordDecl *Parent = Method->getParent();
10111   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10112     Attr *NewAttr = SAttr->clone(S.getASTContext());
10113     NewAttr->setImplicit(true);
10114     return NewAttr;
10115   }
10116 
10117   // The Microsoft compiler won't check outer classes for the CodeSeg
10118   // when the #pragma code_seg stack is active.
10119   if (S.CodeSegStack.CurrentValue)
10120    return nullptr;
10121 
10122   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10123     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10124       Attr *NewAttr = SAttr->clone(S.getASTContext());
10125       NewAttr->setImplicit(true);
10126       return NewAttr;
10127     }
10128   }
10129   return nullptr;
10130 }
10131 
10132 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10133 /// containing class. Otherwise it will return implicit SectionAttr if the
10134 /// function is a definition and there is an active value on CodeSegStack
10135 /// (from the current #pragma code-seg value).
10136 ///
10137 /// \param FD Function being declared.
10138 /// \param IsDefinition Whether it is a definition or just a declarartion.
10139 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10140 ///          nullptr if no attribute should be added.
10141 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10142                                                        bool IsDefinition) {
10143   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10144     return A;
10145   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10146       CodeSegStack.CurrentValue)
10147     return SectionAttr::CreateImplicit(
10148         getASTContext(), CodeSegStack.CurrentValue->getString(),
10149         CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10150         SectionAttr::Declspec_allocate);
10151   return nullptr;
10152 }
10153 
10154 /// Determines if we can perform a correct type check for \p D as a
10155 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10156 /// best-effort check.
10157 ///
10158 /// \param NewD The new declaration.
10159 /// \param OldD The old declaration.
10160 /// \param NewT The portion of the type of the new declaration to check.
10161 /// \param OldT The portion of the type of the old declaration to check.
10162 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10163                                           QualType NewT, QualType OldT) {
10164   if (!NewD->getLexicalDeclContext()->isDependentContext())
10165     return true;
10166 
10167   // For dependently-typed local extern declarations and friends, we can't
10168   // perform a correct type check in general until instantiation:
10169   //
10170   //   int f();
10171   //   template<typename T> void g() { T f(); }
10172   //
10173   // (valid if g() is only instantiated with T = int).
10174   if (NewT->isDependentType() &&
10175       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10176     return false;
10177 
10178   // Similarly, if the previous declaration was a dependent local extern
10179   // declaration, we don't really know its type yet.
10180   if (OldT->isDependentType() && OldD->isLocalExternDecl())
10181     return false;
10182 
10183   return true;
10184 }
10185 
10186 /// Checks if the new declaration declared in dependent context must be
10187 /// put in the same redeclaration chain as the specified declaration.
10188 ///
10189 /// \param D Declaration that is checked.
10190 /// \param PrevDecl Previous declaration found with proper lookup method for the
10191 ///                 same declaration name.
10192 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10193 ///          belongs to.
10194 ///
10195 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10196   if (!D->getLexicalDeclContext()->isDependentContext())
10197     return true;
10198 
10199   // Don't chain dependent friend function definitions until instantiation, to
10200   // permit cases like
10201   //
10202   //   void func();
10203   //   template<typename T> class C1 { friend void func() {} };
10204   //   template<typename T> class C2 { friend void func() {} };
10205   //
10206   // ... which is valid if only one of C1 and C2 is ever instantiated.
10207   //
10208   // FIXME: This need only apply to function definitions. For now, we proxy
10209   // this by checking for a file-scope function. We do not want this to apply
10210   // to friend declarations nominating member functions, because that gets in
10211   // the way of access checks.
10212   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10213     return false;
10214 
10215   auto *VD = dyn_cast<ValueDecl>(D);
10216   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10217   return !VD || !PrevVD ||
10218          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10219                                         PrevVD->getType());
10220 }
10221 
10222 /// Check the target attribute of the function for MultiVersion
10223 /// validity.
10224 ///
10225 /// Returns true if there was an error, false otherwise.
10226 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10227   const auto *TA = FD->getAttr<TargetAttr>();
10228   assert(TA && "MultiVersion Candidate requires a target attribute");
10229   ParsedTargetAttr ParseInfo = TA->parse();
10230   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10231   enum ErrType { Feature = 0, Architecture = 1 };
10232 
10233   if (!ParseInfo.Architecture.empty() &&
10234       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10235     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10236         << Architecture << ParseInfo.Architecture;
10237     return true;
10238   }
10239 
10240   for (const auto &Feat : ParseInfo.Features) {
10241     auto BareFeat = StringRef{Feat}.substr(1);
10242     if (Feat[0] == '-') {
10243       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10244           << Feature << ("no-" + BareFeat).str();
10245       return true;
10246     }
10247 
10248     if (!TargetInfo.validateCpuSupports(BareFeat) ||
10249         !TargetInfo.isValidFeatureName(BareFeat)) {
10250       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10251           << Feature << BareFeat;
10252       return true;
10253     }
10254   }
10255   return false;
10256 }
10257 
10258 // Provide a white-list of attributes that are allowed to be combined with
10259 // multiversion functions.
10260 static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10261                                            MultiVersionKind MVType) {
10262   // Note: this list/diagnosis must match the list in
10263   // checkMultiversionAttributesAllSame.
10264   switch (Kind) {
10265   default:
10266     return false;
10267   case attr::Used:
10268     return MVType == MultiVersionKind::Target;
10269   case attr::NonNull:
10270   case attr::NoThrow:
10271     return true;
10272   }
10273 }
10274 
10275 static bool checkNonMultiVersionCompatAttributes(Sema &S,
10276                                                  const FunctionDecl *FD,
10277                                                  const FunctionDecl *CausedFD,
10278                                                  MultiVersionKind MVType) {
10279   const auto Diagnose = [FD, CausedFD, MVType](Sema &S, const Attr *A) {
10280     S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10281         << static_cast<unsigned>(MVType) << A;
10282     if (CausedFD)
10283       S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10284     return true;
10285   };
10286 
10287   for (const Attr *A : FD->attrs()) {
10288     switch (A->getKind()) {
10289     case attr::CPUDispatch:
10290     case attr::CPUSpecific:
10291       if (MVType != MultiVersionKind::CPUDispatch &&
10292           MVType != MultiVersionKind::CPUSpecific)
10293         return Diagnose(S, A);
10294       break;
10295     case attr::Target:
10296       if (MVType != MultiVersionKind::Target)
10297         return Diagnose(S, A);
10298       break;
10299     case attr::TargetClones:
10300       if (MVType != MultiVersionKind::TargetClones)
10301         return Diagnose(S, A);
10302       break;
10303     default:
10304       if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10305         return Diagnose(S, A);
10306       break;
10307     }
10308   }
10309   return false;
10310 }
10311 
10312 bool Sema::areMultiversionVariantFunctionsCompatible(
10313     const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10314     const PartialDiagnostic &NoProtoDiagID,
10315     const PartialDiagnosticAt &NoteCausedDiagIDAt,
10316     const PartialDiagnosticAt &NoSupportDiagIDAt,
10317     const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10318     bool ConstexprSupported, bool CLinkageMayDiffer) {
10319   enum DoesntSupport {
10320     FuncTemplates = 0,
10321     VirtFuncs = 1,
10322     DeducedReturn = 2,
10323     Constructors = 3,
10324     Destructors = 4,
10325     DeletedFuncs = 5,
10326     DefaultedFuncs = 6,
10327     ConstexprFuncs = 7,
10328     ConstevalFuncs = 8,
10329     Lambda = 9,
10330   };
10331   enum Different {
10332     CallingConv = 0,
10333     ReturnType = 1,
10334     ConstexprSpec = 2,
10335     InlineSpec = 3,
10336     Linkage = 4,
10337     LanguageLinkage = 5,
10338   };
10339 
10340   if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10341       !OldFD->getType()->getAs<FunctionProtoType>()) {
10342     Diag(OldFD->getLocation(), NoProtoDiagID);
10343     Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10344     return true;
10345   }
10346 
10347   if (NoProtoDiagID.getDiagID() != 0 &&
10348       !NewFD->getType()->getAs<FunctionProtoType>())
10349     return Diag(NewFD->getLocation(), NoProtoDiagID);
10350 
10351   if (!TemplatesSupported &&
10352       NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10353     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10354            << FuncTemplates;
10355 
10356   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10357     if (NewCXXFD->isVirtual())
10358       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10359              << VirtFuncs;
10360 
10361     if (isa<CXXConstructorDecl>(NewCXXFD))
10362       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10363              << Constructors;
10364 
10365     if (isa<CXXDestructorDecl>(NewCXXFD))
10366       return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10367              << Destructors;
10368   }
10369 
10370   if (NewFD->isDeleted())
10371     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10372            << DeletedFuncs;
10373 
10374   if (NewFD->isDefaulted())
10375     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10376            << DefaultedFuncs;
10377 
10378   if (!ConstexprSupported && NewFD->isConstexpr())
10379     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10380            << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10381 
10382   QualType NewQType = Context.getCanonicalType(NewFD->getType());
10383   const auto *NewType = cast<FunctionType>(NewQType);
10384   QualType NewReturnType = NewType->getReturnType();
10385 
10386   if (NewReturnType->isUndeducedType())
10387     return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10388            << DeducedReturn;
10389 
10390   // Ensure the return type is identical.
10391   if (OldFD) {
10392     QualType OldQType = Context.getCanonicalType(OldFD->getType());
10393     const auto *OldType = cast<FunctionType>(OldQType);
10394     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10395     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10396 
10397     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10398       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10399 
10400     QualType OldReturnType = OldType->getReturnType();
10401 
10402     if (OldReturnType != NewReturnType)
10403       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10404 
10405     if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10406       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10407 
10408     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10409       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10410 
10411     if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10412       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10413 
10414     if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10415       return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10416 
10417     if (CheckEquivalentExceptionSpec(
10418             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10419             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10420       return true;
10421   }
10422   return false;
10423 }
10424 
10425 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10426                                              const FunctionDecl *NewFD,
10427                                              bool CausesMV,
10428                                              MultiVersionKind MVType) {
10429   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10430     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10431     if (OldFD)
10432       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10433     return true;
10434   }
10435 
10436   bool IsCPUSpecificCPUDispatchMVType =
10437       MVType == MultiVersionKind::CPUDispatch ||
10438       MVType == MultiVersionKind::CPUSpecific;
10439 
10440   if (CausesMV && OldFD &&
10441       checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10442     return true;
10443 
10444   if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10445     return true;
10446 
10447   // Only allow transition to MultiVersion if it hasn't been used.
10448   if (OldFD && CausesMV && OldFD->isUsed(false))
10449     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10450 
10451   return S.areMultiversionVariantFunctionsCompatible(
10452       OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10453       PartialDiagnosticAt(NewFD->getLocation(),
10454                           S.PDiag(diag::note_multiversioning_caused_here)),
10455       PartialDiagnosticAt(NewFD->getLocation(),
10456                           S.PDiag(diag::err_multiversion_doesnt_support)
10457                               << static_cast<unsigned>(MVType)),
10458       PartialDiagnosticAt(NewFD->getLocation(),
10459                           S.PDiag(diag::err_multiversion_diff)),
10460       /*TemplatesSupported=*/false,
10461       /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10462       /*CLinkageMayDiffer=*/false);
10463 }
10464 
10465 /// Check the validity of a multiversion function declaration that is the
10466 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10467 ///
10468 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10469 ///
10470 /// Returns true if there was an error, false otherwise.
10471 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10472                                            MultiVersionKind MVType,
10473                                            const TargetAttr *TA) {
10474   assert(MVType != MultiVersionKind::None &&
10475          "Function lacks multiversion attribute");
10476 
10477   // Target only causes MV if it is default, otherwise this is a normal
10478   // function.
10479   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10480     return false;
10481 
10482   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10483     FD->setInvalidDecl();
10484     return true;
10485   }
10486 
10487   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10488     FD->setInvalidDecl();
10489     return true;
10490   }
10491 
10492   FD->setIsMultiVersion();
10493   return false;
10494 }
10495 
10496 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10497   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10498     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10499       return true;
10500   }
10501 
10502   return false;
10503 }
10504 
10505 static bool CheckTargetCausesMultiVersioning(
10506     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10507     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10508     LookupResult &Previous) {
10509   const auto *OldTA = OldFD->getAttr<TargetAttr>();
10510   ParsedTargetAttr NewParsed = NewTA->parse();
10511   // Sort order doesn't matter, it just needs to be consistent.
10512   llvm::sort(NewParsed.Features);
10513 
10514   // If the old decl is NOT MultiVersioned yet, and we don't cause that
10515   // to change, this is a simple redeclaration.
10516   if (!NewTA->isDefaultVersion() &&
10517       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10518     return false;
10519 
10520   // Otherwise, this decl causes MultiVersioning.
10521   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10522     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10523     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10524     NewFD->setInvalidDecl();
10525     return true;
10526   }
10527 
10528   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10529                                        MultiVersionKind::Target)) {
10530     NewFD->setInvalidDecl();
10531     return true;
10532   }
10533 
10534   if (CheckMultiVersionValue(S, NewFD)) {
10535     NewFD->setInvalidDecl();
10536     return true;
10537   }
10538 
10539   // If this is 'default', permit the forward declaration.
10540   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10541     Redeclaration = true;
10542     OldDecl = OldFD;
10543     OldFD->setIsMultiVersion();
10544     NewFD->setIsMultiVersion();
10545     return false;
10546   }
10547 
10548   if (CheckMultiVersionValue(S, OldFD)) {
10549     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10550     NewFD->setInvalidDecl();
10551     return true;
10552   }
10553 
10554   ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10555 
10556   if (OldParsed == NewParsed) {
10557     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10558     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10559     NewFD->setInvalidDecl();
10560     return true;
10561   }
10562 
10563   for (const auto *FD : OldFD->redecls()) {
10564     const auto *CurTA = FD->getAttr<TargetAttr>();
10565     // We allow forward declarations before ANY multiversioning attributes, but
10566     // nothing after the fact.
10567     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10568         (!CurTA || CurTA->isInherited())) {
10569       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10570           << 0;
10571       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10572       NewFD->setInvalidDecl();
10573       return true;
10574     }
10575   }
10576 
10577   OldFD->setIsMultiVersion();
10578   NewFD->setIsMultiVersion();
10579   Redeclaration = false;
10580   MergeTypeWithPrevious = false;
10581   OldDecl = nullptr;
10582   Previous.clear();
10583   return false;
10584 }
10585 
10586 static bool MultiVersionTypesCompatible(MultiVersionKind Old,
10587                                         MultiVersionKind New) {
10588   if (Old == New || Old == MultiVersionKind::None ||
10589       New == MultiVersionKind::None)
10590     return true;
10591 
10592   return (Old == MultiVersionKind::CPUDispatch &&
10593           New == MultiVersionKind::CPUSpecific) ||
10594          (Old == MultiVersionKind::CPUSpecific &&
10595           New == MultiVersionKind::CPUDispatch);
10596 }
10597 
10598 /// Check the validity of a new function declaration being added to an existing
10599 /// multiversioned declaration collection.
10600 static bool CheckMultiVersionAdditionalDecl(
10601     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10602     MultiVersionKind NewMVType, const TargetAttr *NewTA,
10603     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10604     const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10605     bool &MergeTypeWithPrevious, LookupResult &Previous) {
10606 
10607   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10608   // Disallow mixing of multiversioning types.
10609   if (!MultiVersionTypesCompatible(OldMVType, NewMVType)) {
10610     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10611     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10612     NewFD->setInvalidDecl();
10613     return true;
10614   }
10615 
10616   ParsedTargetAttr NewParsed;
10617   if (NewTA) {
10618     NewParsed = NewTA->parse();
10619     llvm::sort(NewParsed.Features);
10620   }
10621 
10622   bool UseMemberUsingDeclRules =
10623       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10624 
10625   // Next, check ALL non-overloads to see if this is a redeclaration of a
10626   // previous member of the MultiVersion set.
10627   for (NamedDecl *ND : Previous) {
10628     FunctionDecl *CurFD = ND->getAsFunction();
10629     if (!CurFD)
10630       continue;
10631     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10632       continue;
10633 
10634     switch (NewMVType) {
10635     case MultiVersionKind::None:
10636       assert(OldMVType == MultiVersionKind::TargetClones &&
10637              "Only target_clones can be omitted in subsequent declarations");
10638       break;
10639     case MultiVersionKind::Target: {
10640       const auto *CurTA = CurFD->getAttr<TargetAttr>();
10641       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10642         NewFD->setIsMultiVersion();
10643         Redeclaration = true;
10644         OldDecl = ND;
10645         return false;
10646       }
10647 
10648       ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10649       if (CurParsed == NewParsed) {
10650         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10651         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10652         NewFD->setInvalidDecl();
10653         return true;
10654       }
10655       break;
10656     }
10657     case MultiVersionKind::TargetClones: {
10658       const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10659       Redeclaration = true;
10660       OldDecl = CurFD;
10661       MergeTypeWithPrevious = true;
10662       NewFD->setIsMultiVersion();
10663 
10664       if (CurClones && NewClones &&
10665           (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10666            !std::equal(CurClones->featuresStrs_begin(),
10667                        CurClones->featuresStrs_end(),
10668                        NewClones->featuresStrs_begin()))) {
10669         S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10670         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10671         NewFD->setInvalidDecl();
10672         return true;
10673       }
10674 
10675       return false;
10676     }
10677     case MultiVersionKind::CPUSpecific:
10678     case MultiVersionKind::CPUDispatch: {
10679       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10680       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10681       // Handle CPUDispatch/CPUSpecific versions.
10682       // Only 1 CPUDispatch function is allowed, this will make it go through
10683       // the redeclaration errors.
10684       if (NewMVType == MultiVersionKind::CPUDispatch &&
10685           CurFD->hasAttr<CPUDispatchAttr>()) {
10686         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10687             std::equal(
10688                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10689                 NewCPUDisp->cpus_begin(),
10690                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10691                   return Cur->getName() == New->getName();
10692                 })) {
10693           NewFD->setIsMultiVersion();
10694           Redeclaration = true;
10695           OldDecl = ND;
10696           return false;
10697         }
10698 
10699         // If the declarations don't match, this is an error condition.
10700         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10701         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10702         NewFD->setInvalidDecl();
10703         return true;
10704       }
10705       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10706 
10707         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10708             std::equal(
10709                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10710                 NewCPUSpec->cpus_begin(),
10711                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10712                   return Cur->getName() == New->getName();
10713                 })) {
10714           NewFD->setIsMultiVersion();
10715           Redeclaration = true;
10716           OldDecl = ND;
10717           return false;
10718         }
10719 
10720         // Only 1 version of CPUSpecific is allowed for each CPU.
10721         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10722           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10723             if (CurII == NewII) {
10724               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10725                   << NewII;
10726               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10727               NewFD->setInvalidDecl();
10728               return true;
10729             }
10730           }
10731         }
10732       }
10733       break;
10734     }
10735     }
10736   }
10737 
10738   // Else, this is simply a non-redecl case.  Checking the 'value' is only
10739   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10740   // handled in the attribute adding step.
10741   if (NewMVType == MultiVersionKind::Target &&
10742       CheckMultiVersionValue(S, NewFD)) {
10743     NewFD->setInvalidDecl();
10744     return true;
10745   }
10746 
10747   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10748                                        !OldFD->isMultiVersion(), NewMVType)) {
10749     NewFD->setInvalidDecl();
10750     return true;
10751   }
10752 
10753   // Permit forward declarations in the case where these two are compatible.
10754   if (!OldFD->isMultiVersion()) {
10755     OldFD->setIsMultiVersion();
10756     NewFD->setIsMultiVersion();
10757     Redeclaration = true;
10758     OldDecl = OldFD;
10759     return false;
10760   }
10761 
10762   NewFD->setIsMultiVersion();
10763   Redeclaration = false;
10764   MergeTypeWithPrevious = false;
10765   OldDecl = nullptr;
10766   Previous.clear();
10767   return false;
10768 }
10769 
10770 /// Check the validity of a mulitversion function declaration.
10771 /// Also sets the multiversion'ness' of the function itself.
10772 ///
10773 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10774 ///
10775 /// Returns true if there was an error, false otherwise.
10776 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10777                                       bool &Redeclaration, NamedDecl *&OldDecl,
10778                                       bool &MergeTypeWithPrevious,
10779                                       LookupResult &Previous) {
10780   const auto *NewTA = NewFD->getAttr<TargetAttr>();
10781   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10782   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10783   const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10784   MultiVersionKind MVType = NewFD->getMultiVersionKind();
10785 
10786   // Main isn't allowed to become a multiversion function, however it IS
10787   // permitted to have 'main' be marked with the 'target' optimization hint.
10788   if (NewFD->isMain()) {
10789     if (MVType != MultiVersionKind::None &&
10790         !(MVType == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10791       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10792       NewFD->setInvalidDecl();
10793       return true;
10794     }
10795     return false;
10796   }
10797 
10798   if (!OldDecl || !OldDecl->getAsFunction() ||
10799       OldDecl->getDeclContext()->getRedeclContext() !=
10800           NewFD->getDeclContext()->getRedeclContext()) {
10801     // If there's no previous declaration, AND this isn't attempting to cause
10802     // multiversioning, this isn't an error condition.
10803     if (MVType == MultiVersionKind::None)
10804       return false;
10805     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10806   }
10807 
10808   FunctionDecl *OldFD = OldDecl->getAsFunction();
10809 
10810   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10811     return false;
10812 
10813   // Multiversioned redeclarations aren't allowed to omit the attribute, except
10814   // for target_clones.
10815   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None &&
10816       OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) {
10817     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10818         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10819     NewFD->setInvalidDecl();
10820     return true;
10821   }
10822 
10823   if (!OldFD->isMultiVersion()) {
10824     switch (MVType) {
10825     case MultiVersionKind::Target:
10826       return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10827                                               Redeclaration, OldDecl,
10828                                               MergeTypeWithPrevious, Previous);
10829     case MultiVersionKind::TargetClones:
10830       if (OldFD->isUsed(false)) {
10831         NewFD->setInvalidDecl();
10832         return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10833       }
10834       OldFD->setIsMultiVersion();
10835       break;
10836     case MultiVersionKind::CPUDispatch:
10837     case MultiVersionKind::CPUSpecific:
10838     case MultiVersionKind::None:
10839       break;
10840     }
10841   }
10842   // Handle the target potentially causes multiversioning case.
10843   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10844     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10845                                             Redeclaration, OldDecl,
10846                                             MergeTypeWithPrevious, Previous);
10847 
10848   // At this point, we have a multiversion function decl (in OldFD) AND an
10849   // appropriate attribute in the current function decl.  Resolve that these are
10850   // still compatible with previous declarations.
10851   return CheckMultiVersionAdditionalDecl(
10852       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, NewClones,
10853       Redeclaration, OldDecl, MergeTypeWithPrevious, Previous);
10854 }
10855 
10856 /// Perform semantic checking of a new function declaration.
10857 ///
10858 /// Performs semantic analysis of the new function declaration
10859 /// NewFD. This routine performs all semantic checking that does not
10860 /// require the actual declarator involved in the declaration, and is
10861 /// used both for the declaration of functions as they are parsed
10862 /// (called via ActOnDeclarator) and for the declaration of functions
10863 /// that have been instantiated via C++ template instantiation (called
10864 /// via InstantiateDecl).
10865 ///
10866 /// \param IsMemberSpecialization whether this new function declaration is
10867 /// a member specialization (that replaces any definition provided by the
10868 /// previous declaration).
10869 ///
10870 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10871 ///
10872 /// \returns true if the function declaration is a redeclaration.
10873 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10874                                     LookupResult &Previous,
10875                                     bool IsMemberSpecialization) {
10876   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
10877          "Variably modified return types are not handled here");
10878 
10879   // Determine whether the type of this function should be merged with
10880   // a previous visible declaration. This never happens for functions in C++,
10881   // and always happens in C if the previous declaration was visible.
10882   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10883                                !Previous.isShadowed();
10884 
10885   bool Redeclaration = false;
10886   NamedDecl *OldDecl = nullptr;
10887   bool MayNeedOverloadableChecks = false;
10888 
10889   // Merge or overload the declaration with an existing declaration of
10890   // the same name, if appropriate.
10891   if (!Previous.empty()) {
10892     // Determine whether NewFD is an overload of PrevDecl or
10893     // a declaration that requires merging. If it's an overload,
10894     // there's no more work to do here; we'll just add the new
10895     // function to the scope.
10896     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10897       NamedDecl *Candidate = Previous.getRepresentativeDecl();
10898       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10899         Redeclaration = true;
10900         OldDecl = Candidate;
10901       }
10902     } else {
10903       MayNeedOverloadableChecks = true;
10904       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10905                             /*NewIsUsingDecl*/ false)) {
10906       case Ovl_Match:
10907         Redeclaration = true;
10908         break;
10909 
10910       case Ovl_NonFunction:
10911         Redeclaration = true;
10912         break;
10913 
10914       case Ovl_Overload:
10915         Redeclaration = false;
10916         break;
10917       }
10918     }
10919   }
10920 
10921   // Check for a previous extern "C" declaration with this name.
10922   if (!Redeclaration &&
10923       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10924     if (!Previous.empty()) {
10925       // This is an extern "C" declaration with the same name as a previous
10926       // declaration, and thus redeclares that entity...
10927       Redeclaration = true;
10928       OldDecl = Previous.getFoundDecl();
10929       MergeTypeWithPrevious = false;
10930 
10931       // ... except in the presence of __attribute__((overloadable)).
10932       if (OldDecl->hasAttr<OverloadableAttr>() ||
10933           NewFD->hasAttr<OverloadableAttr>()) {
10934         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10935           MayNeedOverloadableChecks = true;
10936           Redeclaration = false;
10937           OldDecl = nullptr;
10938         }
10939       }
10940     }
10941   }
10942 
10943   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10944                                 MergeTypeWithPrevious, Previous))
10945     return Redeclaration;
10946 
10947   // PPC MMA non-pointer types are not allowed as function return types.
10948   if (Context.getTargetInfo().getTriple().isPPC64() &&
10949       CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10950     NewFD->setInvalidDecl();
10951   }
10952 
10953   // C++11 [dcl.constexpr]p8:
10954   //   A constexpr specifier for a non-static member function that is not
10955   //   a constructor declares that member function to be const.
10956   //
10957   // This needs to be delayed until we know whether this is an out-of-line
10958   // definition of a static member function.
10959   //
10960   // This rule is not present in C++1y, so we produce a backwards
10961   // compatibility warning whenever it happens in C++11.
10962   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10963   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10964       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10965       !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10966     CXXMethodDecl *OldMD = nullptr;
10967     if (OldDecl)
10968       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10969     if (!OldMD || !OldMD->isStatic()) {
10970       const FunctionProtoType *FPT =
10971         MD->getType()->castAs<FunctionProtoType>();
10972       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10973       EPI.TypeQuals.addConst();
10974       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10975                                           FPT->getParamTypes(), EPI));
10976 
10977       // Warn that we did this, if we're not performing template instantiation.
10978       // In that case, we'll have warned already when the template was defined.
10979       if (!inTemplateInstantiation()) {
10980         SourceLocation AddConstLoc;
10981         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10982                 .IgnoreParens().getAs<FunctionTypeLoc>())
10983           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10984 
10985         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10986           << FixItHint::CreateInsertion(AddConstLoc, " const");
10987       }
10988     }
10989   }
10990 
10991   if (Redeclaration) {
10992     // NewFD and OldDecl represent declarations that need to be
10993     // merged.
10994     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10995       NewFD->setInvalidDecl();
10996       return Redeclaration;
10997     }
10998 
10999     Previous.clear();
11000     Previous.addDecl(OldDecl);
11001 
11002     if (FunctionTemplateDecl *OldTemplateDecl =
11003             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11004       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11005       FunctionTemplateDecl *NewTemplateDecl
11006         = NewFD->getDescribedFunctionTemplate();
11007       assert(NewTemplateDecl && "Template/non-template mismatch");
11008 
11009       // The call to MergeFunctionDecl above may have created some state in
11010       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11011       // can add it as a redeclaration.
11012       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11013 
11014       NewFD->setPreviousDeclaration(OldFD);
11015       if (NewFD->isCXXClassMember()) {
11016         NewFD->setAccess(OldTemplateDecl->getAccess());
11017         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11018       }
11019 
11020       // If this is an explicit specialization of a member that is a function
11021       // template, mark it as a member specialization.
11022       if (IsMemberSpecialization &&
11023           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11024         NewTemplateDecl->setMemberSpecialization();
11025         assert(OldTemplateDecl->isMemberSpecialization());
11026         // Explicit specializations of a member template do not inherit deleted
11027         // status from the parent member template that they are specializing.
11028         if (OldFD->isDeleted()) {
11029           // FIXME: This assert will not hold in the presence of modules.
11030           assert(OldFD->getCanonicalDecl() == OldFD);
11031           // FIXME: We need an update record for this AST mutation.
11032           OldFD->setDeletedAsWritten(false);
11033         }
11034       }
11035 
11036     } else {
11037       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11038         auto *OldFD = cast<FunctionDecl>(OldDecl);
11039         // This needs to happen first so that 'inline' propagates.
11040         NewFD->setPreviousDeclaration(OldFD);
11041         if (NewFD->isCXXClassMember())
11042           NewFD->setAccess(OldFD->getAccess());
11043       }
11044     }
11045   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11046              !NewFD->getAttr<OverloadableAttr>()) {
11047     assert((Previous.empty() ||
11048             llvm::any_of(Previous,
11049                          [](const NamedDecl *ND) {
11050                            return ND->hasAttr<OverloadableAttr>();
11051                          })) &&
11052            "Non-redecls shouldn't happen without overloadable present");
11053 
11054     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11055       const auto *FD = dyn_cast<FunctionDecl>(ND);
11056       return FD && !FD->hasAttr<OverloadableAttr>();
11057     });
11058 
11059     if (OtherUnmarkedIter != Previous.end()) {
11060       Diag(NewFD->getLocation(),
11061            diag::err_attribute_overloadable_multiple_unmarked_overloads);
11062       Diag((*OtherUnmarkedIter)->getLocation(),
11063            diag::note_attribute_overloadable_prev_overload)
11064           << false;
11065 
11066       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11067     }
11068   }
11069 
11070   if (LangOpts.OpenMP)
11071     ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11072 
11073   // Semantic checking for this function declaration (in isolation).
11074 
11075   if (getLangOpts().CPlusPlus) {
11076     // C++-specific checks.
11077     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11078       CheckConstructor(Constructor);
11079     } else if (CXXDestructorDecl *Destructor =
11080                 dyn_cast<CXXDestructorDecl>(NewFD)) {
11081       CXXRecordDecl *Record = Destructor->getParent();
11082       QualType ClassType = Context.getTypeDeclType(Record);
11083 
11084       // FIXME: Shouldn't we be able to perform this check even when the class
11085       // type is dependent? Both gcc and edg can handle that.
11086       if (!ClassType->isDependentType()) {
11087         DeclarationName Name
11088           = Context.DeclarationNames.getCXXDestructorName(
11089                                         Context.getCanonicalType(ClassType));
11090         if (NewFD->getDeclName() != Name) {
11091           Diag(NewFD->getLocation(), diag::err_destructor_name);
11092           NewFD->setInvalidDecl();
11093           return Redeclaration;
11094         }
11095       }
11096     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11097       if (auto *TD = Guide->getDescribedFunctionTemplate())
11098         CheckDeductionGuideTemplate(TD);
11099 
11100       // A deduction guide is not on the list of entities that can be
11101       // explicitly specialized.
11102       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11103         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11104             << /*explicit specialization*/ 1;
11105     }
11106 
11107     // Find any virtual functions that this function overrides.
11108     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11109       if (!Method->isFunctionTemplateSpecialization() &&
11110           !Method->getDescribedFunctionTemplate() &&
11111           Method->isCanonicalDecl()) {
11112         AddOverriddenMethods(Method->getParent(), Method);
11113       }
11114       if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11115         // C++2a [class.virtual]p6
11116         // A virtual method shall not have a requires-clause.
11117         Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11118              diag::err_constrained_virtual_method);
11119 
11120       if (Method->isStatic())
11121         checkThisInStaticMemberFunctionType(Method);
11122     }
11123 
11124     if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11125       ActOnConversionDeclarator(Conversion);
11126 
11127     // Extra checking for C++ overloaded operators (C++ [over.oper]).
11128     if (NewFD->isOverloadedOperator() &&
11129         CheckOverloadedOperatorDeclaration(NewFD)) {
11130       NewFD->setInvalidDecl();
11131       return Redeclaration;
11132     }
11133 
11134     // Extra checking for C++0x literal operators (C++0x [over.literal]).
11135     if (NewFD->getLiteralIdentifier() &&
11136         CheckLiteralOperatorDeclaration(NewFD)) {
11137       NewFD->setInvalidDecl();
11138       return Redeclaration;
11139     }
11140 
11141     // In C++, check default arguments now that we have merged decls. Unless
11142     // the lexical context is the class, because in this case this is done
11143     // during delayed parsing anyway.
11144     if (!CurContext->isRecord())
11145       CheckCXXDefaultArguments(NewFD);
11146 
11147     // If this function is declared as being extern "C", then check to see if
11148     // the function returns a UDT (class, struct, or union type) that is not C
11149     // compatible, and if it does, warn the user.
11150     // But, issue any diagnostic on the first declaration only.
11151     if (Previous.empty() && NewFD->isExternC()) {
11152       QualType R = NewFD->getReturnType();
11153       if (R->isIncompleteType() && !R->isVoidType())
11154         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11155             << NewFD << R;
11156       else if (!R.isPODType(Context) && !R->isVoidType() &&
11157                !R->isObjCObjectPointerType())
11158         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11159     }
11160 
11161     // C++1z [dcl.fct]p6:
11162     //   [...] whether the function has a non-throwing exception-specification
11163     //   [is] part of the function type
11164     //
11165     // This results in an ABI break between C++14 and C++17 for functions whose
11166     // declared type includes an exception-specification in a parameter or
11167     // return type. (Exception specifications on the function itself are OK in
11168     // most cases, and exception specifications are not permitted in most other
11169     // contexts where they could make it into a mangling.)
11170     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11171       auto HasNoexcept = [&](QualType T) -> bool {
11172         // Strip off declarator chunks that could be between us and a function
11173         // type. We don't need to look far, exception specifications are very
11174         // restricted prior to C++17.
11175         if (auto *RT = T->getAs<ReferenceType>())
11176           T = RT->getPointeeType();
11177         else if (T->isAnyPointerType())
11178           T = T->getPointeeType();
11179         else if (auto *MPT = T->getAs<MemberPointerType>())
11180           T = MPT->getPointeeType();
11181         if (auto *FPT = T->getAs<FunctionProtoType>())
11182           if (FPT->isNothrow())
11183             return true;
11184         return false;
11185       };
11186 
11187       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11188       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11189       for (QualType T : FPT->param_types())
11190         AnyNoexcept |= HasNoexcept(T);
11191       if (AnyNoexcept)
11192         Diag(NewFD->getLocation(),
11193              diag::warn_cxx17_compat_exception_spec_in_signature)
11194             << NewFD;
11195     }
11196 
11197     if (!Redeclaration && LangOpts.CUDA)
11198       checkCUDATargetOverload(NewFD, Previous);
11199   }
11200   return Redeclaration;
11201 }
11202 
11203 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11204   // C++11 [basic.start.main]p3:
11205   //   A program that [...] declares main to be inline, static or
11206   //   constexpr is ill-formed.
11207   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
11208   //   appear in a declaration of main.
11209   // static main is not an error under C99, but we should warn about it.
11210   // We accept _Noreturn main as an extension.
11211   if (FD->getStorageClass() == SC_Static)
11212     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11213          ? diag::err_static_main : diag::warn_static_main)
11214       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11215   if (FD->isInlineSpecified())
11216     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11217       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11218   if (DS.isNoreturnSpecified()) {
11219     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11220     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11221     Diag(NoreturnLoc, diag::ext_noreturn_main);
11222     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11223       << FixItHint::CreateRemoval(NoreturnRange);
11224   }
11225   if (FD->isConstexpr()) {
11226     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11227         << FD->isConsteval()
11228         << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11229     FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11230   }
11231 
11232   if (getLangOpts().OpenCL) {
11233     Diag(FD->getLocation(), diag::err_opencl_no_main)
11234         << FD->hasAttr<OpenCLKernelAttr>();
11235     FD->setInvalidDecl();
11236     return;
11237   }
11238 
11239   QualType T = FD->getType();
11240   assert(T->isFunctionType() && "function decl is not of function type");
11241   const FunctionType* FT = T->castAs<FunctionType>();
11242 
11243   // Set default calling convention for main()
11244   if (FT->getCallConv() != CC_C) {
11245     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11246     FD->setType(QualType(FT, 0));
11247     T = Context.getCanonicalType(FD->getType());
11248   }
11249 
11250   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11251     // In C with GNU extensions we allow main() to have non-integer return
11252     // type, but we should warn about the extension, and we disable the
11253     // implicit-return-zero rule.
11254 
11255     // GCC in C mode accepts qualified 'int'.
11256     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11257       FD->setHasImplicitReturnZero(true);
11258     else {
11259       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11260       SourceRange RTRange = FD->getReturnTypeSourceRange();
11261       if (RTRange.isValid())
11262         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11263             << FixItHint::CreateReplacement(RTRange, "int");
11264     }
11265   } else {
11266     // In C and C++, main magically returns 0 if you fall off the end;
11267     // set the flag which tells us that.
11268     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11269 
11270     // All the standards say that main() should return 'int'.
11271     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11272       FD->setHasImplicitReturnZero(true);
11273     else {
11274       // Otherwise, this is just a flat-out error.
11275       SourceRange RTRange = FD->getReturnTypeSourceRange();
11276       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11277           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11278                                 : FixItHint());
11279       FD->setInvalidDecl(true);
11280     }
11281   }
11282 
11283   // Treat protoless main() as nullary.
11284   if (isa<FunctionNoProtoType>(FT)) return;
11285 
11286   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11287   unsigned nparams = FTP->getNumParams();
11288   assert(FD->getNumParams() == nparams);
11289 
11290   bool HasExtraParameters = (nparams > 3);
11291 
11292   if (FTP->isVariadic()) {
11293     Diag(FD->getLocation(), diag::ext_variadic_main);
11294     // FIXME: if we had information about the location of the ellipsis, we
11295     // could add a FixIt hint to remove it as a parameter.
11296   }
11297 
11298   // Darwin passes an undocumented fourth argument of type char**.  If
11299   // other platforms start sprouting these, the logic below will start
11300   // getting shifty.
11301   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11302     HasExtraParameters = false;
11303 
11304   if (HasExtraParameters) {
11305     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11306     FD->setInvalidDecl(true);
11307     nparams = 3;
11308   }
11309 
11310   // FIXME: a lot of the following diagnostics would be improved
11311   // if we had some location information about types.
11312 
11313   QualType CharPP =
11314     Context.getPointerType(Context.getPointerType(Context.CharTy));
11315   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11316 
11317   for (unsigned i = 0; i < nparams; ++i) {
11318     QualType AT = FTP->getParamType(i);
11319 
11320     bool mismatch = true;
11321 
11322     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11323       mismatch = false;
11324     else if (Expected[i] == CharPP) {
11325       // As an extension, the following forms are okay:
11326       //   char const **
11327       //   char const * const *
11328       //   char * const *
11329 
11330       QualifierCollector qs;
11331       const PointerType* PT;
11332       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11333           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11334           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11335                               Context.CharTy)) {
11336         qs.removeConst();
11337         mismatch = !qs.empty();
11338       }
11339     }
11340 
11341     if (mismatch) {
11342       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11343       // TODO: suggest replacing given type with expected type
11344       FD->setInvalidDecl(true);
11345     }
11346   }
11347 
11348   if (nparams == 1 && !FD->isInvalidDecl()) {
11349     Diag(FD->getLocation(), diag::warn_main_one_arg);
11350   }
11351 
11352   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11353     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11354     FD->setInvalidDecl();
11355   }
11356 }
11357 
11358 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11359 
11360   // Default calling convention for main and wmain is __cdecl
11361   if (FD->getName() == "main" || FD->getName() == "wmain")
11362     return false;
11363 
11364   // Default calling convention for MinGW is __cdecl
11365   const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11366   if (T.isWindowsGNUEnvironment())
11367     return false;
11368 
11369   // Default calling convention for WinMain, wWinMain and DllMain
11370   // is __stdcall on 32 bit Windows
11371   if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11372     return true;
11373 
11374   return false;
11375 }
11376 
11377 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11378   QualType T = FD->getType();
11379   assert(T->isFunctionType() && "function decl is not of function type");
11380   const FunctionType *FT = T->castAs<FunctionType>();
11381 
11382   // Set an implicit return of 'zero' if the function can return some integral,
11383   // enumeration, pointer or nullptr type.
11384   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11385       FT->getReturnType()->isAnyPointerType() ||
11386       FT->getReturnType()->isNullPtrType())
11387     // DllMain is exempt because a return value of zero means it failed.
11388     if (FD->getName() != "DllMain")
11389       FD->setHasImplicitReturnZero(true);
11390 
11391   // Explicity specified calling conventions are applied to MSVC entry points
11392   if (!hasExplicitCallingConv(T)) {
11393     if (isDefaultStdCall(FD, *this)) {
11394       if (FT->getCallConv() != CC_X86StdCall) {
11395         FT = Context.adjustFunctionType(
11396             FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11397         FD->setType(QualType(FT, 0));
11398       }
11399     } else if (FT->getCallConv() != CC_C) {
11400       FT = Context.adjustFunctionType(FT,
11401                                       FT->getExtInfo().withCallingConv(CC_C));
11402       FD->setType(QualType(FT, 0));
11403     }
11404   }
11405 
11406   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11407     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11408     FD->setInvalidDecl();
11409   }
11410 }
11411 
11412 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11413   // FIXME: Need strict checking.  In C89, we need to check for
11414   // any assignment, increment, decrement, function-calls, or
11415   // commas outside of a sizeof.  In C99, it's the same list,
11416   // except that the aforementioned are allowed in unevaluated
11417   // expressions.  Everything else falls under the
11418   // "may accept other forms of constant expressions" exception.
11419   //
11420   // Regular C++ code will not end up here (exceptions: language extensions,
11421   // OpenCL C++ etc), so the constant expression rules there don't matter.
11422   if (Init->isValueDependent()) {
11423     assert(Init->containsErrors() &&
11424            "Dependent code should only occur in error-recovery path.");
11425     return true;
11426   }
11427   const Expr *Culprit;
11428   if (Init->isConstantInitializer(Context, false, &Culprit))
11429     return false;
11430   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11431     << Culprit->getSourceRange();
11432   return true;
11433 }
11434 
11435 namespace {
11436   // Visits an initialization expression to see if OrigDecl is evaluated in
11437   // its own initialization and throws a warning if it does.
11438   class SelfReferenceChecker
11439       : public EvaluatedExprVisitor<SelfReferenceChecker> {
11440     Sema &S;
11441     Decl *OrigDecl;
11442     bool isRecordType;
11443     bool isPODType;
11444     bool isReferenceType;
11445 
11446     bool isInitList;
11447     llvm::SmallVector<unsigned, 4> InitFieldIndex;
11448 
11449   public:
11450     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11451 
11452     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11453                                                     S(S), OrigDecl(OrigDecl) {
11454       isPODType = false;
11455       isRecordType = false;
11456       isReferenceType = false;
11457       isInitList = false;
11458       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11459         isPODType = VD->getType().isPODType(S.Context);
11460         isRecordType = VD->getType()->isRecordType();
11461         isReferenceType = VD->getType()->isReferenceType();
11462       }
11463     }
11464 
11465     // For most expressions, just call the visitor.  For initializer lists,
11466     // track the index of the field being initialized since fields are
11467     // initialized in order allowing use of previously initialized fields.
11468     void CheckExpr(Expr *E) {
11469       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11470       if (!InitList) {
11471         Visit(E);
11472         return;
11473       }
11474 
11475       // Track and increment the index here.
11476       isInitList = true;
11477       InitFieldIndex.push_back(0);
11478       for (auto Child : InitList->children()) {
11479         CheckExpr(cast<Expr>(Child));
11480         ++InitFieldIndex.back();
11481       }
11482       InitFieldIndex.pop_back();
11483     }
11484 
11485     // Returns true if MemberExpr is checked and no further checking is needed.
11486     // Returns false if additional checking is required.
11487     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11488       llvm::SmallVector<FieldDecl*, 4> Fields;
11489       Expr *Base = E;
11490       bool ReferenceField = false;
11491 
11492       // Get the field members used.
11493       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11494         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11495         if (!FD)
11496           return false;
11497         Fields.push_back(FD);
11498         if (FD->getType()->isReferenceType())
11499           ReferenceField = true;
11500         Base = ME->getBase()->IgnoreParenImpCasts();
11501       }
11502 
11503       // Keep checking only if the base Decl is the same.
11504       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11505       if (!DRE || DRE->getDecl() != OrigDecl)
11506         return false;
11507 
11508       // A reference field can be bound to an unininitialized field.
11509       if (CheckReference && !ReferenceField)
11510         return true;
11511 
11512       // Convert FieldDecls to their index number.
11513       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11514       for (const FieldDecl *I : llvm::reverse(Fields))
11515         UsedFieldIndex.push_back(I->getFieldIndex());
11516 
11517       // See if a warning is needed by checking the first difference in index
11518       // numbers.  If field being used has index less than the field being
11519       // initialized, then the use is safe.
11520       for (auto UsedIter = UsedFieldIndex.begin(),
11521                 UsedEnd = UsedFieldIndex.end(),
11522                 OrigIter = InitFieldIndex.begin(),
11523                 OrigEnd = InitFieldIndex.end();
11524            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11525         if (*UsedIter < *OrigIter)
11526           return true;
11527         if (*UsedIter > *OrigIter)
11528           break;
11529       }
11530 
11531       // TODO: Add a different warning which will print the field names.
11532       HandleDeclRefExpr(DRE);
11533       return true;
11534     }
11535 
11536     // For most expressions, the cast is directly above the DeclRefExpr.
11537     // For conditional operators, the cast can be outside the conditional
11538     // operator if both expressions are DeclRefExpr's.
11539     void HandleValue(Expr *E) {
11540       E = E->IgnoreParens();
11541       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11542         HandleDeclRefExpr(DRE);
11543         return;
11544       }
11545 
11546       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11547         Visit(CO->getCond());
11548         HandleValue(CO->getTrueExpr());
11549         HandleValue(CO->getFalseExpr());
11550         return;
11551       }
11552 
11553       if (BinaryConditionalOperator *BCO =
11554               dyn_cast<BinaryConditionalOperator>(E)) {
11555         Visit(BCO->getCond());
11556         HandleValue(BCO->getFalseExpr());
11557         return;
11558       }
11559 
11560       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11561         HandleValue(OVE->getSourceExpr());
11562         return;
11563       }
11564 
11565       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11566         if (BO->getOpcode() == BO_Comma) {
11567           Visit(BO->getLHS());
11568           HandleValue(BO->getRHS());
11569           return;
11570         }
11571       }
11572 
11573       if (isa<MemberExpr>(E)) {
11574         if (isInitList) {
11575           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11576                                       false /*CheckReference*/))
11577             return;
11578         }
11579 
11580         Expr *Base = E->IgnoreParenImpCasts();
11581         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11582           // Check for static member variables and don't warn on them.
11583           if (!isa<FieldDecl>(ME->getMemberDecl()))
11584             return;
11585           Base = ME->getBase()->IgnoreParenImpCasts();
11586         }
11587         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11588           HandleDeclRefExpr(DRE);
11589         return;
11590       }
11591 
11592       Visit(E);
11593     }
11594 
11595     // Reference types not handled in HandleValue are handled here since all
11596     // uses of references are bad, not just r-value uses.
11597     void VisitDeclRefExpr(DeclRefExpr *E) {
11598       if (isReferenceType)
11599         HandleDeclRefExpr(E);
11600     }
11601 
11602     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11603       if (E->getCastKind() == CK_LValueToRValue) {
11604         HandleValue(E->getSubExpr());
11605         return;
11606       }
11607 
11608       Inherited::VisitImplicitCastExpr(E);
11609     }
11610 
11611     void VisitMemberExpr(MemberExpr *E) {
11612       if (isInitList) {
11613         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11614           return;
11615       }
11616 
11617       // Don't warn on arrays since they can be treated as pointers.
11618       if (E->getType()->canDecayToPointerType()) return;
11619 
11620       // Warn when a non-static method call is followed by non-static member
11621       // field accesses, which is followed by a DeclRefExpr.
11622       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11623       bool Warn = (MD && !MD->isStatic());
11624       Expr *Base = E->getBase()->IgnoreParenImpCasts();
11625       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11626         if (!isa<FieldDecl>(ME->getMemberDecl()))
11627           Warn = false;
11628         Base = ME->getBase()->IgnoreParenImpCasts();
11629       }
11630 
11631       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11632         if (Warn)
11633           HandleDeclRefExpr(DRE);
11634         return;
11635       }
11636 
11637       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11638       // Visit that expression.
11639       Visit(Base);
11640     }
11641 
11642     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11643       Expr *Callee = E->getCallee();
11644 
11645       if (isa<UnresolvedLookupExpr>(Callee))
11646         return Inherited::VisitCXXOperatorCallExpr(E);
11647 
11648       Visit(Callee);
11649       for (auto Arg: E->arguments())
11650         HandleValue(Arg->IgnoreParenImpCasts());
11651     }
11652 
11653     void VisitUnaryOperator(UnaryOperator *E) {
11654       // For POD record types, addresses of its own members are well-defined.
11655       if (E->getOpcode() == UO_AddrOf && isRecordType &&
11656           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11657         if (!isPODType)
11658           HandleValue(E->getSubExpr());
11659         return;
11660       }
11661 
11662       if (E->isIncrementDecrementOp()) {
11663         HandleValue(E->getSubExpr());
11664         return;
11665       }
11666 
11667       Inherited::VisitUnaryOperator(E);
11668     }
11669 
11670     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11671 
11672     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11673       if (E->getConstructor()->isCopyConstructor()) {
11674         Expr *ArgExpr = E->getArg(0);
11675         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11676           if (ILE->getNumInits() == 1)
11677             ArgExpr = ILE->getInit(0);
11678         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11679           if (ICE->getCastKind() == CK_NoOp)
11680             ArgExpr = ICE->getSubExpr();
11681         HandleValue(ArgExpr);
11682         return;
11683       }
11684       Inherited::VisitCXXConstructExpr(E);
11685     }
11686 
11687     void VisitCallExpr(CallExpr *E) {
11688       // Treat std::move as a use.
11689       if (E->isCallToStdMove()) {
11690         HandleValue(E->getArg(0));
11691         return;
11692       }
11693 
11694       Inherited::VisitCallExpr(E);
11695     }
11696 
11697     void VisitBinaryOperator(BinaryOperator *E) {
11698       if (E->isCompoundAssignmentOp()) {
11699         HandleValue(E->getLHS());
11700         Visit(E->getRHS());
11701         return;
11702       }
11703 
11704       Inherited::VisitBinaryOperator(E);
11705     }
11706 
11707     // A custom visitor for BinaryConditionalOperator is needed because the
11708     // regular visitor would check the condition and true expression separately
11709     // but both point to the same place giving duplicate diagnostics.
11710     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11711       Visit(E->getCond());
11712       Visit(E->getFalseExpr());
11713     }
11714 
11715     void HandleDeclRefExpr(DeclRefExpr *DRE) {
11716       Decl* ReferenceDecl = DRE->getDecl();
11717       if (OrigDecl != ReferenceDecl) return;
11718       unsigned diag;
11719       if (isReferenceType) {
11720         diag = diag::warn_uninit_self_reference_in_reference_init;
11721       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11722         diag = diag::warn_static_self_reference_in_init;
11723       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11724                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11725                  DRE->getDecl()->getType()->isRecordType()) {
11726         diag = diag::warn_uninit_self_reference_in_init;
11727       } else {
11728         // Local variables will be handled by the CFG analysis.
11729         return;
11730       }
11731 
11732       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11733                             S.PDiag(diag)
11734                                 << DRE->getDecl() << OrigDecl->getLocation()
11735                                 << DRE->getSourceRange());
11736     }
11737   };
11738 
11739   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11740   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11741                                  bool DirectInit) {
11742     // Parameters arguments are occassionially constructed with itself,
11743     // for instance, in recursive functions.  Skip them.
11744     if (isa<ParmVarDecl>(OrigDecl))
11745       return;
11746 
11747     E = E->IgnoreParens();
11748 
11749     // Skip checking T a = a where T is not a record or reference type.
11750     // Doing so is a way to silence uninitialized warnings.
11751     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11752       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11753         if (ICE->getCastKind() == CK_LValueToRValue)
11754           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11755             if (DRE->getDecl() == OrigDecl)
11756               return;
11757 
11758     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11759   }
11760 } // end anonymous namespace
11761 
11762 namespace {
11763   // Simple wrapper to add the name of a variable or (if no variable is
11764   // available) a DeclarationName into a diagnostic.
11765   struct VarDeclOrName {
11766     VarDecl *VDecl;
11767     DeclarationName Name;
11768 
11769     friend const Sema::SemaDiagnosticBuilder &
11770     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11771       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11772     }
11773   };
11774 } // end anonymous namespace
11775 
11776 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11777                                             DeclarationName Name, QualType Type,
11778                                             TypeSourceInfo *TSI,
11779                                             SourceRange Range, bool DirectInit,
11780                                             Expr *Init) {
11781   bool IsInitCapture = !VDecl;
11782   assert((!VDecl || !VDecl->isInitCapture()) &&
11783          "init captures are expected to be deduced prior to initialization");
11784 
11785   VarDeclOrName VN{VDecl, Name};
11786 
11787   DeducedType *Deduced = Type->getContainedDeducedType();
11788   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11789 
11790   // C++11 [dcl.spec.auto]p3
11791   if (!Init) {
11792     assert(VDecl && "no init for init capture deduction?");
11793 
11794     // Except for class argument deduction, and then for an initializing
11795     // declaration only, i.e. no static at class scope or extern.
11796     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11797         VDecl->hasExternalStorage() ||
11798         VDecl->isStaticDataMember()) {
11799       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11800         << VDecl->getDeclName() << Type;
11801       return QualType();
11802     }
11803   }
11804 
11805   ArrayRef<Expr*> DeduceInits;
11806   if (Init)
11807     DeduceInits = Init;
11808 
11809   if (DirectInit) {
11810     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11811       DeduceInits = PL->exprs();
11812   }
11813 
11814   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11815     assert(VDecl && "non-auto type for init capture deduction?");
11816     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11817     InitializationKind Kind = InitializationKind::CreateForInit(
11818         VDecl->getLocation(), DirectInit, Init);
11819     // FIXME: Initialization should not be taking a mutable list of inits.
11820     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11821     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11822                                                        InitsCopy);
11823   }
11824 
11825   if (DirectInit) {
11826     if (auto *IL = dyn_cast<InitListExpr>(Init))
11827       DeduceInits = IL->inits();
11828   }
11829 
11830   // Deduction only works if we have exactly one source expression.
11831   if (DeduceInits.empty()) {
11832     // It isn't possible to write this directly, but it is possible to
11833     // end up in this situation with "auto x(some_pack...);"
11834     Diag(Init->getBeginLoc(), IsInitCapture
11835                                   ? diag::err_init_capture_no_expression
11836                                   : diag::err_auto_var_init_no_expression)
11837         << VN << Type << Range;
11838     return QualType();
11839   }
11840 
11841   if (DeduceInits.size() > 1) {
11842     Diag(DeduceInits[1]->getBeginLoc(),
11843          IsInitCapture ? diag::err_init_capture_multiple_expressions
11844                        : diag::err_auto_var_init_multiple_expressions)
11845         << VN << Type << Range;
11846     return QualType();
11847   }
11848 
11849   Expr *DeduceInit = DeduceInits[0];
11850   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11851     Diag(Init->getBeginLoc(), IsInitCapture
11852                                   ? diag::err_init_capture_paren_braces
11853                                   : diag::err_auto_var_init_paren_braces)
11854         << isa<InitListExpr>(Init) << VN << Type << Range;
11855     return QualType();
11856   }
11857 
11858   // Expressions default to 'id' when we're in a debugger.
11859   bool DefaultedAnyToId = false;
11860   if (getLangOpts().DebuggerCastResultToId &&
11861       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11862     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11863     if (Result.isInvalid()) {
11864       return QualType();
11865     }
11866     Init = Result.get();
11867     DefaultedAnyToId = true;
11868   }
11869 
11870   // C++ [dcl.decomp]p1:
11871   //   If the assignment-expression [...] has array type A and no ref-qualifier
11872   //   is present, e has type cv A
11873   if (VDecl && isa<DecompositionDecl>(VDecl) &&
11874       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11875       DeduceInit->getType()->isConstantArrayType())
11876     return Context.getQualifiedType(DeduceInit->getType(),
11877                                     Type.getQualifiers());
11878 
11879   QualType DeducedType;
11880   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11881     if (!IsInitCapture)
11882       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11883     else if (isa<InitListExpr>(Init))
11884       Diag(Range.getBegin(),
11885            diag::err_init_capture_deduction_failure_from_init_list)
11886           << VN
11887           << (DeduceInit->getType().isNull() ? TSI->getType()
11888                                              : DeduceInit->getType())
11889           << DeduceInit->getSourceRange();
11890     else
11891       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11892           << VN << TSI->getType()
11893           << (DeduceInit->getType().isNull() ? TSI->getType()
11894                                              : DeduceInit->getType())
11895           << DeduceInit->getSourceRange();
11896   }
11897 
11898   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11899   // 'id' instead of a specific object type prevents most of our usual
11900   // checks.
11901   // We only want to warn outside of template instantiations, though:
11902   // inside a template, the 'id' could have come from a parameter.
11903   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11904       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11905     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11906     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11907   }
11908 
11909   return DeducedType;
11910 }
11911 
11912 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11913                                          Expr *Init) {
11914   assert(!Init || !Init->containsErrors());
11915   QualType DeducedType = deduceVarTypeFromInitializer(
11916       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11917       VDecl->getSourceRange(), DirectInit, Init);
11918   if (DeducedType.isNull()) {
11919     VDecl->setInvalidDecl();
11920     return true;
11921   }
11922 
11923   VDecl->setType(DeducedType);
11924   assert(VDecl->isLinkageValid());
11925 
11926   // In ARC, infer lifetime.
11927   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11928     VDecl->setInvalidDecl();
11929 
11930   if (getLangOpts().OpenCL)
11931     deduceOpenCLAddressSpace(VDecl);
11932 
11933   // If this is a redeclaration, check that the type we just deduced matches
11934   // the previously declared type.
11935   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11936     // We never need to merge the type, because we cannot form an incomplete
11937     // array of auto, nor deduce such a type.
11938     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11939   }
11940 
11941   // Check the deduced type is valid for a variable declaration.
11942   CheckVariableDeclarationType(VDecl);
11943   return VDecl->isInvalidDecl();
11944 }
11945 
11946 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11947                                               SourceLocation Loc) {
11948   if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11949     Init = EWC->getSubExpr();
11950 
11951   if (auto *CE = dyn_cast<ConstantExpr>(Init))
11952     Init = CE->getSubExpr();
11953 
11954   QualType InitType = Init->getType();
11955   assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
11956           InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
11957          "shouldn't be called if type doesn't have a non-trivial C struct");
11958   if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11959     for (auto I : ILE->inits()) {
11960       if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11961           !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11962         continue;
11963       SourceLocation SL = I->getExprLoc();
11964       checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11965     }
11966     return;
11967   }
11968 
11969   if (isa<ImplicitValueInitExpr>(Init)) {
11970     if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11971       checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11972                             NTCUK_Init);
11973   } else {
11974     // Assume all other explicit initializers involving copying some existing
11975     // object.
11976     // TODO: ignore any explicit initializers where we can guarantee
11977     // copy-elision.
11978     if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11979       checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11980   }
11981 }
11982 
11983 namespace {
11984 
11985 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11986   // Ignore unavailable fields. A field can be marked as unavailable explicitly
11987   // in the source code or implicitly by the compiler if it is in a union
11988   // defined in a system header and has non-trivial ObjC ownership
11989   // qualifications. We don't want those fields to participate in determining
11990   // whether the containing union is non-trivial.
11991   return FD->hasAttr<UnavailableAttr>();
11992 }
11993 
11994 struct DiagNonTrivalCUnionDefaultInitializeVisitor
11995     : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11996                                     void> {
11997   using Super =
11998       DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11999                                     void>;
12000 
12001   DiagNonTrivalCUnionDefaultInitializeVisitor(
12002       QualType OrigTy, SourceLocation OrigLoc,
12003       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12004       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12005 
12006   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12007                      const FieldDecl *FD, bool InNonTrivialUnion) {
12008     if (const auto *AT = S.Context.getAsArrayType(QT))
12009       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12010                                      InNonTrivialUnion);
12011     return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12012   }
12013 
12014   void visitARCStrong(QualType QT, const FieldDecl *FD,
12015                       bool InNonTrivialUnion) {
12016     if (InNonTrivialUnion)
12017       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12018           << 1 << 0 << QT << FD->getName();
12019   }
12020 
12021   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12022     if (InNonTrivialUnion)
12023       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12024           << 1 << 0 << QT << FD->getName();
12025   }
12026 
12027   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12028     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12029     if (RD->isUnion()) {
12030       if (OrigLoc.isValid()) {
12031         bool IsUnion = false;
12032         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12033           IsUnion = OrigRD->isUnion();
12034         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12035             << 0 << OrigTy << IsUnion << UseContext;
12036         // Reset OrigLoc so that this diagnostic is emitted only once.
12037         OrigLoc = SourceLocation();
12038       }
12039       InNonTrivialUnion = true;
12040     }
12041 
12042     if (InNonTrivialUnion)
12043       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12044           << 0 << 0 << QT.getUnqualifiedType() << "";
12045 
12046     for (const FieldDecl *FD : RD->fields())
12047       if (!shouldIgnoreForRecordTriviality(FD))
12048         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12049   }
12050 
12051   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12052 
12053   // The non-trivial C union type or the struct/union type that contains a
12054   // non-trivial C union.
12055   QualType OrigTy;
12056   SourceLocation OrigLoc;
12057   Sema::NonTrivialCUnionContext UseContext;
12058   Sema &S;
12059 };
12060 
12061 struct DiagNonTrivalCUnionDestructedTypeVisitor
12062     : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12063   using Super =
12064       DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
12065 
12066   DiagNonTrivalCUnionDestructedTypeVisitor(
12067       QualType OrigTy, SourceLocation OrigLoc,
12068       Sema::NonTrivialCUnionContext UseContext, Sema &S)
12069       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12070 
12071   void visitWithKind(QualType::DestructionKind DK, QualType QT,
12072                      const FieldDecl *FD, bool InNonTrivialUnion) {
12073     if (const auto *AT = S.Context.getAsArrayType(QT))
12074       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12075                                      InNonTrivialUnion);
12076     return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12077   }
12078 
12079   void visitARCStrong(QualType QT, const FieldDecl *FD,
12080                       bool InNonTrivialUnion) {
12081     if (InNonTrivialUnion)
12082       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12083           << 1 << 1 << QT << FD->getName();
12084   }
12085 
12086   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12087     if (InNonTrivialUnion)
12088       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12089           << 1 << 1 << QT << FD->getName();
12090   }
12091 
12092   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12093     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12094     if (RD->isUnion()) {
12095       if (OrigLoc.isValid()) {
12096         bool IsUnion = false;
12097         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12098           IsUnion = OrigRD->isUnion();
12099         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12100             << 1 << OrigTy << IsUnion << UseContext;
12101         // Reset OrigLoc so that this diagnostic is emitted only once.
12102         OrigLoc = SourceLocation();
12103       }
12104       InNonTrivialUnion = true;
12105     }
12106 
12107     if (InNonTrivialUnion)
12108       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12109           << 0 << 1 << QT.getUnqualifiedType() << "";
12110 
12111     for (const FieldDecl *FD : RD->fields())
12112       if (!shouldIgnoreForRecordTriviality(FD))
12113         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12114   }
12115 
12116   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12117   void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12118                           bool InNonTrivialUnion) {}
12119 
12120   // The non-trivial C union type or the struct/union type that contains a
12121   // non-trivial C union.
12122   QualType OrigTy;
12123   SourceLocation OrigLoc;
12124   Sema::NonTrivialCUnionContext UseContext;
12125   Sema &S;
12126 };
12127 
12128 struct DiagNonTrivalCUnionCopyVisitor
12129     : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12130   using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12131 
12132   DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12133                                  Sema::NonTrivialCUnionContext UseContext,
12134                                  Sema &S)
12135       : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12136 
12137   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12138                      const FieldDecl *FD, bool InNonTrivialUnion) {
12139     if (const auto *AT = S.Context.getAsArrayType(QT))
12140       return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12141                                      InNonTrivialUnion);
12142     return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12143   }
12144 
12145   void visitARCStrong(QualType QT, const FieldDecl *FD,
12146                       bool InNonTrivialUnion) {
12147     if (InNonTrivialUnion)
12148       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12149           << 1 << 2 << QT << FD->getName();
12150   }
12151 
12152   void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12153     if (InNonTrivialUnion)
12154       S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12155           << 1 << 2 << QT << FD->getName();
12156   }
12157 
12158   void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12159     const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12160     if (RD->isUnion()) {
12161       if (OrigLoc.isValid()) {
12162         bool IsUnion = false;
12163         if (auto *OrigRD = OrigTy->getAsRecordDecl())
12164           IsUnion = OrigRD->isUnion();
12165         S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12166             << 2 << OrigTy << IsUnion << UseContext;
12167         // Reset OrigLoc so that this diagnostic is emitted only once.
12168         OrigLoc = SourceLocation();
12169       }
12170       InNonTrivialUnion = true;
12171     }
12172 
12173     if (InNonTrivialUnion)
12174       S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12175           << 0 << 2 << QT.getUnqualifiedType() << "";
12176 
12177     for (const FieldDecl *FD : RD->fields())
12178       if (!shouldIgnoreForRecordTriviality(FD))
12179         asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12180   }
12181 
12182   void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12183                 const FieldDecl *FD, bool InNonTrivialUnion) {}
12184   void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12185   void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12186                             bool InNonTrivialUnion) {}
12187 
12188   // The non-trivial C union type or the struct/union type that contains a
12189   // non-trivial C union.
12190   QualType OrigTy;
12191   SourceLocation OrigLoc;
12192   Sema::NonTrivialCUnionContext UseContext;
12193   Sema &S;
12194 };
12195 
12196 } // namespace
12197 
12198 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12199                                  NonTrivialCUnionContext UseContext,
12200                                  unsigned NonTrivialKind) {
12201   assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12202           QT.hasNonTrivialToPrimitiveDestructCUnion() ||
12203           QT.hasNonTrivialToPrimitiveCopyCUnion()) &&
12204          "shouldn't be called if type doesn't have a non-trivial C union");
12205 
12206   if ((NonTrivialKind & NTCUK_Init) &&
12207       QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12208     DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12209         .visit(QT, nullptr, false);
12210   if ((NonTrivialKind & NTCUK_Destruct) &&
12211       QT.hasNonTrivialToPrimitiveDestructCUnion())
12212     DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12213         .visit(QT, nullptr, false);
12214   if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12215     DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12216         .visit(QT, nullptr, false);
12217 }
12218 
12219 /// AddInitializerToDecl - Adds the initializer Init to the
12220 /// declaration dcl. If DirectInit is true, this is C++ direct
12221 /// initialization rather than copy initialization.
12222 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12223   // If there is no declaration, there was an error parsing it.  Just ignore
12224   // the initializer.
12225   if (!RealDecl || RealDecl->isInvalidDecl()) {
12226     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12227     return;
12228   }
12229 
12230   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12231     // Pure-specifiers are handled in ActOnPureSpecifier.
12232     Diag(Method->getLocation(), diag::err_member_function_initialization)
12233       << Method->getDeclName() << Init->getSourceRange();
12234     Method->setInvalidDecl();
12235     return;
12236   }
12237 
12238   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12239   if (!VDecl) {
12240     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12241     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12242     RealDecl->setInvalidDecl();
12243     return;
12244   }
12245 
12246   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12247   if (VDecl->getType()->isUndeducedType()) {
12248     // Attempt typo correction early so that the type of the init expression can
12249     // be deduced based on the chosen correction if the original init contains a
12250     // TypoExpr.
12251     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12252     if (!Res.isUsable()) {
12253       // There are unresolved typos in Init, just drop them.
12254       // FIXME: improve the recovery strategy to preserve the Init.
12255       RealDecl->setInvalidDecl();
12256       return;
12257     }
12258     if (Res.get()->containsErrors()) {
12259       // Invalidate the decl as we don't know the type for recovery-expr yet.
12260       RealDecl->setInvalidDecl();
12261       VDecl->setInit(Res.get());
12262       return;
12263     }
12264     Init = Res.get();
12265 
12266     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12267       return;
12268   }
12269 
12270   // dllimport cannot be used on variable definitions.
12271   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12272     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12273     VDecl->setInvalidDecl();
12274     return;
12275   }
12276 
12277   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12278     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12279     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12280     VDecl->setInvalidDecl();
12281     return;
12282   }
12283 
12284   if (!VDecl->getType()->isDependentType()) {
12285     // A definition must end up with a complete type, which means it must be
12286     // complete with the restriction that an array type might be completed by
12287     // the initializer; note that later code assumes this restriction.
12288     QualType BaseDeclType = VDecl->getType();
12289     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12290       BaseDeclType = Array->getElementType();
12291     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12292                             diag::err_typecheck_decl_incomplete_type)) {
12293       RealDecl->setInvalidDecl();
12294       return;
12295     }
12296 
12297     // The variable can not have an abstract class type.
12298     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12299                                diag::err_abstract_type_in_decl,
12300                                AbstractVariableType))
12301       VDecl->setInvalidDecl();
12302   }
12303 
12304   // If adding the initializer will turn this declaration into a definition,
12305   // and we already have a definition for this variable, diagnose or otherwise
12306   // handle the situation.
12307   if (VarDecl *Def = VDecl->getDefinition())
12308     if (Def != VDecl &&
12309         (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12310         !VDecl->isThisDeclarationADemotedDefinition() &&
12311         checkVarDeclRedefinition(Def, VDecl))
12312       return;
12313 
12314   if (getLangOpts().CPlusPlus) {
12315     // C++ [class.static.data]p4
12316     //   If a static data member is of const integral or const
12317     //   enumeration type, its declaration in the class definition can
12318     //   specify a constant-initializer which shall be an integral
12319     //   constant expression (5.19). In that case, the member can appear
12320     //   in integral constant expressions. The member shall still be
12321     //   defined in a namespace scope if it is used in the program and the
12322     //   namespace scope definition shall not contain an initializer.
12323     //
12324     // We already performed a redefinition check above, but for static
12325     // data members we also need to check whether there was an in-class
12326     // declaration with an initializer.
12327     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12328       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12329           << VDecl->getDeclName();
12330       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12331            diag::note_previous_initializer)
12332           << 0;
12333       return;
12334     }
12335 
12336     if (VDecl->hasLocalStorage())
12337       setFunctionHasBranchProtectedScope();
12338 
12339     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12340       VDecl->setInvalidDecl();
12341       return;
12342     }
12343   }
12344 
12345   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12346   // a kernel function cannot be initialized."
12347   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12348     Diag(VDecl->getLocation(), diag::err_local_cant_init);
12349     VDecl->setInvalidDecl();
12350     return;
12351   }
12352 
12353   // The LoaderUninitialized attribute acts as a definition (of undef).
12354   if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12355     Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12356     VDecl->setInvalidDecl();
12357     return;
12358   }
12359 
12360   // Get the decls type and save a reference for later, since
12361   // CheckInitializerTypes may change it.
12362   QualType DclT = VDecl->getType(), SavT = DclT;
12363 
12364   // Expressions default to 'id' when we're in a debugger
12365   // and we are assigning it to a variable of Objective-C pointer type.
12366   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12367       Init->getType() == Context.UnknownAnyTy) {
12368     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12369     if (Result.isInvalid()) {
12370       VDecl->setInvalidDecl();
12371       return;
12372     }
12373     Init = Result.get();
12374   }
12375 
12376   // Perform the initialization.
12377   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12378   if (!VDecl->isInvalidDecl()) {
12379     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12380     InitializationKind Kind = InitializationKind::CreateForInit(
12381         VDecl->getLocation(), DirectInit, Init);
12382 
12383     MultiExprArg Args = Init;
12384     if (CXXDirectInit)
12385       Args = MultiExprArg(CXXDirectInit->getExprs(),
12386                           CXXDirectInit->getNumExprs());
12387 
12388     // Try to correct any TypoExprs in the initialization arguments.
12389     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12390       ExprResult Res = CorrectDelayedTyposInExpr(
12391           Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12392           [this, Entity, Kind](Expr *E) {
12393             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12394             return Init.Failed() ? ExprError() : E;
12395           });
12396       if (Res.isInvalid()) {
12397         VDecl->setInvalidDecl();
12398       } else if (Res.get() != Args[Idx]) {
12399         Args[Idx] = Res.get();
12400       }
12401     }
12402     if (VDecl->isInvalidDecl())
12403       return;
12404 
12405     InitializationSequence InitSeq(*this, Entity, Kind, Args,
12406                                    /*TopLevelOfInitList=*/false,
12407                                    /*TreatUnavailableAsInvalid=*/false);
12408     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12409     if (Result.isInvalid()) {
12410       // If the provided initializer fails to initialize the var decl,
12411       // we attach a recovery expr for better recovery.
12412       auto RecoveryExpr =
12413           CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12414       if (RecoveryExpr.get())
12415         VDecl->setInit(RecoveryExpr.get());
12416       return;
12417     }
12418 
12419     Init = Result.getAs<Expr>();
12420   }
12421 
12422   // Check for self-references within variable initializers.
12423   // Variables declared within a function/method body (except for references)
12424   // are handled by a dataflow analysis.
12425   // This is undefined behavior in C++, but valid in C.
12426   if (getLangOpts().CPlusPlus)
12427     if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12428         VDecl->getType()->isReferenceType())
12429       CheckSelfReference(*this, RealDecl, Init, DirectInit);
12430 
12431   // If the type changed, it means we had an incomplete type that was
12432   // completed by the initializer. For example:
12433   //   int ary[] = { 1, 3, 5 };
12434   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12435   if (!VDecl->isInvalidDecl() && (DclT != SavT))
12436     VDecl->setType(DclT);
12437 
12438   if (!VDecl->isInvalidDecl()) {
12439     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12440 
12441     if (VDecl->hasAttr<BlocksAttr>())
12442       checkRetainCycles(VDecl, Init);
12443 
12444     // It is safe to assign a weak reference into a strong variable.
12445     // Although this code can still have problems:
12446     //   id x = self.weakProp;
12447     //   id y = self.weakProp;
12448     // we do not warn to warn spuriously when 'x' and 'y' are on separate
12449     // paths through the function. This should be revisited if
12450     // -Wrepeated-use-of-weak is made flow-sensitive.
12451     if (FunctionScopeInfo *FSI = getCurFunction())
12452       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12453            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12454           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12455                            Init->getBeginLoc()))
12456         FSI->markSafeWeakUse(Init);
12457   }
12458 
12459   // The initialization is usually a full-expression.
12460   //
12461   // FIXME: If this is a braced initialization of an aggregate, it is not
12462   // an expression, and each individual field initializer is a separate
12463   // full-expression. For instance, in:
12464   //
12465   //   struct Temp { ~Temp(); };
12466   //   struct S { S(Temp); };
12467   //   struct T { S a, b; } t = { Temp(), Temp() }
12468   //
12469   // we should destroy the first Temp before constructing the second.
12470   ExprResult Result =
12471       ActOnFinishFullExpr(Init, VDecl->getLocation(),
12472                           /*DiscardedValue*/ false, VDecl->isConstexpr());
12473   if (Result.isInvalid()) {
12474     VDecl->setInvalidDecl();
12475     return;
12476   }
12477   Init = Result.get();
12478 
12479   // Attach the initializer to the decl.
12480   VDecl->setInit(Init);
12481 
12482   if (VDecl->isLocalVarDecl()) {
12483     // Don't check the initializer if the declaration is malformed.
12484     if (VDecl->isInvalidDecl()) {
12485       // do nothing
12486 
12487     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12488     // This is true even in C++ for OpenCL.
12489     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12490       CheckForConstantInitializer(Init, DclT);
12491 
12492     // Otherwise, C++ does not restrict the initializer.
12493     } else if (getLangOpts().CPlusPlus) {
12494       // do nothing
12495 
12496     // C99 6.7.8p4: All the expressions in an initializer for an object that has
12497     // static storage duration shall be constant expressions or string literals.
12498     } else if (VDecl->getStorageClass() == SC_Static) {
12499       CheckForConstantInitializer(Init, DclT);
12500 
12501     // C89 is stricter than C99 for aggregate initializers.
12502     // C89 6.5.7p3: All the expressions [...] in an initializer list
12503     // for an object that has aggregate or union type shall be
12504     // constant expressions.
12505     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12506                isa<InitListExpr>(Init)) {
12507       const Expr *Culprit;
12508       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12509         Diag(Culprit->getExprLoc(),
12510              diag::ext_aggregate_init_not_constant)
12511           << Culprit->getSourceRange();
12512       }
12513     }
12514 
12515     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12516       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12517         if (VDecl->hasLocalStorage())
12518           BE->getBlockDecl()->setCanAvoidCopyToHeap();
12519   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12520              VDecl->getLexicalDeclContext()->isRecord()) {
12521     // This is an in-class initialization for a static data member, e.g.,
12522     //
12523     // struct S {
12524     //   static const int value = 17;
12525     // };
12526 
12527     // C++ [class.mem]p4:
12528     //   A member-declarator can contain a constant-initializer only
12529     //   if it declares a static member (9.4) of const integral or
12530     //   const enumeration type, see 9.4.2.
12531     //
12532     // C++11 [class.static.data]p3:
12533     //   If a non-volatile non-inline const static data member is of integral
12534     //   or enumeration type, its declaration in the class definition can
12535     //   specify a brace-or-equal-initializer in which every initializer-clause
12536     //   that is an assignment-expression is a constant expression. A static
12537     //   data member of literal type can be declared in the class definition
12538     //   with the constexpr specifier; if so, its declaration shall specify a
12539     //   brace-or-equal-initializer in which every initializer-clause that is
12540     //   an assignment-expression is a constant expression.
12541 
12542     // Do nothing on dependent types.
12543     if (DclT->isDependentType()) {
12544 
12545     // Allow any 'static constexpr' members, whether or not they are of literal
12546     // type. We separately check that every constexpr variable is of literal
12547     // type.
12548     } else if (VDecl->isConstexpr()) {
12549 
12550     // Require constness.
12551     } else if (!DclT.isConstQualified()) {
12552       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12553         << Init->getSourceRange();
12554       VDecl->setInvalidDecl();
12555 
12556     // We allow integer constant expressions in all cases.
12557     } else if (DclT->isIntegralOrEnumerationType()) {
12558       // Check whether the expression is a constant expression.
12559       SourceLocation Loc;
12560       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12561         // In C++11, a non-constexpr const static data member with an
12562         // in-class initializer cannot be volatile.
12563         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12564       else if (Init->isValueDependent())
12565         ; // Nothing to check.
12566       else if (Init->isIntegerConstantExpr(Context, &Loc))
12567         ; // Ok, it's an ICE!
12568       else if (Init->getType()->isScopedEnumeralType() &&
12569                Init->isCXX11ConstantExpr(Context))
12570         ; // Ok, it is a scoped-enum constant expression.
12571       else if (Init->isEvaluatable(Context)) {
12572         // If we can constant fold the initializer through heroics, accept it,
12573         // but report this as a use of an extension for -pedantic.
12574         Diag(Loc, diag::ext_in_class_initializer_non_constant)
12575           << Init->getSourceRange();
12576       } else {
12577         // Otherwise, this is some crazy unknown case.  Report the issue at the
12578         // location provided by the isIntegerConstantExpr failed check.
12579         Diag(Loc, diag::err_in_class_initializer_non_constant)
12580           << Init->getSourceRange();
12581         VDecl->setInvalidDecl();
12582       }
12583 
12584     // We allow foldable floating-point constants as an extension.
12585     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12586       // In C++98, this is a GNU extension. In C++11, it is not, but we support
12587       // it anyway and provide a fixit to add the 'constexpr'.
12588       if (getLangOpts().CPlusPlus11) {
12589         Diag(VDecl->getLocation(),
12590              diag::ext_in_class_initializer_float_type_cxx11)
12591             << DclT << Init->getSourceRange();
12592         Diag(VDecl->getBeginLoc(),
12593              diag::note_in_class_initializer_float_type_cxx11)
12594             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12595       } else {
12596         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12597           << DclT << Init->getSourceRange();
12598 
12599         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12600           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12601             << Init->getSourceRange();
12602           VDecl->setInvalidDecl();
12603         }
12604       }
12605 
12606     // Suggest adding 'constexpr' in C++11 for literal types.
12607     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12608       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12609           << DclT << Init->getSourceRange()
12610           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12611       VDecl->setConstexpr(true);
12612 
12613     } else {
12614       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12615         << DclT << Init->getSourceRange();
12616       VDecl->setInvalidDecl();
12617     }
12618   } else if (VDecl->isFileVarDecl()) {
12619     // In C, extern is typically used to avoid tentative definitions when
12620     // declaring variables in headers, but adding an intializer makes it a
12621     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12622     // In C++, extern is often used to give implictly static const variables
12623     // external linkage, so don't warn in that case. If selectany is present,
12624     // this might be header code intended for C and C++ inclusion, so apply the
12625     // C++ rules.
12626     if (VDecl->getStorageClass() == SC_Extern &&
12627         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12628          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12629         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12630         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12631       Diag(VDecl->getLocation(), diag::warn_extern_init);
12632 
12633     // In Microsoft C++ mode, a const variable defined in namespace scope has
12634     // external linkage by default if the variable is declared with
12635     // __declspec(dllexport).
12636     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12637         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12638         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12639       VDecl->setStorageClass(SC_Extern);
12640 
12641     // C99 6.7.8p4. All file scoped initializers need to be constant.
12642     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12643       CheckForConstantInitializer(Init, DclT);
12644   }
12645 
12646   QualType InitType = Init->getType();
12647   if (!InitType.isNull() &&
12648       (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12649        InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12650     checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12651 
12652   // We will represent direct-initialization similarly to copy-initialization:
12653   //    int x(1);  -as-> int x = 1;
12654   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12655   //
12656   // Clients that want to distinguish between the two forms, can check for
12657   // direct initializer using VarDecl::getInitStyle().
12658   // A major benefit is that clients that don't particularly care about which
12659   // exactly form was it (like the CodeGen) can handle both cases without
12660   // special case code.
12661 
12662   // C++ 8.5p11:
12663   // The form of initialization (using parentheses or '=') is generally
12664   // insignificant, but does matter when the entity being initialized has a
12665   // class type.
12666   if (CXXDirectInit) {
12667     assert(DirectInit && "Call-style initializer must be direct init.");
12668     VDecl->setInitStyle(VarDecl::CallInit);
12669   } else if (DirectInit) {
12670     // This must be list-initialization. No other way is direct-initialization.
12671     VDecl->setInitStyle(VarDecl::ListInit);
12672   }
12673 
12674   if (LangOpts.OpenMP &&
12675       (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12676       VDecl->isFileVarDecl())
12677     DeclsToCheckForDeferredDiags.insert(VDecl);
12678   CheckCompleteVariableDeclaration(VDecl);
12679 }
12680 
12681 /// ActOnInitializerError - Given that there was an error parsing an
12682 /// initializer for the given declaration, try to at least re-establish
12683 /// invariants such as whether a variable's type is either dependent or
12684 /// complete.
12685 void Sema::ActOnInitializerError(Decl *D) {
12686   // Our main concern here is re-establishing invariants like "a
12687   // variable's type is either dependent or complete".
12688   if (!D || D->isInvalidDecl()) return;
12689 
12690   VarDecl *VD = dyn_cast<VarDecl>(D);
12691   if (!VD) return;
12692 
12693   // Bindings are not usable if we can't make sense of the initializer.
12694   if (auto *DD = dyn_cast<DecompositionDecl>(D))
12695     for (auto *BD : DD->bindings())
12696       BD->setInvalidDecl();
12697 
12698   // Auto types are meaningless if we can't make sense of the initializer.
12699   if (VD->getType()->isUndeducedType()) {
12700     D->setInvalidDecl();
12701     return;
12702   }
12703 
12704   QualType Ty = VD->getType();
12705   if (Ty->isDependentType()) return;
12706 
12707   // Require a complete type.
12708   if (RequireCompleteType(VD->getLocation(),
12709                           Context.getBaseElementType(Ty),
12710                           diag::err_typecheck_decl_incomplete_type)) {
12711     VD->setInvalidDecl();
12712     return;
12713   }
12714 
12715   // Require a non-abstract type.
12716   if (RequireNonAbstractType(VD->getLocation(), Ty,
12717                              diag::err_abstract_type_in_decl,
12718                              AbstractVariableType)) {
12719     VD->setInvalidDecl();
12720     return;
12721   }
12722 
12723   // Don't bother complaining about constructors or destructors,
12724   // though.
12725 }
12726 
12727 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12728   // If there is no declaration, there was an error parsing it. Just ignore it.
12729   if (!RealDecl)
12730     return;
12731 
12732   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12733     QualType Type = Var->getType();
12734 
12735     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12736     if (isa<DecompositionDecl>(RealDecl)) {
12737       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12738       Var->setInvalidDecl();
12739       return;
12740     }
12741 
12742     if (Type->isUndeducedType() &&
12743         DeduceVariableDeclarationType(Var, false, nullptr))
12744       return;
12745 
12746     // C++11 [class.static.data]p3: A static data member can be declared with
12747     // the constexpr specifier; if so, its declaration shall specify
12748     // a brace-or-equal-initializer.
12749     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12750     // the definition of a variable [...] or the declaration of a static data
12751     // member.
12752     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12753         !Var->isThisDeclarationADemotedDefinition()) {
12754       if (Var->isStaticDataMember()) {
12755         // C++1z removes the relevant rule; the in-class declaration is always
12756         // a definition there.
12757         if (!getLangOpts().CPlusPlus17 &&
12758             !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12759           Diag(Var->getLocation(),
12760                diag::err_constexpr_static_mem_var_requires_init)
12761               << Var;
12762           Var->setInvalidDecl();
12763           return;
12764         }
12765       } else {
12766         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12767         Var->setInvalidDecl();
12768         return;
12769       }
12770     }
12771 
12772     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12773     // be initialized.
12774     if (!Var->isInvalidDecl() &&
12775         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12776         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12777       bool HasConstExprDefaultConstructor = false;
12778       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12779         for (auto *Ctor : RD->ctors()) {
12780           if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12781               Ctor->getMethodQualifiers().getAddressSpace() ==
12782                   LangAS::opencl_constant) {
12783             HasConstExprDefaultConstructor = true;
12784           }
12785         }
12786       }
12787       if (!HasConstExprDefaultConstructor) {
12788         Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12789         Var->setInvalidDecl();
12790         return;
12791       }
12792     }
12793 
12794     if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12795       if (Var->getStorageClass() == SC_Extern) {
12796         Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12797             << Var;
12798         Var->setInvalidDecl();
12799         return;
12800       }
12801       if (RequireCompleteType(Var->getLocation(), Var->getType(),
12802                               diag::err_typecheck_decl_incomplete_type)) {
12803         Var->setInvalidDecl();
12804         return;
12805       }
12806       if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12807         if (!RD->hasTrivialDefaultConstructor()) {
12808           Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12809           Var->setInvalidDecl();
12810           return;
12811         }
12812       }
12813       // The declaration is unitialized, no need for further checks.
12814       return;
12815     }
12816 
12817     VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12818     if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12819         Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12820       checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12821                             NTCUC_DefaultInitializedObject, NTCUK_Init);
12822 
12823 
12824     switch (DefKind) {
12825     case VarDecl::Definition:
12826       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12827         break;
12828 
12829       // We have an out-of-line definition of a static data member
12830       // that has an in-class initializer, so we type-check this like
12831       // a declaration.
12832       //
12833       LLVM_FALLTHROUGH;
12834 
12835     case VarDecl::DeclarationOnly:
12836       // It's only a declaration.
12837 
12838       // Block scope. C99 6.7p7: If an identifier for an object is
12839       // declared with no linkage (C99 6.2.2p6), the type for the
12840       // object shall be complete.
12841       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12842           !Var->hasLinkage() && !Var->isInvalidDecl() &&
12843           RequireCompleteType(Var->getLocation(), Type,
12844                               diag::err_typecheck_decl_incomplete_type))
12845         Var->setInvalidDecl();
12846 
12847       // Make sure that the type is not abstract.
12848       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12849           RequireNonAbstractType(Var->getLocation(), Type,
12850                                  diag::err_abstract_type_in_decl,
12851                                  AbstractVariableType))
12852         Var->setInvalidDecl();
12853       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12854           Var->getStorageClass() == SC_PrivateExtern) {
12855         Diag(Var->getLocation(), diag::warn_private_extern);
12856         Diag(Var->getLocation(), diag::note_private_extern);
12857       }
12858 
12859       if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12860           !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12861         ExternalDeclarations.push_back(Var);
12862 
12863       return;
12864 
12865     case VarDecl::TentativeDefinition:
12866       // File scope. C99 6.9.2p2: A declaration of an identifier for an
12867       // object that has file scope without an initializer, and without a
12868       // storage-class specifier or with the storage-class specifier "static",
12869       // constitutes a tentative definition. Note: A tentative definition with
12870       // external linkage is valid (C99 6.2.2p5).
12871       if (!Var->isInvalidDecl()) {
12872         if (const IncompleteArrayType *ArrayT
12873                                     = Context.getAsIncompleteArrayType(Type)) {
12874           if (RequireCompleteSizedType(
12875                   Var->getLocation(), ArrayT->getElementType(),
12876                   diag::err_array_incomplete_or_sizeless_type))
12877             Var->setInvalidDecl();
12878         } else if (Var->getStorageClass() == SC_Static) {
12879           // C99 6.9.2p3: If the declaration of an identifier for an object is
12880           // a tentative definition and has internal linkage (C99 6.2.2p3), the
12881           // declared type shall not be an incomplete type.
12882           // NOTE: code such as the following
12883           //     static struct s;
12884           //     struct s { int a; };
12885           // is accepted by gcc. Hence here we issue a warning instead of
12886           // an error and we do not invalidate the static declaration.
12887           // NOTE: to avoid multiple warnings, only check the first declaration.
12888           if (Var->isFirstDecl())
12889             RequireCompleteType(Var->getLocation(), Type,
12890                                 diag::ext_typecheck_decl_incomplete_type);
12891         }
12892       }
12893 
12894       // Record the tentative definition; we're done.
12895       if (!Var->isInvalidDecl())
12896         TentativeDefinitions.push_back(Var);
12897       return;
12898     }
12899 
12900     // Provide a specific diagnostic for uninitialized variable
12901     // definitions with incomplete array type.
12902     if (Type->isIncompleteArrayType()) {
12903       Diag(Var->getLocation(),
12904            diag::err_typecheck_incomplete_array_needs_initializer);
12905       Var->setInvalidDecl();
12906       return;
12907     }
12908 
12909     // Provide a specific diagnostic for uninitialized variable
12910     // definitions with reference type.
12911     if (Type->isReferenceType()) {
12912       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12913           << Var << SourceRange(Var->getLocation(), Var->getLocation());
12914       Var->setInvalidDecl();
12915       return;
12916     }
12917 
12918     // Do not attempt to type-check the default initializer for a
12919     // variable with dependent type.
12920     if (Type->isDependentType())
12921       return;
12922 
12923     if (Var->isInvalidDecl())
12924       return;
12925 
12926     if (!Var->hasAttr<AliasAttr>()) {
12927       if (RequireCompleteType(Var->getLocation(),
12928                               Context.getBaseElementType(Type),
12929                               diag::err_typecheck_decl_incomplete_type)) {
12930         Var->setInvalidDecl();
12931         return;
12932       }
12933     } else {
12934       return;
12935     }
12936 
12937     // The variable can not have an abstract class type.
12938     if (RequireNonAbstractType(Var->getLocation(), Type,
12939                                diag::err_abstract_type_in_decl,
12940                                AbstractVariableType)) {
12941       Var->setInvalidDecl();
12942       return;
12943     }
12944 
12945     // Check for jumps past the implicit initializer.  C++0x
12946     // clarifies that this applies to a "variable with automatic
12947     // storage duration", not a "local variable".
12948     // C++11 [stmt.dcl]p3
12949     //   A program that jumps from a point where a variable with automatic
12950     //   storage duration is not in scope to a point where it is in scope is
12951     //   ill-formed unless the variable has scalar type, class type with a
12952     //   trivial default constructor and a trivial destructor, a cv-qualified
12953     //   version of one of these types, or an array of one of the preceding
12954     //   types and is declared without an initializer.
12955     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12956       if (const RecordType *Record
12957             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12958         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12959         // Mark the function (if we're in one) for further checking even if the
12960         // looser rules of C++11 do not require such checks, so that we can
12961         // diagnose incompatibilities with C++98.
12962         if (!CXXRecord->isPOD())
12963           setFunctionHasBranchProtectedScope();
12964       }
12965     }
12966     // In OpenCL, we can't initialize objects in the __local address space,
12967     // even implicitly, so don't synthesize an implicit initializer.
12968     if (getLangOpts().OpenCL &&
12969         Var->getType().getAddressSpace() == LangAS::opencl_local)
12970       return;
12971     // C++03 [dcl.init]p9:
12972     //   If no initializer is specified for an object, and the
12973     //   object is of (possibly cv-qualified) non-POD class type (or
12974     //   array thereof), the object shall be default-initialized; if
12975     //   the object is of const-qualified type, the underlying class
12976     //   type shall have a user-declared default
12977     //   constructor. Otherwise, if no initializer is specified for
12978     //   a non- static object, the object and its subobjects, if
12979     //   any, have an indeterminate initial value); if the object
12980     //   or any of its subobjects are of const-qualified type, the
12981     //   program is ill-formed.
12982     // C++0x [dcl.init]p11:
12983     //   If no initializer is specified for an object, the object is
12984     //   default-initialized; [...].
12985     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12986     InitializationKind Kind
12987       = InitializationKind::CreateDefault(Var->getLocation());
12988 
12989     InitializationSequence InitSeq(*this, Entity, Kind, None);
12990     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12991 
12992     if (Init.get()) {
12993       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12994       // This is important for template substitution.
12995       Var->setInitStyle(VarDecl::CallInit);
12996     } else if (Init.isInvalid()) {
12997       // If default-init fails, attach a recovery-expr initializer to track
12998       // that initialization was attempted and failed.
12999       auto RecoveryExpr =
13000           CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13001       if (RecoveryExpr.get())
13002         Var->setInit(RecoveryExpr.get());
13003     }
13004 
13005     CheckCompleteVariableDeclaration(Var);
13006   }
13007 }
13008 
13009 void Sema::ActOnCXXForRangeDecl(Decl *D) {
13010   // If there is no declaration, there was an error parsing it. Ignore it.
13011   if (!D)
13012     return;
13013 
13014   VarDecl *VD = dyn_cast<VarDecl>(D);
13015   if (!VD) {
13016     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13017     D->setInvalidDecl();
13018     return;
13019   }
13020 
13021   VD->setCXXForRangeDecl(true);
13022 
13023   // for-range-declaration cannot be given a storage class specifier.
13024   int Error = -1;
13025   switch (VD->getStorageClass()) {
13026   case SC_None:
13027     break;
13028   case SC_Extern:
13029     Error = 0;
13030     break;
13031   case SC_Static:
13032     Error = 1;
13033     break;
13034   case SC_PrivateExtern:
13035     Error = 2;
13036     break;
13037   case SC_Auto:
13038     Error = 3;
13039     break;
13040   case SC_Register:
13041     Error = 4;
13042     break;
13043   }
13044 
13045   // for-range-declaration cannot be given a storage class specifier con't.
13046   switch (VD->getTSCSpec()) {
13047   case TSCS_thread_local:
13048     Error = 6;
13049     break;
13050   case TSCS___thread:
13051   case TSCS__Thread_local:
13052   case TSCS_unspecified:
13053     break;
13054   }
13055 
13056   if (Error != -1) {
13057     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13058         << VD << Error;
13059     D->setInvalidDecl();
13060   }
13061 }
13062 
13063 StmtResult
13064 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
13065                                  IdentifierInfo *Ident,
13066                                  ParsedAttributes &Attrs,
13067                                  SourceLocation AttrEnd) {
13068   // C++1y [stmt.iter]p1:
13069   //   A range-based for statement of the form
13070   //      for ( for-range-identifier : for-range-initializer ) statement
13071   //   is equivalent to
13072   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
13073   DeclSpec DS(Attrs.getPool().getFactory());
13074 
13075   const char *PrevSpec;
13076   unsigned DiagID;
13077   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13078                      getPrintingPolicy());
13079 
13080   Declarator D(DS, DeclaratorContext::ForInit);
13081   D.SetIdentifier(Ident, IdentLoc);
13082   D.takeAttributes(Attrs, AttrEnd);
13083 
13084   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13085                 IdentLoc);
13086   Decl *Var = ActOnDeclarator(S, D);
13087   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13088   FinalizeDeclaration(Var);
13089   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13090                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
13091 }
13092 
13093 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13094   if (var->isInvalidDecl()) return;
13095 
13096   MaybeAddCUDAConstantAttr(var);
13097 
13098   if (getLangOpts().OpenCL) {
13099     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13100     // initialiser
13101     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13102         !var->hasInit()) {
13103       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13104           << 1 /*Init*/;
13105       var->setInvalidDecl();
13106       return;
13107     }
13108   }
13109 
13110   // In Objective-C, don't allow jumps past the implicit initialization of a
13111   // local retaining variable.
13112   if (getLangOpts().ObjC &&
13113       var->hasLocalStorage()) {
13114     switch (var->getType().getObjCLifetime()) {
13115     case Qualifiers::OCL_None:
13116     case Qualifiers::OCL_ExplicitNone:
13117     case Qualifiers::OCL_Autoreleasing:
13118       break;
13119 
13120     case Qualifiers::OCL_Weak:
13121     case Qualifiers::OCL_Strong:
13122       setFunctionHasBranchProtectedScope();
13123       break;
13124     }
13125   }
13126 
13127   if (var->hasLocalStorage() &&
13128       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13129     setFunctionHasBranchProtectedScope();
13130 
13131   // Warn about externally-visible variables being defined without a
13132   // prior declaration.  We only want to do this for global
13133   // declarations, but we also specifically need to avoid doing it for
13134   // class members because the linkage of an anonymous class can
13135   // change if it's later given a typedef name.
13136   if (var->isThisDeclarationADefinition() &&
13137       var->getDeclContext()->getRedeclContext()->isFileContext() &&
13138       var->isExternallyVisible() && var->hasLinkage() &&
13139       !var->isInline() && !var->getDescribedVarTemplate() &&
13140       !isa<VarTemplatePartialSpecializationDecl>(var) &&
13141       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13142       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13143                                   var->getLocation())) {
13144     // Find a previous declaration that's not a definition.
13145     VarDecl *prev = var->getPreviousDecl();
13146     while (prev && prev->isThisDeclarationADefinition())
13147       prev = prev->getPreviousDecl();
13148 
13149     if (!prev) {
13150       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13151       Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13152           << /* variable */ 0;
13153     }
13154   }
13155 
13156   // Cache the result of checking for constant initialization.
13157   Optional<bool> CacheHasConstInit;
13158   const Expr *CacheCulprit = nullptr;
13159   auto checkConstInit = [&]() mutable {
13160     if (!CacheHasConstInit)
13161       CacheHasConstInit = var->getInit()->isConstantInitializer(
13162             Context, var->getType()->isReferenceType(), &CacheCulprit);
13163     return *CacheHasConstInit;
13164   };
13165 
13166   if (var->getTLSKind() == VarDecl::TLS_Static) {
13167     if (var->getType().isDestructedType()) {
13168       // GNU C++98 edits for __thread, [basic.start.term]p3:
13169       //   The type of an object with thread storage duration shall not
13170       //   have a non-trivial destructor.
13171       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13172       if (getLangOpts().CPlusPlus11)
13173         Diag(var->getLocation(), diag::note_use_thread_local);
13174     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13175       if (!checkConstInit()) {
13176         // GNU C++98 edits for __thread, [basic.start.init]p4:
13177         //   An object of thread storage duration shall not require dynamic
13178         //   initialization.
13179         // FIXME: Need strict checking here.
13180         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13181           << CacheCulprit->getSourceRange();
13182         if (getLangOpts().CPlusPlus11)
13183           Diag(var->getLocation(), diag::note_use_thread_local);
13184       }
13185     }
13186   }
13187 
13188 
13189   if (!var->getType()->isStructureType() && var->hasInit() &&
13190       isa<InitListExpr>(var->getInit())) {
13191     const auto *ILE = cast<InitListExpr>(var->getInit());
13192     unsigned NumInits = ILE->getNumInits();
13193     if (NumInits > 2)
13194       for (unsigned I = 0; I < NumInits; ++I) {
13195         const auto *Init = ILE->getInit(I);
13196         if (!Init)
13197           break;
13198         const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13199         if (!SL)
13200           break;
13201 
13202         unsigned NumConcat = SL->getNumConcatenated();
13203         // Diagnose missing comma in string array initialization.
13204         // Do not warn when all the elements in the initializer are concatenated
13205         // together. Do not warn for macros too.
13206         if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13207           bool OnlyOneMissingComma = true;
13208           for (unsigned J = I + 1; J < NumInits; ++J) {
13209             const auto *Init = ILE->getInit(J);
13210             if (!Init)
13211               break;
13212             const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13213             if (!SLJ || SLJ->getNumConcatenated() > 1) {
13214               OnlyOneMissingComma = false;
13215               break;
13216             }
13217           }
13218 
13219           if (OnlyOneMissingComma) {
13220             SmallVector<FixItHint, 1> Hints;
13221             for (unsigned i = 0; i < NumConcat - 1; ++i)
13222               Hints.push_back(FixItHint::CreateInsertion(
13223                   PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13224 
13225             Diag(SL->getStrTokenLoc(1),
13226                  diag::warn_concatenated_literal_array_init)
13227                 << Hints;
13228             Diag(SL->getBeginLoc(),
13229                  diag::note_concatenated_string_literal_silence);
13230           }
13231           // In any case, stop now.
13232           break;
13233         }
13234       }
13235   }
13236 
13237 
13238   QualType type = var->getType();
13239 
13240   if (var->hasAttr<BlocksAttr>())
13241     getCurFunction()->addByrefBlockVar(var);
13242 
13243   Expr *Init = var->getInit();
13244   bool GlobalStorage = var->hasGlobalStorage();
13245   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13246   QualType baseType = Context.getBaseElementType(type);
13247   bool HasConstInit = true;
13248 
13249   // Check whether the initializer is sufficiently constant.
13250   if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13251       !Init->isValueDependent() &&
13252       (GlobalStorage || var->isConstexpr() ||
13253        var->mightBeUsableInConstantExpressions(Context))) {
13254     // If this variable might have a constant initializer or might be usable in
13255     // constant expressions, check whether or not it actually is now.  We can't
13256     // do this lazily, because the result might depend on things that change
13257     // later, such as which constexpr functions happen to be defined.
13258     SmallVector<PartialDiagnosticAt, 8> Notes;
13259     if (!getLangOpts().CPlusPlus11) {
13260       // Prior to C++11, in contexts where a constant initializer is required,
13261       // the set of valid constant initializers is described by syntactic rules
13262       // in [expr.const]p2-6.
13263       // FIXME: Stricter checking for these rules would be useful for constinit /
13264       // -Wglobal-constructors.
13265       HasConstInit = checkConstInit();
13266 
13267       // Compute and cache the constant value, and remember that we have a
13268       // constant initializer.
13269       if (HasConstInit) {
13270         (void)var->checkForConstantInitialization(Notes);
13271         Notes.clear();
13272       } else if (CacheCulprit) {
13273         Notes.emplace_back(CacheCulprit->getExprLoc(),
13274                            PDiag(diag::note_invalid_subexpr_in_const_expr));
13275         Notes.back().second << CacheCulprit->getSourceRange();
13276       }
13277     } else {
13278       // Evaluate the initializer to see if it's a constant initializer.
13279       HasConstInit = var->checkForConstantInitialization(Notes);
13280     }
13281 
13282     if (HasConstInit) {
13283       // FIXME: Consider replacing the initializer with a ConstantExpr.
13284     } else if (var->isConstexpr()) {
13285       SourceLocation DiagLoc = var->getLocation();
13286       // If the note doesn't add any useful information other than a source
13287       // location, fold it into the primary diagnostic.
13288       if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13289                                    diag::note_invalid_subexpr_in_const_expr) {
13290         DiagLoc = Notes[0].first;
13291         Notes.clear();
13292       }
13293       Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13294           << var << Init->getSourceRange();
13295       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13296         Diag(Notes[I].first, Notes[I].second);
13297     } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13298       auto *Attr = var->getAttr<ConstInitAttr>();
13299       Diag(var->getLocation(), diag::err_require_constant_init_failed)
13300           << Init->getSourceRange();
13301       Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13302           << Attr->getRange() << Attr->isConstinit();
13303       for (auto &it : Notes)
13304         Diag(it.first, it.second);
13305     } else if (IsGlobal &&
13306                !getDiagnostics().isIgnored(diag::warn_global_constructor,
13307                                            var->getLocation())) {
13308       // Warn about globals which don't have a constant initializer.  Don't
13309       // warn about globals with a non-trivial destructor because we already
13310       // warned about them.
13311       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13312       if (!(RD && !RD->hasTrivialDestructor())) {
13313         // checkConstInit() here permits trivial default initialization even in
13314         // C++11 onwards, where such an initializer is not a constant initializer
13315         // but nonetheless doesn't require a global constructor.
13316         if (!checkConstInit())
13317           Diag(var->getLocation(), diag::warn_global_constructor)
13318               << Init->getSourceRange();
13319       }
13320     }
13321   }
13322 
13323   // Apply section attributes and pragmas to global variables.
13324   if (GlobalStorage && var->isThisDeclarationADefinition() &&
13325       !inTemplateInstantiation()) {
13326     PragmaStack<StringLiteral *> *Stack = nullptr;
13327     int SectionFlags = ASTContext::PSF_Read;
13328     if (var->getType().isConstQualified()) {
13329       if (HasConstInit)
13330         Stack = &ConstSegStack;
13331       else {
13332         Stack = &BSSSegStack;
13333         SectionFlags |= ASTContext::PSF_Write;
13334       }
13335     } else if (var->hasInit() && HasConstInit) {
13336       Stack = &DataSegStack;
13337       SectionFlags |= ASTContext::PSF_Write;
13338     } else {
13339       Stack = &BSSSegStack;
13340       SectionFlags |= ASTContext::PSF_Write;
13341     }
13342     if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13343       if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13344         SectionFlags |= ASTContext::PSF_Implicit;
13345       UnifySection(SA->getName(), SectionFlags, var);
13346     } else if (Stack->CurrentValue) {
13347       SectionFlags |= ASTContext::PSF_Implicit;
13348       auto SectionName = Stack->CurrentValue->getString();
13349       var->addAttr(SectionAttr::CreateImplicit(
13350           Context, SectionName, Stack->CurrentPragmaLocation,
13351           AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13352       if (UnifySection(SectionName, SectionFlags, var))
13353         var->dropAttr<SectionAttr>();
13354     }
13355 
13356     // Apply the init_seg attribute if this has an initializer.  If the
13357     // initializer turns out to not be dynamic, we'll end up ignoring this
13358     // attribute.
13359     if (CurInitSeg && var->getInit())
13360       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13361                                                CurInitSegLoc,
13362                                                AttributeCommonInfo::AS_Pragma));
13363   }
13364 
13365   // All the following checks are C++ only.
13366   if (!getLangOpts().CPlusPlus) {
13367     // If this variable must be emitted, add it as an initializer for the
13368     // current module.
13369     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13370       Context.addModuleInitializer(ModuleScopes.back().Module, var);
13371     return;
13372   }
13373 
13374   // Require the destructor.
13375   if (!type->isDependentType())
13376     if (const RecordType *recordType = baseType->getAs<RecordType>())
13377       FinalizeVarWithDestructor(var, recordType);
13378 
13379   // If this variable must be emitted, add it as an initializer for the current
13380   // module.
13381   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13382     Context.addModuleInitializer(ModuleScopes.back().Module, var);
13383 
13384   // Build the bindings if this is a structured binding declaration.
13385   if (auto *DD = dyn_cast<DecompositionDecl>(var))
13386     CheckCompleteDecompositionDeclaration(DD);
13387 }
13388 
13389 /// Check if VD needs to be dllexport/dllimport due to being in a
13390 /// dllexport/import function.
13391 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13392   assert(VD->isStaticLocal());
13393 
13394   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13395 
13396   // Find outermost function when VD is in lambda function.
13397   while (FD && !getDLLAttr(FD) &&
13398          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13399          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13400     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13401   }
13402 
13403   if (!FD)
13404     return;
13405 
13406   // Static locals inherit dll attributes from their function.
13407   if (Attr *A = getDLLAttr(FD)) {
13408     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13409     NewAttr->setInherited(true);
13410     VD->addAttr(NewAttr);
13411   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13412     auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13413     NewAttr->setInherited(true);
13414     VD->addAttr(NewAttr);
13415 
13416     // Export this function to enforce exporting this static variable even
13417     // if it is not used in this compilation unit.
13418     if (!FD->hasAttr<DLLExportAttr>())
13419       FD->addAttr(NewAttr);
13420 
13421   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13422     auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13423     NewAttr->setInherited(true);
13424     VD->addAttr(NewAttr);
13425   }
13426 }
13427 
13428 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13429 /// any semantic actions necessary after any initializer has been attached.
13430 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13431   // Note that we are no longer parsing the initializer for this declaration.
13432   ParsingInitForAutoVars.erase(ThisDecl);
13433 
13434   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13435   if (!VD)
13436     return;
13437 
13438   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13439   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13440       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13441     if (PragmaClangBSSSection.Valid)
13442       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13443           Context, PragmaClangBSSSection.SectionName,
13444           PragmaClangBSSSection.PragmaLocation,
13445           AttributeCommonInfo::AS_Pragma));
13446     if (PragmaClangDataSection.Valid)
13447       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13448           Context, PragmaClangDataSection.SectionName,
13449           PragmaClangDataSection.PragmaLocation,
13450           AttributeCommonInfo::AS_Pragma));
13451     if (PragmaClangRodataSection.Valid)
13452       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13453           Context, PragmaClangRodataSection.SectionName,
13454           PragmaClangRodataSection.PragmaLocation,
13455           AttributeCommonInfo::AS_Pragma));
13456     if (PragmaClangRelroSection.Valid)
13457       VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13458           Context, PragmaClangRelroSection.SectionName,
13459           PragmaClangRelroSection.PragmaLocation,
13460           AttributeCommonInfo::AS_Pragma));
13461   }
13462 
13463   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13464     for (auto *BD : DD->bindings()) {
13465       FinalizeDeclaration(BD);
13466     }
13467   }
13468 
13469   checkAttributesAfterMerging(*this, *VD);
13470 
13471   // Perform TLS alignment check here after attributes attached to the variable
13472   // which may affect the alignment have been processed. Only perform the check
13473   // if the target has a maximum TLS alignment (zero means no constraints).
13474   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13475     // Protect the check so that it's not performed on dependent types and
13476     // dependent alignments (we can't determine the alignment in that case).
13477     if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13478       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13479       if (Context.getDeclAlign(VD) > MaxAlignChars) {
13480         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13481           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13482           << (unsigned)MaxAlignChars.getQuantity();
13483       }
13484     }
13485   }
13486 
13487   if (VD->isStaticLocal())
13488     CheckStaticLocalForDllExport(VD);
13489 
13490   // Perform check for initializers of device-side global variables.
13491   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13492   // 7.5). We must also apply the same checks to all __shared__
13493   // variables whether they are local or not. CUDA also allows
13494   // constant initializers for __constant__ and __device__ variables.
13495   if (getLangOpts().CUDA)
13496     checkAllowedCUDAInitializer(VD);
13497 
13498   // Grab the dllimport or dllexport attribute off of the VarDecl.
13499   const InheritableAttr *DLLAttr = getDLLAttr(VD);
13500 
13501   // Imported static data members cannot be defined out-of-line.
13502   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13503     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13504         VD->isThisDeclarationADefinition()) {
13505       // We allow definitions of dllimport class template static data members
13506       // with a warning.
13507       CXXRecordDecl *Context =
13508         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13509       bool IsClassTemplateMember =
13510           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13511           Context->getDescribedClassTemplate();
13512 
13513       Diag(VD->getLocation(),
13514            IsClassTemplateMember
13515                ? diag::warn_attribute_dllimport_static_field_definition
13516                : diag::err_attribute_dllimport_static_field_definition);
13517       Diag(IA->getLocation(), diag::note_attribute);
13518       if (!IsClassTemplateMember)
13519         VD->setInvalidDecl();
13520     }
13521   }
13522 
13523   // dllimport/dllexport variables cannot be thread local, their TLS index
13524   // isn't exported with the variable.
13525   if (DLLAttr && VD->getTLSKind()) {
13526     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13527     if (F && getDLLAttr(F)) {
13528       assert(VD->isStaticLocal());
13529       // But if this is a static local in a dlimport/dllexport function, the
13530       // function will never be inlined, which means the var would never be
13531       // imported, so having it marked import/export is safe.
13532     } else {
13533       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13534                                                                     << DLLAttr;
13535       VD->setInvalidDecl();
13536     }
13537   }
13538 
13539   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13540     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13541       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13542           << Attr;
13543       VD->dropAttr<UsedAttr>();
13544     }
13545   }
13546   if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13547     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13548       Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13549           << Attr;
13550       VD->dropAttr<RetainAttr>();
13551     }
13552   }
13553 
13554   const DeclContext *DC = VD->getDeclContext();
13555   // If there's a #pragma GCC visibility in scope, and this isn't a class
13556   // member, set the visibility of this variable.
13557   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13558     AddPushedVisibilityAttribute(VD);
13559 
13560   // FIXME: Warn on unused var template partial specializations.
13561   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13562     MarkUnusedFileScopedDecl(VD);
13563 
13564   // Now we have parsed the initializer and can update the table of magic
13565   // tag values.
13566   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13567       !VD->getType()->isIntegralOrEnumerationType())
13568     return;
13569 
13570   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13571     const Expr *MagicValueExpr = VD->getInit();
13572     if (!MagicValueExpr) {
13573       continue;
13574     }
13575     Optional<llvm::APSInt> MagicValueInt;
13576     if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13577       Diag(I->getRange().getBegin(),
13578            diag::err_type_tag_for_datatype_not_ice)
13579         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13580       continue;
13581     }
13582     if (MagicValueInt->getActiveBits() > 64) {
13583       Diag(I->getRange().getBegin(),
13584            diag::err_type_tag_for_datatype_too_large)
13585         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13586       continue;
13587     }
13588     uint64_t MagicValue = MagicValueInt->getZExtValue();
13589     RegisterTypeTagForDatatype(I->getArgumentKind(),
13590                                MagicValue,
13591                                I->getMatchingCType(),
13592                                I->getLayoutCompatible(),
13593                                I->getMustBeNull());
13594   }
13595 }
13596 
13597 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13598   auto *VD = dyn_cast<VarDecl>(DD);
13599   return VD && !VD->getType()->hasAutoForTrailingReturnType();
13600 }
13601 
13602 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13603                                                    ArrayRef<Decl *> Group) {
13604   SmallVector<Decl*, 8> Decls;
13605 
13606   if (DS.isTypeSpecOwned())
13607     Decls.push_back(DS.getRepAsDecl());
13608 
13609   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13610   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13611   bool DiagnosedMultipleDecomps = false;
13612   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13613   bool DiagnosedNonDeducedAuto = false;
13614 
13615   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13616     if (Decl *D = Group[i]) {
13617       // For declarators, there are some additional syntactic-ish checks we need
13618       // to perform.
13619       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13620         if (!FirstDeclaratorInGroup)
13621           FirstDeclaratorInGroup = DD;
13622         if (!FirstDecompDeclaratorInGroup)
13623           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13624         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13625             !hasDeducedAuto(DD))
13626           FirstNonDeducedAutoInGroup = DD;
13627 
13628         if (FirstDeclaratorInGroup != DD) {
13629           // A decomposition declaration cannot be combined with any other
13630           // declaration in the same group.
13631           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13632             Diag(FirstDecompDeclaratorInGroup->getLocation(),
13633                  diag::err_decomp_decl_not_alone)
13634                 << FirstDeclaratorInGroup->getSourceRange()
13635                 << DD->getSourceRange();
13636             DiagnosedMultipleDecomps = true;
13637           }
13638 
13639           // A declarator that uses 'auto' in any way other than to declare a
13640           // variable with a deduced type cannot be combined with any other
13641           // declarator in the same group.
13642           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13643             Diag(FirstNonDeducedAutoInGroup->getLocation(),
13644                  diag::err_auto_non_deduced_not_alone)
13645                 << FirstNonDeducedAutoInGroup->getType()
13646                        ->hasAutoForTrailingReturnType()
13647                 << FirstDeclaratorInGroup->getSourceRange()
13648                 << DD->getSourceRange();
13649             DiagnosedNonDeducedAuto = true;
13650           }
13651         }
13652       }
13653 
13654       Decls.push_back(D);
13655     }
13656   }
13657 
13658   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13659     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13660       handleTagNumbering(Tag, S);
13661       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13662           getLangOpts().CPlusPlus)
13663         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13664     }
13665   }
13666 
13667   return BuildDeclaratorGroup(Decls);
13668 }
13669 
13670 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13671 /// group, performing any necessary semantic checking.
13672 Sema::DeclGroupPtrTy
13673 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13674   // C++14 [dcl.spec.auto]p7: (DR1347)
13675   //   If the type that replaces the placeholder type is not the same in each
13676   //   deduction, the program is ill-formed.
13677   if (Group.size() > 1) {
13678     QualType Deduced;
13679     VarDecl *DeducedDecl = nullptr;
13680     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13681       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13682       if (!D || D->isInvalidDecl())
13683         break;
13684       DeducedType *DT = D->getType()->getContainedDeducedType();
13685       if (!DT || DT->getDeducedType().isNull())
13686         continue;
13687       if (Deduced.isNull()) {
13688         Deduced = DT->getDeducedType();
13689         DeducedDecl = D;
13690       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13691         auto *AT = dyn_cast<AutoType>(DT);
13692         auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13693                         diag::err_auto_different_deductions)
13694                    << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13695                    << DeducedDecl->getDeclName() << DT->getDeducedType()
13696                    << D->getDeclName();
13697         if (DeducedDecl->hasInit())
13698           Dia << DeducedDecl->getInit()->getSourceRange();
13699         if (D->getInit())
13700           Dia << D->getInit()->getSourceRange();
13701         D->setInvalidDecl();
13702         break;
13703       }
13704     }
13705   }
13706 
13707   ActOnDocumentableDecls(Group);
13708 
13709   return DeclGroupPtrTy::make(
13710       DeclGroupRef::Create(Context, Group.data(), Group.size()));
13711 }
13712 
13713 void Sema::ActOnDocumentableDecl(Decl *D) {
13714   ActOnDocumentableDecls(D);
13715 }
13716 
13717 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13718   // Don't parse the comment if Doxygen diagnostics are ignored.
13719   if (Group.empty() || !Group[0])
13720     return;
13721 
13722   if (Diags.isIgnored(diag::warn_doc_param_not_found,
13723                       Group[0]->getLocation()) &&
13724       Diags.isIgnored(diag::warn_unknown_comment_command_name,
13725                       Group[0]->getLocation()))
13726     return;
13727 
13728   if (Group.size() >= 2) {
13729     // This is a decl group.  Normally it will contain only declarations
13730     // produced from declarator list.  But in case we have any definitions or
13731     // additional declaration references:
13732     //   'typedef struct S {} S;'
13733     //   'typedef struct S *S;'
13734     //   'struct S *pS;'
13735     // FinalizeDeclaratorGroup adds these as separate declarations.
13736     Decl *MaybeTagDecl = Group[0];
13737     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13738       Group = Group.slice(1);
13739     }
13740   }
13741 
13742   // FIMXE: We assume every Decl in the group is in the same file.
13743   // This is false when preprocessor constructs the group from decls in
13744   // different files (e. g. macros or #include).
13745   Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13746 }
13747 
13748 /// Common checks for a parameter-declaration that should apply to both function
13749 /// parameters and non-type template parameters.
13750 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13751   // Check that there are no default arguments inside the type of this
13752   // parameter.
13753   if (getLangOpts().CPlusPlus)
13754     CheckExtraCXXDefaultArguments(D);
13755 
13756   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13757   if (D.getCXXScopeSpec().isSet()) {
13758     Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13759       << D.getCXXScopeSpec().getRange();
13760   }
13761 
13762   // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13763   // simple identifier except [...irrelevant cases...].
13764   switch (D.getName().getKind()) {
13765   case UnqualifiedIdKind::IK_Identifier:
13766     break;
13767 
13768   case UnqualifiedIdKind::IK_OperatorFunctionId:
13769   case UnqualifiedIdKind::IK_ConversionFunctionId:
13770   case UnqualifiedIdKind::IK_LiteralOperatorId:
13771   case UnqualifiedIdKind::IK_ConstructorName:
13772   case UnqualifiedIdKind::IK_DestructorName:
13773   case UnqualifiedIdKind::IK_ImplicitSelfParam:
13774   case UnqualifiedIdKind::IK_DeductionGuideName:
13775     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13776       << GetNameForDeclarator(D).getName();
13777     break;
13778 
13779   case UnqualifiedIdKind::IK_TemplateId:
13780   case UnqualifiedIdKind::IK_ConstructorTemplateId:
13781     // GetNameForDeclarator would not produce a useful name in this case.
13782     Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13783     break;
13784   }
13785 }
13786 
13787 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13788 /// to introduce parameters into function prototype scope.
13789 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13790   const DeclSpec &DS = D.getDeclSpec();
13791 
13792   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13793 
13794   // C++03 [dcl.stc]p2 also permits 'auto'.
13795   StorageClass SC = SC_None;
13796   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13797     SC = SC_Register;
13798     // In C++11, the 'register' storage class specifier is deprecated.
13799     // In C++17, it is not allowed, but we tolerate it as an extension.
13800     if (getLangOpts().CPlusPlus11) {
13801       Diag(DS.getStorageClassSpecLoc(),
13802            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13803                                      : diag::warn_deprecated_register)
13804         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13805     }
13806   } else if (getLangOpts().CPlusPlus &&
13807              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13808     SC = SC_Auto;
13809   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13810     Diag(DS.getStorageClassSpecLoc(),
13811          diag::err_invalid_storage_class_in_func_decl);
13812     D.getMutableDeclSpec().ClearStorageClassSpecs();
13813   }
13814 
13815   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13816     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13817       << DeclSpec::getSpecifierName(TSCS);
13818   if (DS.isInlineSpecified())
13819     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13820         << getLangOpts().CPlusPlus17;
13821   if (DS.hasConstexprSpecifier())
13822     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13823         << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13824 
13825   DiagnoseFunctionSpecifiers(DS);
13826 
13827   CheckFunctionOrTemplateParamDeclarator(S, D);
13828 
13829   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13830   QualType parmDeclType = TInfo->getType();
13831 
13832   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13833   IdentifierInfo *II = D.getIdentifier();
13834   if (II) {
13835     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13836                    ForVisibleRedeclaration);
13837     LookupName(R, S);
13838     if (R.isSingleResult()) {
13839       NamedDecl *PrevDecl = R.getFoundDecl();
13840       if (PrevDecl->isTemplateParameter()) {
13841         // Maybe we will complain about the shadowed template parameter.
13842         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13843         // Just pretend that we didn't see the previous declaration.
13844         PrevDecl = nullptr;
13845       } else if (S->isDeclScope(PrevDecl)) {
13846         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13847         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13848 
13849         // Recover by removing the name
13850         II = nullptr;
13851         D.SetIdentifier(nullptr, D.getIdentifierLoc());
13852         D.setInvalidType(true);
13853       }
13854     }
13855   }
13856 
13857   // Temporarily put parameter variables in the translation unit, not
13858   // the enclosing context.  This prevents them from accidentally
13859   // looking like class members in C++.
13860   ParmVarDecl *New =
13861       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13862                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13863 
13864   if (D.isInvalidType())
13865     New->setInvalidDecl();
13866 
13867   assert(S->isFunctionPrototypeScope());
13868   assert(S->getFunctionPrototypeDepth() >= 1);
13869   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13870                     S->getNextFunctionPrototypeIndex());
13871 
13872   // Add the parameter declaration into this scope.
13873   S->AddDecl(New);
13874   if (II)
13875     IdResolver.AddDecl(New);
13876 
13877   ProcessDeclAttributes(S, New, D);
13878 
13879   if (D.getDeclSpec().isModulePrivateSpecified())
13880     Diag(New->getLocation(), diag::err_module_private_local)
13881         << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13882         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13883 
13884   if (New->hasAttr<BlocksAttr>()) {
13885     Diag(New->getLocation(), diag::err_block_on_nonlocal);
13886   }
13887 
13888   if (getLangOpts().OpenCL)
13889     deduceOpenCLAddressSpace(New);
13890 
13891   return New;
13892 }
13893 
13894 /// Synthesizes a variable for a parameter arising from a
13895 /// typedef.
13896 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13897                                               SourceLocation Loc,
13898                                               QualType T) {
13899   /* FIXME: setting StartLoc == Loc.
13900      Would it be worth to modify callers so as to provide proper source
13901      location for the unnamed parameters, embedding the parameter's type? */
13902   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13903                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
13904                                            SC_None, nullptr);
13905   Param->setImplicit();
13906   return Param;
13907 }
13908 
13909 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13910   // Don't diagnose unused-parameter errors in template instantiations; we
13911   // will already have done so in the template itself.
13912   if (inTemplateInstantiation())
13913     return;
13914 
13915   for (const ParmVarDecl *Parameter : Parameters) {
13916     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13917         !Parameter->hasAttr<UnusedAttr>()) {
13918       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13919         << Parameter->getDeclName();
13920     }
13921   }
13922 }
13923 
13924 void Sema::DiagnoseSizeOfParametersAndReturnValue(
13925     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13926   if (LangOpts.NumLargeByValueCopy == 0) // No check.
13927     return;
13928 
13929   // Warn if the return value is pass-by-value and larger than the specified
13930   // threshold.
13931   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13932     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13933     if (Size > LangOpts.NumLargeByValueCopy)
13934       Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13935   }
13936 
13937   // Warn if any parameter is pass-by-value and larger than the specified
13938   // threshold.
13939   for (const ParmVarDecl *Parameter : Parameters) {
13940     QualType T = Parameter->getType();
13941     if (T->isDependentType() || !T.isPODType(Context))
13942       continue;
13943     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13944     if (Size > LangOpts.NumLargeByValueCopy)
13945       Diag(Parameter->getLocation(), diag::warn_parameter_size)
13946           << Parameter << Size;
13947   }
13948 }
13949 
13950 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13951                                   SourceLocation NameLoc, IdentifierInfo *Name,
13952                                   QualType T, TypeSourceInfo *TSInfo,
13953                                   StorageClass SC) {
13954   // In ARC, infer a lifetime qualifier for appropriate parameter types.
13955   if (getLangOpts().ObjCAutoRefCount &&
13956       T.getObjCLifetime() == Qualifiers::OCL_None &&
13957       T->isObjCLifetimeType()) {
13958 
13959     Qualifiers::ObjCLifetime lifetime;
13960 
13961     // Special cases for arrays:
13962     //   - if it's const, use __unsafe_unretained
13963     //   - otherwise, it's an error
13964     if (T->isArrayType()) {
13965       if (!T.isConstQualified()) {
13966         if (DelayedDiagnostics.shouldDelayDiagnostics())
13967           DelayedDiagnostics.add(
13968               sema::DelayedDiagnostic::makeForbiddenType(
13969               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13970         else
13971           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13972               << TSInfo->getTypeLoc().getSourceRange();
13973       }
13974       lifetime = Qualifiers::OCL_ExplicitNone;
13975     } else {
13976       lifetime = T->getObjCARCImplicitLifetime();
13977     }
13978     T = Context.getLifetimeQualifiedType(T, lifetime);
13979   }
13980 
13981   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13982                                          Context.getAdjustedParameterType(T),
13983                                          TSInfo, SC, nullptr);
13984 
13985   // Make a note if we created a new pack in the scope of a lambda, so that
13986   // we know that references to that pack must also be expanded within the
13987   // lambda scope.
13988   if (New->isParameterPack())
13989     if (auto *LSI = getEnclosingLambda())
13990       LSI->LocalPacks.push_back(New);
13991 
13992   if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13993       New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13994     checkNonTrivialCUnion(New->getType(), New->getLocation(),
13995                           NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13996 
13997   // Parameters can not be abstract class types.
13998   // For record types, this is done by the AbstractClassUsageDiagnoser once
13999   // the class has been completely parsed.
14000   if (!CurContext->isRecord() &&
14001       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14002                              AbstractParamType))
14003     New->setInvalidDecl();
14004 
14005   // Parameter declarators cannot be interface types. All ObjC objects are
14006   // passed by reference.
14007   if (T->isObjCObjectType()) {
14008     SourceLocation TypeEndLoc =
14009         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14010     Diag(NameLoc,
14011          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14012       << FixItHint::CreateInsertion(TypeEndLoc, "*");
14013     T = Context.getObjCObjectPointerType(T);
14014     New->setType(T);
14015   }
14016 
14017   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14018   // duration shall not be qualified by an address-space qualifier."
14019   // Since all parameters have automatic store duration, they can not have
14020   // an address space.
14021   if (T.getAddressSpace() != LangAS::Default &&
14022       // OpenCL allows function arguments declared to be an array of a type
14023       // to be qualified with an address space.
14024       !(getLangOpts().OpenCL &&
14025         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
14026     Diag(NameLoc, diag::err_arg_with_address_space);
14027     New->setInvalidDecl();
14028   }
14029 
14030   // PPC MMA non-pointer types are not allowed as function argument types.
14031   if (Context.getTargetInfo().getTriple().isPPC64() &&
14032       CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14033     New->setInvalidDecl();
14034   }
14035 
14036   return New;
14037 }
14038 
14039 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
14040                                            SourceLocation LocAfterDecls) {
14041   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
14042 
14043   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14044   // for a K&R function.
14045   if (!FTI.hasPrototype) {
14046     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14047       --i;
14048       if (FTI.Params[i].Param == nullptr) {
14049         SmallString<256> Code;
14050         llvm::raw_svector_ostream(Code)
14051             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
14052         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14053             << FTI.Params[i].Ident
14054             << FixItHint::CreateInsertion(LocAfterDecls, Code);
14055 
14056         // Implicitly declare the argument as type 'int' for lack of a better
14057         // type.
14058         AttributeFactory attrs;
14059         DeclSpec DS(attrs);
14060         const char* PrevSpec; // unused
14061         unsigned DiagID; // unused
14062         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14063                            DiagID, Context.getPrintingPolicy());
14064         // Use the identifier location for the type source range.
14065         DS.SetRangeStart(FTI.Params[i].IdentLoc);
14066         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14067         Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
14068         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14069         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14070       }
14071     }
14072   }
14073 }
14074 
14075 Decl *
14076 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
14077                               MultiTemplateParamsArg TemplateParameterLists,
14078                               SkipBodyInfo *SkipBody) {
14079   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14080   assert(D.isFunctionDeclarator() && "Not a function declarator!");
14081   Scope *ParentScope = FnBodyScope->getParent();
14082 
14083   // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14084   // we define a non-templated function definition, we will create a declaration
14085   // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14086   // The base function declaration will have the equivalent of an `omp declare
14087   // variant` annotation which specifies the mangled definition as a
14088   // specialization function under the OpenMP context defined as part of the
14089   // `omp begin declare variant`.
14090   SmallVector<FunctionDecl *, 4> Bases;
14091   if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14092     ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14093         ParentScope, D, TemplateParameterLists, Bases);
14094 
14095   D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14096   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14097   Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14098 
14099   if (!Bases.empty())
14100     ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14101 
14102   return Dcl;
14103 }
14104 
14105 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14106   Consumer.HandleInlineFunctionDefinition(D);
14107 }
14108 
14109 static bool
14110 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14111                                 const FunctionDecl *&PossiblePrototype) {
14112   // Don't warn about invalid declarations.
14113   if (FD->isInvalidDecl())
14114     return false;
14115 
14116   // Or declarations that aren't global.
14117   if (!FD->isGlobal())
14118     return false;
14119 
14120   // Don't warn about C++ member functions.
14121   if (isa<CXXMethodDecl>(FD))
14122     return false;
14123 
14124   // Don't warn about 'main'.
14125   if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14126     if (IdentifierInfo *II = FD->getIdentifier())
14127       if (II->isStr("main") || II->isStr("efi_main"))
14128         return false;
14129 
14130   // Don't warn about inline functions.
14131   if (FD->isInlined())
14132     return false;
14133 
14134   // Don't warn about function templates.
14135   if (FD->getDescribedFunctionTemplate())
14136     return false;
14137 
14138   // Don't warn about function template specializations.
14139   if (FD->isFunctionTemplateSpecialization())
14140     return false;
14141 
14142   // Don't warn for OpenCL kernels.
14143   if (FD->hasAttr<OpenCLKernelAttr>())
14144     return false;
14145 
14146   // Don't warn on explicitly deleted functions.
14147   if (FD->isDeleted())
14148     return false;
14149 
14150   for (const FunctionDecl *Prev = FD->getPreviousDecl();
14151        Prev; Prev = Prev->getPreviousDecl()) {
14152     // Ignore any declarations that occur in function or method
14153     // scope, because they aren't visible from the header.
14154     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14155       continue;
14156 
14157     PossiblePrototype = Prev;
14158     return Prev->getType()->isFunctionNoProtoType();
14159   }
14160 
14161   return true;
14162 }
14163 
14164 void
14165 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14166                                    const FunctionDecl *EffectiveDefinition,
14167                                    SkipBodyInfo *SkipBody) {
14168   const FunctionDecl *Definition = EffectiveDefinition;
14169   if (!Definition &&
14170       !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14171     return;
14172 
14173   if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14174     if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14175       if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14176         // A merged copy of the same function, instantiated as a member of
14177         // the same class, is OK.
14178         if (declaresSameEntity(OrigFD, OrigDef) &&
14179             declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14180                                cast<Decl>(FD->getLexicalDeclContext())))
14181           return;
14182       }
14183     }
14184   }
14185 
14186   if (canRedefineFunction(Definition, getLangOpts()))
14187     return;
14188 
14189   // Don't emit an error when this is redefinition of a typo-corrected
14190   // definition.
14191   if (TypoCorrectedFunctionDefinitions.count(Definition))
14192     return;
14193 
14194   // If we don't have a visible definition of the function, and it's inline or
14195   // a template, skip the new definition.
14196   if (SkipBody && !hasVisibleDefinition(Definition) &&
14197       (Definition->getFormalLinkage() == InternalLinkage ||
14198        Definition->isInlined() ||
14199        Definition->getDescribedFunctionTemplate() ||
14200        Definition->getNumTemplateParameterLists())) {
14201     SkipBody->ShouldSkip = true;
14202     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14203     if (auto *TD = Definition->getDescribedFunctionTemplate())
14204       makeMergedDefinitionVisible(TD);
14205     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14206     return;
14207   }
14208 
14209   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14210       Definition->getStorageClass() == SC_Extern)
14211     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14212         << FD << getLangOpts().CPlusPlus;
14213   else
14214     Diag(FD->getLocation(), diag::err_redefinition) << FD;
14215 
14216   Diag(Definition->getLocation(), diag::note_previous_definition);
14217   FD->setInvalidDecl();
14218 }
14219 
14220 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14221                                    Sema &S) {
14222   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14223 
14224   LambdaScopeInfo *LSI = S.PushLambdaScope();
14225   LSI->CallOperator = CallOperator;
14226   LSI->Lambda = LambdaClass;
14227   LSI->ReturnType = CallOperator->getReturnType();
14228   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14229 
14230   if (LCD == LCD_None)
14231     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14232   else if (LCD == LCD_ByCopy)
14233     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14234   else if (LCD == LCD_ByRef)
14235     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14236   DeclarationNameInfo DNI = CallOperator->getNameInfo();
14237 
14238   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14239   LSI->Mutable = !CallOperator->isConst();
14240 
14241   // Add the captures to the LSI so they can be noted as already
14242   // captured within tryCaptureVar.
14243   auto I = LambdaClass->field_begin();
14244   for (const auto &C : LambdaClass->captures()) {
14245     if (C.capturesVariable()) {
14246       VarDecl *VD = C.getCapturedVar();
14247       if (VD->isInitCapture())
14248         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14249       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14250       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14251           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14252           /*EllipsisLoc*/C.isPackExpansion()
14253                          ? C.getEllipsisLoc() : SourceLocation(),
14254           I->getType(), /*Invalid*/false);
14255 
14256     } else if (C.capturesThis()) {
14257       LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14258                           C.getCaptureKind() == LCK_StarThis);
14259     } else {
14260       LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14261                              I->getType());
14262     }
14263     ++I;
14264   }
14265 }
14266 
14267 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14268                                     SkipBodyInfo *SkipBody) {
14269   if (!D) {
14270     // Parsing the function declaration failed in some way. Push on a fake scope
14271     // anyway so we can try to parse the function body.
14272     PushFunctionScope();
14273     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14274     return D;
14275   }
14276 
14277   FunctionDecl *FD = nullptr;
14278 
14279   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14280     FD = FunTmpl->getTemplatedDecl();
14281   else
14282     FD = cast<FunctionDecl>(D);
14283 
14284   // Do not push if it is a lambda because one is already pushed when building
14285   // the lambda in ActOnStartOfLambdaDefinition().
14286   if (!isLambdaCallOperator(FD))
14287     PushExpressionEvaluationContext(
14288         FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14289                           : ExprEvalContexts.back().Context);
14290 
14291   // Check for defining attributes before the check for redefinition.
14292   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14293     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14294     FD->dropAttr<AliasAttr>();
14295     FD->setInvalidDecl();
14296   }
14297   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14298     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14299     FD->dropAttr<IFuncAttr>();
14300     FD->setInvalidDecl();
14301   }
14302 
14303   if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14304     if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14305         Ctor->isDefaultConstructor() &&
14306         Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14307       // If this is an MS ABI dllexport default constructor, instantiate any
14308       // default arguments.
14309       InstantiateDefaultCtorDefaultArgs(Ctor);
14310     }
14311   }
14312 
14313   // See if this is a redefinition. If 'will have body' (or similar) is already
14314   // set, then these checks were already performed when it was set.
14315   if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14316       !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14317     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14318 
14319     // If we're skipping the body, we're done. Don't enter the scope.
14320     if (SkipBody && SkipBody->ShouldSkip)
14321       return D;
14322   }
14323 
14324   // Mark this function as "will have a body eventually".  This lets users to
14325   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14326   // this function.
14327   FD->setWillHaveBody();
14328 
14329   // If we are instantiating a generic lambda call operator, push
14330   // a LambdaScopeInfo onto the function stack.  But use the information
14331   // that's already been calculated (ActOnLambdaExpr) to prime the current
14332   // LambdaScopeInfo.
14333   // When the template operator is being specialized, the LambdaScopeInfo,
14334   // has to be properly restored so that tryCaptureVariable doesn't try
14335   // and capture any new variables. In addition when calculating potential
14336   // captures during transformation of nested lambdas, it is necessary to
14337   // have the LSI properly restored.
14338   if (isGenericLambdaCallOperatorSpecialization(FD)) {
14339     assert(inTemplateInstantiation() &&
14340            "There should be an active template instantiation on the stack "
14341            "when instantiating a generic lambda!");
14342     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14343   } else {
14344     // Enter a new function scope
14345     PushFunctionScope();
14346   }
14347 
14348   // Builtin functions cannot be defined.
14349   if (unsigned BuiltinID = FD->getBuiltinID()) {
14350     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14351         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14352       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14353       FD->setInvalidDecl();
14354     }
14355   }
14356 
14357   // The return type of a function definition must be complete
14358   // (C99 6.9.1p3, C++ [dcl.fct]p6).
14359   QualType ResultType = FD->getReturnType();
14360   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14361       !FD->isInvalidDecl() &&
14362       RequireCompleteType(FD->getLocation(), ResultType,
14363                           diag::err_func_def_incomplete_result))
14364     FD->setInvalidDecl();
14365 
14366   if (FnBodyScope)
14367     PushDeclContext(FnBodyScope, FD);
14368 
14369   // Check the validity of our function parameters
14370   CheckParmsForFunctionDef(FD->parameters(),
14371                            /*CheckParameterNames=*/true);
14372 
14373   // Add non-parameter declarations already in the function to the current
14374   // scope.
14375   if (FnBodyScope) {
14376     for (Decl *NPD : FD->decls()) {
14377       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14378       if (!NonParmDecl)
14379         continue;
14380       assert(!isa<ParmVarDecl>(NonParmDecl) &&
14381              "parameters should not be in newly created FD yet");
14382 
14383       // If the decl has a name, make it accessible in the current scope.
14384       if (NonParmDecl->getDeclName())
14385         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14386 
14387       // Similarly, dive into enums and fish their constants out, making them
14388       // accessible in this scope.
14389       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14390         for (auto *EI : ED->enumerators())
14391           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14392       }
14393     }
14394   }
14395 
14396   // Introduce our parameters into the function scope
14397   for (auto Param : FD->parameters()) {
14398     Param->setOwningFunction(FD);
14399 
14400     // If this has an identifier, add it to the scope stack.
14401     if (Param->getIdentifier() && FnBodyScope) {
14402       CheckShadow(FnBodyScope, Param);
14403 
14404       PushOnScopeChains(Param, FnBodyScope);
14405     }
14406   }
14407 
14408   // Ensure that the function's exception specification is instantiated.
14409   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14410     ResolveExceptionSpec(D->getLocation(), FPT);
14411 
14412   // dllimport cannot be applied to non-inline function definitions.
14413   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14414       !FD->isTemplateInstantiation()) {
14415     assert(!FD->hasAttr<DLLExportAttr>());
14416     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14417     FD->setInvalidDecl();
14418     return D;
14419   }
14420   // We want to attach documentation to original Decl (which might be
14421   // a function template).
14422   ActOnDocumentableDecl(D);
14423   if (getCurLexicalContext()->isObjCContainer() &&
14424       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14425       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14426     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14427 
14428   return D;
14429 }
14430 
14431 /// Given the set of return statements within a function body,
14432 /// compute the variables that are subject to the named return value
14433 /// optimization.
14434 ///
14435 /// Each of the variables that is subject to the named return value
14436 /// optimization will be marked as NRVO variables in the AST, and any
14437 /// return statement that has a marked NRVO variable as its NRVO candidate can
14438 /// use the named return value optimization.
14439 ///
14440 /// This function applies a very simplistic algorithm for NRVO: if every return
14441 /// statement in the scope of a variable has the same NRVO candidate, that
14442 /// candidate is an NRVO variable.
14443 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14444   ReturnStmt **Returns = Scope->Returns.data();
14445 
14446   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14447     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14448       if (!NRVOCandidate->isNRVOVariable())
14449         Returns[I]->setNRVOCandidate(nullptr);
14450     }
14451   }
14452 }
14453 
14454 bool Sema::canDelayFunctionBody(const Declarator &D) {
14455   // We can't delay parsing the body of a constexpr function template (yet).
14456   if (D.getDeclSpec().hasConstexprSpecifier())
14457     return false;
14458 
14459   // We can't delay parsing the body of a function template with a deduced
14460   // return type (yet).
14461   if (D.getDeclSpec().hasAutoTypeSpec()) {
14462     // If the placeholder introduces a non-deduced trailing return type,
14463     // we can still delay parsing it.
14464     if (D.getNumTypeObjects()) {
14465       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14466       if (Outer.Kind == DeclaratorChunk::Function &&
14467           Outer.Fun.hasTrailingReturnType()) {
14468         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14469         return Ty.isNull() || !Ty->isUndeducedType();
14470       }
14471     }
14472     return false;
14473   }
14474 
14475   return true;
14476 }
14477 
14478 bool Sema::canSkipFunctionBody(Decl *D) {
14479   // We cannot skip the body of a function (or function template) which is
14480   // constexpr, since we may need to evaluate its body in order to parse the
14481   // rest of the file.
14482   // We cannot skip the body of a function with an undeduced return type,
14483   // because any callers of that function need to know the type.
14484   if (const FunctionDecl *FD = D->getAsFunction()) {
14485     if (FD->isConstexpr())
14486       return false;
14487     // We can't simply call Type::isUndeducedType here, because inside template
14488     // auto can be deduced to a dependent type, which is not considered
14489     // "undeduced".
14490     if (FD->getReturnType()->getContainedDeducedType())
14491       return false;
14492   }
14493   return Consumer.shouldSkipFunctionBody(D);
14494 }
14495 
14496 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14497   if (!Decl)
14498     return nullptr;
14499   if (FunctionDecl *FD = Decl->getAsFunction())
14500     FD->setHasSkippedBody();
14501   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14502     MD->setHasSkippedBody();
14503   return Decl;
14504 }
14505 
14506 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14507   return ActOnFinishFunctionBody(D, BodyArg, false);
14508 }
14509 
14510 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14511 /// body.
14512 class ExitFunctionBodyRAII {
14513 public:
14514   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14515   ~ExitFunctionBodyRAII() {
14516     if (!IsLambda)
14517       S.PopExpressionEvaluationContext();
14518   }
14519 
14520 private:
14521   Sema &S;
14522   bool IsLambda = false;
14523 };
14524 
14525 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14526   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14527 
14528   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14529     if (EscapeInfo.count(BD))
14530       return EscapeInfo[BD];
14531 
14532     bool R = false;
14533     const BlockDecl *CurBD = BD;
14534 
14535     do {
14536       R = !CurBD->doesNotEscape();
14537       if (R)
14538         break;
14539       CurBD = CurBD->getParent()->getInnermostBlockDecl();
14540     } while (CurBD);
14541 
14542     return EscapeInfo[BD] = R;
14543   };
14544 
14545   // If the location where 'self' is implicitly retained is inside a escaping
14546   // block, emit a diagnostic.
14547   for (const std::pair<SourceLocation, const BlockDecl *> &P :
14548        S.ImplicitlyRetainedSelfLocs)
14549     if (IsOrNestedInEscapingBlock(P.second))
14550       S.Diag(P.first, diag::warn_implicitly_retains_self)
14551           << FixItHint::CreateInsertion(P.first, "self->");
14552 }
14553 
14554 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14555                                     bool IsInstantiation) {
14556   FunctionScopeInfo *FSI = getCurFunction();
14557   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14558 
14559   if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14560     FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14561 
14562   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14563   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14564 
14565   if (getLangOpts().Coroutines && FSI->isCoroutine())
14566     CheckCompletedCoroutineBody(FD, Body);
14567 
14568   {
14569     // Do not call PopExpressionEvaluationContext() if it is a lambda because
14570     // one is already popped when finishing the lambda in BuildLambdaExpr().
14571     // This is meant to pop the context added in ActOnStartOfFunctionDef().
14572     ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14573 
14574     if (FD) {
14575       FD->setBody(Body);
14576       FD->setWillHaveBody(false);
14577 
14578       if (getLangOpts().CPlusPlus14) {
14579         if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14580             FD->getReturnType()->isUndeducedType()) {
14581           // If the function has a deduced result type but contains no 'return'
14582           // statements, the result type as written must be exactly 'auto', and
14583           // the deduced result type is 'void'.
14584           if (!FD->getReturnType()->getAs<AutoType>()) {
14585             Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14586                 << FD->getReturnType();
14587             FD->setInvalidDecl();
14588           } else {
14589             // Substitute 'void' for the 'auto' in the type.
14590             TypeLoc ResultType = getReturnTypeLoc(FD);
14591             Context.adjustDeducedFunctionResultType(
14592                 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14593           }
14594         }
14595       } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14596         // In C++11, we don't use 'auto' deduction rules for lambda call
14597         // operators because we don't support return type deduction.
14598         auto *LSI = getCurLambda();
14599         if (LSI->HasImplicitReturnType) {
14600           deduceClosureReturnType(*LSI);
14601 
14602           // C++11 [expr.prim.lambda]p4:
14603           //   [...] if there are no return statements in the compound-statement
14604           //   [the deduced type is] the type void
14605           QualType RetType =
14606               LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14607 
14608           // Update the return type to the deduced type.
14609           const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14610           FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14611                                               Proto->getExtProtoInfo()));
14612         }
14613       }
14614 
14615       // If the function implicitly returns zero (like 'main') or is naked,
14616       // don't complain about missing return statements.
14617       if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14618         WP.disableCheckFallThrough();
14619 
14620       // MSVC permits the use of pure specifier (=0) on function definition,
14621       // defined at class scope, warn about this non-standard construct.
14622       if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14623         Diag(FD->getLocation(), diag::ext_pure_function_definition);
14624 
14625       if (!FD->isInvalidDecl()) {
14626         // Don't diagnose unused parameters of defaulted or deleted functions.
14627         if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14628           DiagnoseUnusedParameters(FD->parameters());
14629         DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14630                                                FD->getReturnType(), FD);
14631 
14632         // If this is a structor, we need a vtable.
14633         if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14634           MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14635         else if (CXXDestructorDecl *Destructor =
14636                      dyn_cast<CXXDestructorDecl>(FD))
14637           MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14638 
14639         // Try to apply the named return value optimization. We have to check
14640         // if we can do this here because lambdas keep return statements around
14641         // to deduce an implicit return type.
14642         if (FD->getReturnType()->isRecordType() &&
14643             (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14644           computeNRVO(Body, FSI);
14645       }
14646 
14647       // GNU warning -Wmissing-prototypes:
14648       //   Warn if a global function is defined without a previous
14649       //   prototype declaration. This warning is issued even if the
14650       //   definition itself provides a prototype. The aim is to detect
14651       //   global functions that fail to be declared in header files.
14652       const FunctionDecl *PossiblePrototype = nullptr;
14653       if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14654         Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14655 
14656         if (PossiblePrototype) {
14657           // We found a declaration that is not a prototype,
14658           // but that could be a zero-parameter prototype
14659           if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14660             TypeLoc TL = TI->getTypeLoc();
14661             if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14662               Diag(PossiblePrototype->getLocation(),
14663                    diag::note_declaration_not_a_prototype)
14664                   << (FD->getNumParams() != 0)
14665                   << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14666                                                     FTL.getRParenLoc(), "void")
14667                                               : FixItHint{});
14668           }
14669         } else {
14670           // Returns true if the token beginning at this Loc is `const`.
14671           auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14672                                   const LangOptions &LangOpts) {
14673             std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14674             if (LocInfo.first.isInvalid())
14675               return false;
14676 
14677             bool Invalid = false;
14678             StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14679             if (Invalid)
14680               return false;
14681 
14682             if (LocInfo.second > Buffer.size())
14683               return false;
14684 
14685             const char *LexStart = Buffer.data() + LocInfo.second;
14686             StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14687 
14688             return StartTok.consume_front("const") &&
14689                    (StartTok.empty() || isWhitespace(StartTok[0]) ||
14690                     StartTok.startswith("/*") || StartTok.startswith("//"));
14691           };
14692 
14693           auto findBeginLoc = [&]() {
14694             // If the return type has `const` qualifier, we want to insert
14695             // `static` before `const` (and not before the typename).
14696             if ((FD->getReturnType()->isAnyPointerType() &&
14697                  FD->getReturnType()->getPointeeType().isConstQualified()) ||
14698                 FD->getReturnType().isConstQualified()) {
14699               // But only do this if we can determine where the `const` is.
14700 
14701               if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14702                                getLangOpts()))
14703 
14704                 return FD->getBeginLoc();
14705             }
14706             return FD->getTypeSpecStartLoc();
14707           };
14708           Diag(FD->getTypeSpecStartLoc(),
14709                diag::note_static_for_internal_linkage)
14710               << /* function */ 1
14711               << (FD->getStorageClass() == SC_None
14712                       ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14713                       : FixItHint{});
14714         }
14715 
14716         // GNU warning -Wstrict-prototypes
14717         //   Warn if K&R function is defined without a previous declaration.
14718         //   This warning is issued only if the definition itself does not
14719         //   provide a prototype. Only K&R definitions do not provide a
14720         //   prototype.
14721         if (!FD->hasWrittenPrototype()) {
14722           TypeSourceInfo *TI = FD->getTypeSourceInfo();
14723           TypeLoc TL = TI->getTypeLoc();
14724           FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14725           Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14726         }
14727       }
14728 
14729       // Warn on CPUDispatch with an actual body.
14730       if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14731         if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14732           if (!CmpndBody->body_empty())
14733             Diag(CmpndBody->body_front()->getBeginLoc(),
14734                  diag::warn_dispatch_body_ignored);
14735 
14736       if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14737         const CXXMethodDecl *KeyFunction;
14738         if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14739             MD->isVirtual() &&
14740             (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14741             MD == KeyFunction->getCanonicalDecl()) {
14742           // Update the key-function state if necessary for this ABI.
14743           if (FD->isInlined() &&
14744               !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14745             Context.setNonKeyFunction(MD);
14746 
14747             // If the newly-chosen key function is already defined, then we
14748             // need to mark the vtable as used retroactively.
14749             KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14750             const FunctionDecl *Definition;
14751             if (KeyFunction && KeyFunction->isDefined(Definition))
14752               MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14753           } else {
14754             // We just defined they key function; mark the vtable as used.
14755             MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14756           }
14757         }
14758       }
14759 
14760       assert(
14761           (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14762           "Function parsing confused");
14763     } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14764       assert(MD == getCurMethodDecl() && "Method parsing confused");
14765       MD->setBody(Body);
14766       if (!MD->isInvalidDecl()) {
14767         DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14768                                                MD->getReturnType(), MD);
14769 
14770         if (Body)
14771           computeNRVO(Body, FSI);
14772       }
14773       if (FSI->ObjCShouldCallSuper) {
14774         Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14775             << MD->getSelector().getAsString();
14776         FSI->ObjCShouldCallSuper = false;
14777       }
14778       if (FSI->ObjCWarnForNoDesignatedInitChain) {
14779         const ObjCMethodDecl *InitMethod = nullptr;
14780         bool isDesignated =
14781             MD->isDesignatedInitializerForTheInterface(&InitMethod);
14782         assert(isDesignated && InitMethod);
14783         (void)isDesignated;
14784 
14785         auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14786           auto IFace = MD->getClassInterface();
14787           if (!IFace)
14788             return false;
14789           auto SuperD = IFace->getSuperClass();
14790           if (!SuperD)
14791             return false;
14792           return SuperD->getIdentifier() ==
14793                  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14794         };
14795         // Don't issue this warning for unavailable inits or direct subclasses
14796         // of NSObject.
14797         if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14798           Diag(MD->getLocation(),
14799                diag::warn_objc_designated_init_missing_super_call);
14800           Diag(InitMethod->getLocation(),
14801                diag::note_objc_designated_init_marked_here);
14802         }
14803         FSI->ObjCWarnForNoDesignatedInitChain = false;
14804       }
14805       if (FSI->ObjCWarnForNoInitDelegation) {
14806         // Don't issue this warning for unavaialable inits.
14807         if (!MD->isUnavailable())
14808           Diag(MD->getLocation(),
14809                diag::warn_objc_secondary_init_missing_init_call);
14810         FSI->ObjCWarnForNoInitDelegation = false;
14811       }
14812 
14813       diagnoseImplicitlyRetainedSelf(*this);
14814     } else {
14815       // Parsing the function declaration failed in some way. Pop the fake scope
14816       // we pushed on.
14817       PopFunctionScopeInfo(ActivePolicy, dcl);
14818       return nullptr;
14819     }
14820 
14821     if (Body && FSI->HasPotentialAvailabilityViolations)
14822       DiagnoseUnguardedAvailabilityViolations(dcl);
14823 
14824     assert(!FSI->ObjCShouldCallSuper &&
14825            "This should only be set for ObjC methods, which should have been "
14826            "handled in the block above.");
14827 
14828     // Verify and clean out per-function state.
14829     if (Body && (!FD || !FD->isDefaulted())) {
14830       // C++ constructors that have function-try-blocks can't have return
14831       // statements in the handlers of that block. (C++ [except.handle]p14)
14832       // Verify this.
14833       if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14834         DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14835 
14836       // Verify that gotos and switch cases don't jump into scopes illegally.
14837       if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
14838         DiagnoseInvalidJumps(Body);
14839 
14840       if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14841         if (!Destructor->getParent()->isDependentType())
14842           CheckDestructor(Destructor);
14843 
14844         MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14845                                                Destructor->getParent());
14846       }
14847 
14848       // If any errors have occurred, clear out any temporaries that may have
14849       // been leftover. This ensures that these temporaries won't be picked up
14850       // for deletion in some later function.
14851       if (hasUncompilableErrorOccurred() ||
14852           getDiagnostics().getSuppressAllDiagnostics()) {
14853         DiscardCleanupsInEvaluationContext();
14854       }
14855       if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
14856         // Since the body is valid, issue any analysis-based warnings that are
14857         // enabled.
14858         ActivePolicy = &WP;
14859       }
14860 
14861       if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14862           !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14863         FD->setInvalidDecl();
14864 
14865       if (FD && FD->hasAttr<NakedAttr>()) {
14866         for (const Stmt *S : Body->children()) {
14867           // Allow local register variables without initializer as they don't
14868           // require prologue.
14869           bool RegisterVariables = false;
14870           if (auto *DS = dyn_cast<DeclStmt>(S)) {
14871             for (const auto *Decl : DS->decls()) {
14872               if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14873                 RegisterVariables =
14874                     Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14875                 if (!RegisterVariables)
14876                   break;
14877               }
14878             }
14879           }
14880           if (RegisterVariables)
14881             continue;
14882           if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14883             Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14884             Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14885             FD->setInvalidDecl();
14886             break;
14887           }
14888         }
14889       }
14890 
14891       assert(ExprCleanupObjects.size() ==
14892                  ExprEvalContexts.back().NumCleanupObjects &&
14893              "Leftover temporaries in function");
14894       assert(!Cleanup.exprNeedsCleanups() &&
14895              "Unaccounted cleanups in function");
14896       assert(MaybeODRUseExprs.empty() &&
14897              "Leftover expressions for odr-use checking");
14898     }
14899   } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
14900     // the declaration context below. Otherwise, we're unable to transform
14901     // 'this' expressions when transforming immediate context functions.
14902 
14903   if (!IsInstantiation)
14904     PopDeclContext();
14905 
14906   PopFunctionScopeInfo(ActivePolicy, dcl);
14907   // If any errors have occurred, clear out any temporaries that may have
14908   // been leftover. This ensures that these temporaries won't be picked up for
14909   // deletion in some later function.
14910   if (hasUncompilableErrorOccurred()) {
14911     DiscardCleanupsInEvaluationContext();
14912   }
14913 
14914   if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
14915                                   !LangOpts.OMPTargetTriples.empty())) ||
14916              LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14917     auto ES = getEmissionStatus(FD);
14918     if (ES == Sema::FunctionEmissionStatus::Emitted ||
14919         ES == Sema::FunctionEmissionStatus::Unknown)
14920       DeclsToCheckForDeferredDiags.insert(FD);
14921   }
14922 
14923   if (FD && !FD->isDeleted())
14924     checkTypeSupport(FD->getType(), FD->getLocation(), FD);
14925 
14926   return dcl;
14927 }
14928 
14929 /// When we finish delayed parsing of an attribute, we must attach it to the
14930 /// relevant Decl.
14931 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14932                                        ParsedAttributes &Attrs) {
14933   // Always attach attributes to the underlying decl.
14934   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14935     D = TD->getTemplatedDecl();
14936   ProcessDeclAttributeList(S, D, Attrs);
14937 
14938   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14939     if (Method->isStatic())
14940       checkThisInStaticMemberFunctionAttributes(Method);
14941 }
14942 
14943 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14944 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14945 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14946                                           IdentifierInfo &II, Scope *S) {
14947   // Find the scope in which the identifier is injected and the corresponding
14948   // DeclContext.
14949   // FIXME: C89 does not say what happens if there is no enclosing block scope.
14950   // In that case, we inject the declaration into the translation unit scope
14951   // instead.
14952   Scope *BlockScope = S;
14953   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14954     BlockScope = BlockScope->getParent();
14955 
14956   Scope *ContextScope = BlockScope;
14957   while (!ContextScope->getEntity())
14958     ContextScope = ContextScope->getParent();
14959   ContextRAII SavedContext(*this, ContextScope->getEntity());
14960 
14961   // Before we produce a declaration for an implicitly defined
14962   // function, see whether there was a locally-scoped declaration of
14963   // this name as a function or variable. If so, use that
14964   // (non-visible) declaration, and complain about it.
14965   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14966   if (ExternCPrev) {
14967     // We still need to inject the function into the enclosing block scope so
14968     // that later (non-call) uses can see it.
14969     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14970 
14971     // C89 footnote 38:
14972     //   If in fact it is not defined as having type "function returning int",
14973     //   the behavior is undefined.
14974     if (!isa<FunctionDecl>(ExternCPrev) ||
14975         !Context.typesAreCompatible(
14976             cast<FunctionDecl>(ExternCPrev)->getType(),
14977             Context.getFunctionNoProtoType(Context.IntTy))) {
14978       Diag(Loc, diag::ext_use_out_of_scope_declaration)
14979           << ExternCPrev << !getLangOpts().C99;
14980       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14981       return ExternCPrev;
14982     }
14983   }
14984 
14985   // Extension in C99.  Legal in C90, but warn about it.
14986   unsigned diag_id;
14987   if (II.getName().startswith("__builtin_"))
14988     diag_id = diag::warn_builtin_unknown;
14989   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14990   else if (getLangOpts().OpenCL)
14991     diag_id = diag::err_opencl_implicit_function_decl;
14992   else if (getLangOpts().C99)
14993     diag_id = diag::ext_implicit_function_decl;
14994   else
14995     diag_id = diag::warn_implicit_function_decl;
14996   Diag(Loc, diag_id) << &II;
14997 
14998   // If we found a prior declaration of this function, don't bother building
14999   // another one. We've already pushed that one into scope, so there's nothing
15000   // more to do.
15001   if (ExternCPrev)
15002     return ExternCPrev;
15003 
15004   // Because typo correction is expensive, only do it if the implicit
15005   // function declaration is going to be treated as an error.
15006   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
15007     TypoCorrection Corrected;
15008     DeclFilterCCC<FunctionDecl> CCC{};
15009     if (S && (Corrected =
15010                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15011                               S, nullptr, CCC, CTK_NonError)))
15012       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15013                    /*ErrorRecovery*/false);
15014   }
15015 
15016   // Set a Declarator for the implicit definition: int foo();
15017   const char *Dummy;
15018   AttributeFactory attrFactory;
15019   DeclSpec DS(attrFactory);
15020   unsigned DiagID;
15021   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15022                                   Context.getPrintingPolicy());
15023   (void)Error; // Silence warning.
15024   assert(!Error && "Error setting up implicit decl!");
15025   SourceLocation NoLoc;
15026   Declarator D(DS, DeclaratorContext::Block);
15027   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15028                                              /*IsAmbiguous=*/false,
15029                                              /*LParenLoc=*/NoLoc,
15030                                              /*Params=*/nullptr,
15031                                              /*NumParams=*/0,
15032                                              /*EllipsisLoc=*/NoLoc,
15033                                              /*RParenLoc=*/NoLoc,
15034                                              /*RefQualifierIsLvalueRef=*/true,
15035                                              /*RefQualifierLoc=*/NoLoc,
15036                                              /*MutableLoc=*/NoLoc, EST_None,
15037                                              /*ESpecRange=*/SourceRange(),
15038                                              /*Exceptions=*/nullptr,
15039                                              /*ExceptionRanges=*/nullptr,
15040                                              /*NumExceptions=*/0,
15041                                              /*NoexceptExpr=*/nullptr,
15042                                              /*ExceptionSpecTokens=*/nullptr,
15043                                              /*DeclsInPrototype=*/None, Loc,
15044                                              Loc, D),
15045                 std::move(DS.getAttributes()), SourceLocation());
15046   D.SetIdentifier(&II, Loc);
15047 
15048   // Insert this function into the enclosing block scope.
15049   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15050   FD->setImplicit();
15051 
15052   AddKnownFunctionAttributes(FD);
15053 
15054   return FD;
15055 }
15056 
15057 /// If this function is a C++ replaceable global allocation function
15058 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15059 /// adds any function attributes that we know a priori based on the standard.
15060 ///
15061 /// We need to check for duplicate attributes both here and where user-written
15062 /// attributes are applied to declarations.
15063 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
15064     FunctionDecl *FD) {
15065   if (FD->isInvalidDecl())
15066     return;
15067 
15068   if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15069       FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15070     return;
15071 
15072   Optional<unsigned> AlignmentParam;
15073   bool IsNothrow = false;
15074   if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15075     return;
15076 
15077   // C++2a [basic.stc.dynamic.allocation]p4:
15078   //   An allocation function that has a non-throwing exception specification
15079   //   indicates failure by returning a null pointer value. Any other allocation
15080   //   function never returns a null pointer value and indicates failure only by
15081   //   throwing an exception [...]
15082   if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15083     FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15084 
15085   // C++2a [basic.stc.dynamic.allocation]p2:
15086   //   An allocation function attempts to allocate the requested amount of
15087   //   storage. [...] If the request succeeds, the value returned by a
15088   //   replaceable allocation function is a [...] pointer value p0 different
15089   //   from any previously returned value p1 [...]
15090   //
15091   // However, this particular information is being added in codegen,
15092   // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15093 
15094   // C++2a [basic.stc.dynamic.allocation]p2:
15095   //   An allocation function attempts to allocate the requested amount of
15096   //   storage. If it is successful, it returns the address of the start of a
15097   //   block of storage whose length in bytes is at least as large as the
15098   //   requested size.
15099   if (!FD->hasAttr<AllocSizeAttr>()) {
15100     FD->addAttr(AllocSizeAttr::CreateImplicit(
15101         Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15102         /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15103   }
15104 
15105   // C++2a [basic.stc.dynamic.allocation]p3:
15106   //   For an allocation function [...], the pointer returned on a successful
15107   //   call shall represent the address of storage that is aligned as follows:
15108   //   (3.1) If the allocation function takes an argument of type
15109   //         std​::​align_­val_­t, the storage will have the alignment
15110   //         specified by the value of this argument.
15111   if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15112     FD->addAttr(AllocAlignAttr::CreateImplicit(
15113         Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15114   }
15115 
15116   // FIXME:
15117   // C++2a [basic.stc.dynamic.allocation]p3:
15118   //   For an allocation function [...], the pointer returned on a successful
15119   //   call shall represent the address of storage that is aligned as follows:
15120   //   (3.2) Otherwise, if the allocation function is named operator new[],
15121   //         the storage is aligned for any object that does not have
15122   //         new-extended alignment ([basic.align]) and is no larger than the
15123   //         requested size.
15124   //   (3.3) Otherwise, the storage is aligned for any object that does not
15125   //         have new-extended alignment and is of the requested size.
15126 }
15127 
15128 /// Adds any function attributes that we know a priori based on
15129 /// the declaration of this function.
15130 ///
15131 /// These attributes can apply both to implicitly-declared builtins
15132 /// (like __builtin___printf_chk) or to library-declared functions
15133 /// like NSLog or printf.
15134 ///
15135 /// We need to check for duplicate attributes both here and where user-written
15136 /// attributes are applied to declarations.
15137 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15138   if (FD->isInvalidDecl())
15139     return;
15140 
15141   // If this is a built-in function, map its builtin attributes to
15142   // actual attributes.
15143   if (unsigned BuiltinID = FD->getBuiltinID()) {
15144     // Handle printf-formatting attributes.
15145     unsigned FormatIdx;
15146     bool HasVAListArg;
15147     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15148       if (!FD->hasAttr<FormatAttr>()) {
15149         const char *fmt = "printf";
15150         unsigned int NumParams = FD->getNumParams();
15151         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15152             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15153           fmt = "NSString";
15154         FD->addAttr(FormatAttr::CreateImplicit(Context,
15155                                                &Context.Idents.get(fmt),
15156                                                FormatIdx+1,
15157                                                HasVAListArg ? 0 : FormatIdx+2,
15158                                                FD->getLocation()));
15159       }
15160     }
15161     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15162                                              HasVAListArg)) {
15163      if (!FD->hasAttr<FormatAttr>())
15164        FD->addAttr(FormatAttr::CreateImplicit(Context,
15165                                               &Context.Idents.get("scanf"),
15166                                               FormatIdx+1,
15167                                               HasVAListArg ? 0 : FormatIdx+2,
15168                                               FD->getLocation()));
15169     }
15170 
15171     // Handle automatically recognized callbacks.
15172     SmallVector<int, 4> Encoding;
15173     if (!FD->hasAttr<CallbackAttr>() &&
15174         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15175       FD->addAttr(CallbackAttr::CreateImplicit(
15176           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15177 
15178     // Mark const if we don't care about errno and that is the only thing
15179     // preventing the function from being const. This allows IRgen to use LLVM
15180     // intrinsics for such functions.
15181     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15182         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15183       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15184 
15185     // We make "fma" on some platforms const because we know it does not set
15186     // errno in those environments even though it could set errno based on the
15187     // C standard.
15188     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15189     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15190         !FD->hasAttr<ConstAttr>()) {
15191       switch (BuiltinID) {
15192       case Builtin::BI__builtin_fma:
15193       case Builtin::BI__builtin_fmaf:
15194       case Builtin::BI__builtin_fmal:
15195       case Builtin::BIfma:
15196       case Builtin::BIfmaf:
15197       case Builtin::BIfmal:
15198         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15199         break;
15200       default:
15201         break;
15202       }
15203     }
15204 
15205     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15206         !FD->hasAttr<ReturnsTwiceAttr>())
15207       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15208                                          FD->getLocation()));
15209     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15210       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15211     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15212       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15213     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15214       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15215     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15216         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15217       // Add the appropriate attribute, depending on the CUDA compilation mode
15218       // and which target the builtin belongs to. For example, during host
15219       // compilation, aux builtins are __device__, while the rest are __host__.
15220       if (getLangOpts().CUDAIsDevice !=
15221           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15222         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15223       else
15224         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15225     }
15226 
15227     // Add known guaranteed alignment for allocation functions.
15228     switch (BuiltinID) {
15229     case Builtin::BIaligned_alloc:
15230       if (!FD->hasAttr<AllocAlignAttr>())
15231         FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15232                                                    FD->getLocation()));
15233       LLVM_FALLTHROUGH;
15234     case Builtin::BIcalloc:
15235     case Builtin::BImalloc:
15236     case Builtin::BImemalign:
15237     case Builtin::BIrealloc:
15238     case Builtin::BIstrdup:
15239     case Builtin::BIstrndup: {
15240       if (!FD->hasAttr<AssumeAlignedAttr>()) {
15241         unsigned NewAlign = Context.getTargetInfo().getNewAlign() /
15242                             Context.getTargetInfo().getCharWidth();
15243         IntegerLiteral *Alignment = IntegerLiteral::Create(
15244             Context, Context.MakeIntValue(NewAlign, Context.UnsignedIntTy),
15245             Context.UnsignedIntTy, FD->getLocation());
15246         FD->addAttr(AssumeAlignedAttr::CreateImplicit(
15247             Context, Alignment, /*Offset=*/nullptr, FD->getLocation()));
15248       }
15249       break;
15250     }
15251     default:
15252       break;
15253     }
15254   }
15255 
15256   AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15257 
15258   // If C++ exceptions are enabled but we are told extern "C" functions cannot
15259   // throw, add an implicit nothrow attribute to any extern "C" function we come
15260   // across.
15261   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15262       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15263     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15264     if (!FPT || FPT->getExceptionSpecType() == EST_None)
15265       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15266   }
15267 
15268   IdentifierInfo *Name = FD->getIdentifier();
15269   if (!Name)
15270     return;
15271   if ((!getLangOpts().CPlusPlus &&
15272        FD->getDeclContext()->isTranslationUnit()) ||
15273       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15274        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15275        LinkageSpecDecl::lang_c)) {
15276     // Okay: this could be a libc/libm/Objective-C function we know
15277     // about.
15278   } else
15279     return;
15280 
15281   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15282     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15283     // target-specific builtins, perhaps?
15284     if (!FD->hasAttr<FormatAttr>())
15285       FD->addAttr(FormatAttr::CreateImplicit(Context,
15286                                              &Context.Idents.get("printf"), 2,
15287                                              Name->isStr("vasprintf") ? 0 : 3,
15288                                              FD->getLocation()));
15289   }
15290 
15291   if (Name->isStr("__CFStringMakeConstantString")) {
15292     // We already have a __builtin___CFStringMakeConstantString,
15293     // but builds that use -fno-constant-cfstrings don't go through that.
15294     if (!FD->hasAttr<FormatArgAttr>())
15295       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15296                                                 FD->getLocation()));
15297   }
15298 }
15299 
15300 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15301                                     TypeSourceInfo *TInfo) {
15302   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15303   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15304 
15305   if (!TInfo) {
15306     assert(D.isInvalidType() && "no declarator info for valid type");
15307     TInfo = Context.getTrivialTypeSourceInfo(T);
15308   }
15309 
15310   // Scope manipulation handled by caller.
15311   TypedefDecl *NewTD =
15312       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15313                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15314 
15315   // Bail out immediately if we have an invalid declaration.
15316   if (D.isInvalidType()) {
15317     NewTD->setInvalidDecl();
15318     return NewTD;
15319   }
15320 
15321   if (D.getDeclSpec().isModulePrivateSpecified()) {
15322     if (CurContext->isFunctionOrMethod())
15323       Diag(NewTD->getLocation(), diag::err_module_private_local)
15324           << 2 << NewTD
15325           << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15326           << FixItHint::CreateRemoval(
15327                  D.getDeclSpec().getModulePrivateSpecLoc());
15328     else
15329       NewTD->setModulePrivate();
15330   }
15331 
15332   // C++ [dcl.typedef]p8:
15333   //   If the typedef declaration defines an unnamed class (or
15334   //   enum), the first typedef-name declared by the declaration
15335   //   to be that class type (or enum type) is used to denote the
15336   //   class type (or enum type) for linkage purposes only.
15337   // We need to check whether the type was declared in the declaration.
15338   switch (D.getDeclSpec().getTypeSpecType()) {
15339   case TST_enum:
15340   case TST_struct:
15341   case TST_interface:
15342   case TST_union:
15343   case TST_class: {
15344     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15345     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15346     break;
15347   }
15348 
15349   default:
15350     break;
15351   }
15352 
15353   return NewTD;
15354 }
15355 
15356 /// Check that this is a valid underlying type for an enum declaration.
15357 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15358   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15359   QualType T = TI->getType();
15360 
15361   if (T->isDependentType())
15362     return false;
15363 
15364   // This doesn't use 'isIntegralType' despite the error message mentioning
15365   // integral type because isIntegralType would also allow enum types in C.
15366   if (const BuiltinType *BT = T->getAs<BuiltinType>())
15367     if (BT->isInteger())
15368       return false;
15369 
15370   if (T->isBitIntType())
15371     return false;
15372 
15373   return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15374 }
15375 
15376 /// Check whether this is a valid redeclaration of a previous enumeration.
15377 /// \return true if the redeclaration was invalid.
15378 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15379                                   QualType EnumUnderlyingTy, bool IsFixed,
15380                                   const EnumDecl *Prev) {
15381   if (IsScoped != Prev->isScoped()) {
15382     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15383       << Prev->isScoped();
15384     Diag(Prev->getLocation(), diag::note_previous_declaration);
15385     return true;
15386   }
15387 
15388   if (IsFixed && Prev->isFixed()) {
15389     if (!EnumUnderlyingTy->isDependentType() &&
15390         !Prev->getIntegerType()->isDependentType() &&
15391         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15392                                         Prev->getIntegerType())) {
15393       // TODO: Highlight the underlying type of the redeclaration.
15394       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15395         << EnumUnderlyingTy << Prev->getIntegerType();
15396       Diag(Prev->getLocation(), diag::note_previous_declaration)
15397           << Prev->getIntegerTypeRange();
15398       return true;
15399     }
15400   } else if (IsFixed != Prev->isFixed()) {
15401     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15402       << Prev->isFixed();
15403     Diag(Prev->getLocation(), diag::note_previous_declaration);
15404     return true;
15405   }
15406 
15407   return false;
15408 }
15409 
15410 /// Get diagnostic %select index for tag kind for
15411 /// redeclaration diagnostic message.
15412 /// WARNING: Indexes apply to particular diagnostics only!
15413 ///
15414 /// \returns diagnostic %select index.
15415 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15416   switch (Tag) {
15417   case TTK_Struct: return 0;
15418   case TTK_Interface: return 1;
15419   case TTK_Class:  return 2;
15420   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15421   }
15422 }
15423 
15424 /// Determine if tag kind is a class-key compatible with
15425 /// class for redeclaration (class, struct, or __interface).
15426 ///
15427 /// \returns true iff the tag kind is compatible.
15428 static bool isClassCompatTagKind(TagTypeKind Tag)
15429 {
15430   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15431 }
15432 
15433 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15434                                              TagTypeKind TTK) {
15435   if (isa<TypedefDecl>(PrevDecl))
15436     return NTK_Typedef;
15437   else if (isa<TypeAliasDecl>(PrevDecl))
15438     return NTK_TypeAlias;
15439   else if (isa<ClassTemplateDecl>(PrevDecl))
15440     return NTK_Template;
15441   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15442     return NTK_TypeAliasTemplate;
15443   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15444     return NTK_TemplateTemplateArgument;
15445   switch (TTK) {
15446   case TTK_Struct:
15447   case TTK_Interface:
15448   case TTK_Class:
15449     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15450   case TTK_Union:
15451     return NTK_NonUnion;
15452   case TTK_Enum:
15453     return NTK_NonEnum;
15454   }
15455   llvm_unreachable("invalid TTK");
15456 }
15457 
15458 /// Determine whether a tag with a given kind is acceptable
15459 /// as a redeclaration of the given tag declaration.
15460 ///
15461 /// \returns true if the new tag kind is acceptable, false otherwise.
15462 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15463                                         TagTypeKind NewTag, bool isDefinition,
15464                                         SourceLocation NewTagLoc,
15465                                         const IdentifierInfo *Name) {
15466   // C++ [dcl.type.elab]p3:
15467   //   The class-key or enum keyword present in the
15468   //   elaborated-type-specifier shall agree in kind with the
15469   //   declaration to which the name in the elaborated-type-specifier
15470   //   refers. This rule also applies to the form of
15471   //   elaborated-type-specifier that declares a class-name or
15472   //   friend class since it can be construed as referring to the
15473   //   definition of the class. Thus, in any
15474   //   elaborated-type-specifier, the enum keyword shall be used to
15475   //   refer to an enumeration (7.2), the union class-key shall be
15476   //   used to refer to a union (clause 9), and either the class or
15477   //   struct class-key shall be used to refer to a class (clause 9)
15478   //   declared using the class or struct class-key.
15479   TagTypeKind OldTag = Previous->getTagKind();
15480   if (OldTag != NewTag &&
15481       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15482     return false;
15483 
15484   // Tags are compatible, but we might still want to warn on mismatched tags.
15485   // Non-class tags can't be mismatched at this point.
15486   if (!isClassCompatTagKind(NewTag))
15487     return true;
15488 
15489   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15490   // by our warning analysis. We don't want to warn about mismatches with (eg)
15491   // declarations in system headers that are designed to be specialized, but if
15492   // a user asks us to warn, we should warn if their code contains mismatched
15493   // declarations.
15494   auto IsIgnoredLoc = [&](SourceLocation Loc) {
15495     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15496                                       Loc);
15497   };
15498   if (IsIgnoredLoc(NewTagLoc))
15499     return true;
15500 
15501   auto IsIgnored = [&](const TagDecl *Tag) {
15502     return IsIgnoredLoc(Tag->getLocation());
15503   };
15504   while (IsIgnored(Previous)) {
15505     Previous = Previous->getPreviousDecl();
15506     if (!Previous)
15507       return true;
15508     OldTag = Previous->getTagKind();
15509   }
15510 
15511   bool isTemplate = false;
15512   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15513     isTemplate = Record->getDescribedClassTemplate();
15514 
15515   if (inTemplateInstantiation()) {
15516     if (OldTag != NewTag) {
15517       // In a template instantiation, do not offer fix-its for tag mismatches
15518       // since they usually mess up the template instead of fixing the problem.
15519       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15520         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15521         << getRedeclDiagFromTagKind(OldTag);
15522       // FIXME: Note previous location?
15523     }
15524     return true;
15525   }
15526 
15527   if (isDefinition) {
15528     // On definitions, check all previous tags and issue a fix-it for each
15529     // one that doesn't match the current tag.
15530     if (Previous->getDefinition()) {
15531       // Don't suggest fix-its for redefinitions.
15532       return true;
15533     }
15534 
15535     bool previousMismatch = false;
15536     for (const TagDecl *I : Previous->redecls()) {
15537       if (I->getTagKind() != NewTag) {
15538         // Ignore previous declarations for which the warning was disabled.
15539         if (IsIgnored(I))
15540           continue;
15541 
15542         if (!previousMismatch) {
15543           previousMismatch = true;
15544           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15545             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15546             << getRedeclDiagFromTagKind(I->getTagKind());
15547         }
15548         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15549           << getRedeclDiagFromTagKind(NewTag)
15550           << FixItHint::CreateReplacement(I->getInnerLocStart(),
15551                TypeWithKeyword::getTagTypeKindName(NewTag));
15552       }
15553     }
15554     return true;
15555   }
15556 
15557   // Identify the prevailing tag kind: this is the kind of the definition (if
15558   // there is a non-ignored definition), or otherwise the kind of the prior
15559   // (non-ignored) declaration.
15560   const TagDecl *PrevDef = Previous->getDefinition();
15561   if (PrevDef && IsIgnored(PrevDef))
15562     PrevDef = nullptr;
15563   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15564   if (Redecl->getTagKind() != NewTag) {
15565     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15566       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15567       << getRedeclDiagFromTagKind(OldTag);
15568     Diag(Redecl->getLocation(), diag::note_previous_use);
15569 
15570     // If there is a previous definition, suggest a fix-it.
15571     if (PrevDef) {
15572       Diag(NewTagLoc, diag::note_struct_class_suggestion)
15573         << getRedeclDiagFromTagKind(Redecl->getTagKind())
15574         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15575              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15576     }
15577   }
15578 
15579   return true;
15580 }
15581 
15582 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15583 /// from an outer enclosing namespace or file scope inside a friend declaration.
15584 /// This should provide the commented out code in the following snippet:
15585 ///   namespace N {
15586 ///     struct X;
15587 ///     namespace M {
15588 ///       struct Y { friend struct /*N::*/ X; };
15589 ///     }
15590 ///   }
15591 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15592                                          SourceLocation NameLoc) {
15593   // While the decl is in a namespace, do repeated lookup of that name and see
15594   // if we get the same namespace back.  If we do not, continue until
15595   // translation unit scope, at which point we have a fully qualified NNS.
15596   SmallVector<IdentifierInfo *, 4> Namespaces;
15597   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15598   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15599     // This tag should be declared in a namespace, which can only be enclosed by
15600     // other namespaces.  Bail if there's an anonymous namespace in the chain.
15601     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15602     if (!Namespace || Namespace->isAnonymousNamespace())
15603       return FixItHint();
15604     IdentifierInfo *II = Namespace->getIdentifier();
15605     Namespaces.push_back(II);
15606     NamedDecl *Lookup = SemaRef.LookupSingleName(
15607         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15608     if (Lookup == Namespace)
15609       break;
15610   }
15611 
15612   // Once we have all the namespaces, reverse them to go outermost first, and
15613   // build an NNS.
15614   SmallString<64> Insertion;
15615   llvm::raw_svector_ostream OS(Insertion);
15616   if (DC->isTranslationUnit())
15617     OS << "::";
15618   std::reverse(Namespaces.begin(), Namespaces.end());
15619   for (auto *II : Namespaces)
15620     OS << II->getName() << "::";
15621   return FixItHint::CreateInsertion(NameLoc, Insertion);
15622 }
15623 
15624 /// Determine whether a tag originally declared in context \p OldDC can
15625 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15626 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15627 /// using-declaration).
15628 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15629                                          DeclContext *NewDC) {
15630   OldDC = OldDC->getRedeclContext();
15631   NewDC = NewDC->getRedeclContext();
15632 
15633   if (OldDC->Equals(NewDC))
15634     return true;
15635 
15636   // In MSVC mode, we allow a redeclaration if the contexts are related (either
15637   // encloses the other).
15638   if (S.getLangOpts().MSVCCompat &&
15639       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15640     return true;
15641 
15642   return false;
15643 }
15644 
15645 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
15646 /// former case, Name will be non-null.  In the later case, Name will be null.
15647 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15648 /// reference/declaration/definition of a tag.
15649 ///
15650 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15651 /// trailing-type-specifier) other than one in an alias-declaration.
15652 ///
15653 /// \param SkipBody If non-null, will be set to indicate if the caller should
15654 /// skip the definition of this tag and treat it as if it were a declaration.
15655 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15656                      SourceLocation KWLoc, CXXScopeSpec &SS,
15657                      IdentifierInfo *Name, SourceLocation NameLoc,
15658                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
15659                      SourceLocation ModulePrivateLoc,
15660                      MultiTemplateParamsArg TemplateParameterLists,
15661                      bool &OwnedDecl, bool &IsDependent,
15662                      SourceLocation ScopedEnumKWLoc,
15663                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15664                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15665                      SkipBodyInfo *SkipBody) {
15666   // If this is not a definition, it must have a name.
15667   IdentifierInfo *OrigName = Name;
15668   assert((Name != nullptr || TUK == TUK_Definition) &&
15669          "Nameless record must be a definition!");
15670   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15671 
15672   OwnedDecl = false;
15673   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15674   bool ScopedEnum = ScopedEnumKWLoc.isValid();
15675 
15676   // FIXME: Check member specializations more carefully.
15677   bool isMemberSpecialization = false;
15678   bool Invalid = false;
15679 
15680   // We only need to do this matching if we have template parameters
15681   // or a scope specifier, which also conveniently avoids this work
15682   // for non-C++ cases.
15683   if (TemplateParameterLists.size() > 0 ||
15684       (SS.isNotEmpty() && TUK != TUK_Reference)) {
15685     if (TemplateParameterList *TemplateParams =
15686             MatchTemplateParametersToScopeSpecifier(
15687                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15688                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15689       if (Kind == TTK_Enum) {
15690         Diag(KWLoc, diag::err_enum_template);
15691         return nullptr;
15692       }
15693 
15694       if (TemplateParams->size() > 0) {
15695         // This is a declaration or definition of a class template (which may
15696         // be a member of another template).
15697 
15698         if (Invalid)
15699           return nullptr;
15700 
15701         OwnedDecl = false;
15702         DeclResult Result = CheckClassTemplate(
15703             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15704             AS, ModulePrivateLoc,
15705             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15706             TemplateParameterLists.data(), SkipBody);
15707         return Result.get();
15708       } else {
15709         // The "template<>" header is extraneous.
15710         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15711           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15712         isMemberSpecialization = true;
15713       }
15714     }
15715 
15716     if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15717         CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15718       return nullptr;
15719   }
15720 
15721   // Figure out the underlying type if this a enum declaration. We need to do
15722   // this early, because it's needed to detect if this is an incompatible
15723   // redeclaration.
15724   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15725   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15726 
15727   if (Kind == TTK_Enum) {
15728     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15729       // No underlying type explicitly specified, or we failed to parse the
15730       // type, default to int.
15731       EnumUnderlying = Context.IntTy.getTypePtr();
15732     } else if (UnderlyingType.get()) {
15733       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15734       // integral type; any cv-qualification is ignored.
15735       TypeSourceInfo *TI = nullptr;
15736       GetTypeFromParser(UnderlyingType.get(), &TI);
15737       EnumUnderlying = TI;
15738 
15739       if (CheckEnumUnderlyingType(TI))
15740         // Recover by falling back to int.
15741         EnumUnderlying = Context.IntTy.getTypePtr();
15742 
15743       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15744                                           UPPC_FixedUnderlyingType))
15745         EnumUnderlying = Context.IntTy.getTypePtr();
15746 
15747     } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15748       // For MSVC ABI compatibility, unfixed enums must use an underlying type
15749       // of 'int'. However, if this is an unfixed forward declaration, don't set
15750       // the underlying type unless the user enables -fms-compatibility. This
15751       // makes unfixed forward declared enums incomplete and is more conforming.
15752       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15753         EnumUnderlying = Context.IntTy.getTypePtr();
15754     }
15755   }
15756 
15757   DeclContext *SearchDC = CurContext;
15758   DeclContext *DC = CurContext;
15759   bool isStdBadAlloc = false;
15760   bool isStdAlignValT = false;
15761 
15762   RedeclarationKind Redecl = forRedeclarationInCurContext();
15763   if (TUK == TUK_Friend || TUK == TUK_Reference)
15764     Redecl = NotForRedeclaration;
15765 
15766   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15767   /// implemented asks for structural equivalence checking, the returned decl
15768   /// here is passed back to the parser, allowing the tag body to be parsed.
15769   auto createTagFromNewDecl = [&]() -> TagDecl * {
15770     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15771     // If there is an identifier, use the location of the identifier as the
15772     // location of the decl, otherwise use the location of the struct/union
15773     // keyword.
15774     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15775     TagDecl *New = nullptr;
15776 
15777     if (Kind == TTK_Enum) {
15778       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15779                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15780       // If this is an undefined enum, bail.
15781       if (TUK != TUK_Definition && !Invalid)
15782         return nullptr;
15783       if (EnumUnderlying) {
15784         EnumDecl *ED = cast<EnumDecl>(New);
15785         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15786           ED->setIntegerTypeSourceInfo(TI);
15787         else
15788           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15789         ED->setPromotionType(ED->getIntegerType());
15790       }
15791     } else { // struct/union
15792       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15793                                nullptr);
15794     }
15795 
15796     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15797       // Add alignment attributes if necessary; these attributes are checked
15798       // when the ASTContext lays out the structure.
15799       //
15800       // It is important for implementing the correct semantics that this
15801       // happen here (in ActOnTag). The #pragma pack stack is
15802       // maintained as a result of parser callbacks which can occur at
15803       // many points during the parsing of a struct declaration (because
15804       // the #pragma tokens are effectively skipped over during the
15805       // parsing of the struct).
15806       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15807         AddAlignmentAttributesForRecord(RD);
15808         AddMsStructLayoutForRecord(RD);
15809       }
15810     }
15811     New->setLexicalDeclContext(CurContext);
15812     return New;
15813   };
15814 
15815   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15816   if (Name && SS.isNotEmpty()) {
15817     // We have a nested-name tag ('struct foo::bar').
15818 
15819     // Check for invalid 'foo::'.
15820     if (SS.isInvalid()) {
15821       Name = nullptr;
15822       goto CreateNewDecl;
15823     }
15824 
15825     // If this is a friend or a reference to a class in a dependent
15826     // context, don't try to make a decl for it.
15827     if (TUK == TUK_Friend || TUK == TUK_Reference) {
15828       DC = computeDeclContext(SS, false);
15829       if (!DC) {
15830         IsDependent = true;
15831         return nullptr;
15832       }
15833     } else {
15834       DC = computeDeclContext(SS, true);
15835       if (!DC) {
15836         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15837           << SS.getRange();
15838         return nullptr;
15839       }
15840     }
15841 
15842     if (RequireCompleteDeclContext(SS, DC))
15843       return nullptr;
15844 
15845     SearchDC = DC;
15846     // Look-up name inside 'foo::'.
15847     LookupQualifiedName(Previous, DC);
15848 
15849     if (Previous.isAmbiguous())
15850       return nullptr;
15851 
15852     if (Previous.empty()) {
15853       // Name lookup did not find anything. However, if the
15854       // nested-name-specifier refers to the current instantiation,
15855       // and that current instantiation has any dependent base
15856       // classes, we might find something at instantiation time: treat
15857       // this as a dependent elaborated-type-specifier.
15858       // But this only makes any sense for reference-like lookups.
15859       if (Previous.wasNotFoundInCurrentInstantiation() &&
15860           (TUK == TUK_Reference || TUK == TUK_Friend)) {
15861         IsDependent = true;
15862         return nullptr;
15863       }
15864 
15865       // A tag 'foo::bar' must already exist.
15866       Diag(NameLoc, diag::err_not_tag_in_scope)
15867         << Kind << Name << DC << SS.getRange();
15868       Name = nullptr;
15869       Invalid = true;
15870       goto CreateNewDecl;
15871     }
15872   } else if (Name) {
15873     // C++14 [class.mem]p14:
15874     //   If T is the name of a class, then each of the following shall have a
15875     //   name different from T:
15876     //    -- every member of class T that is itself a type
15877     if (TUK != TUK_Reference && TUK != TUK_Friend &&
15878         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15879       return nullptr;
15880 
15881     // If this is a named struct, check to see if there was a previous forward
15882     // declaration or definition.
15883     // FIXME: We're looking into outer scopes here, even when we
15884     // shouldn't be. Doing so can result in ambiguities that we
15885     // shouldn't be diagnosing.
15886     LookupName(Previous, S);
15887 
15888     // When declaring or defining a tag, ignore ambiguities introduced
15889     // by types using'ed into this scope.
15890     if (Previous.isAmbiguous() &&
15891         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15892       LookupResult::Filter F = Previous.makeFilter();
15893       while (F.hasNext()) {
15894         NamedDecl *ND = F.next();
15895         if (!ND->getDeclContext()->getRedeclContext()->Equals(
15896                 SearchDC->getRedeclContext()))
15897           F.erase();
15898       }
15899       F.done();
15900     }
15901 
15902     // C++11 [namespace.memdef]p3:
15903     //   If the name in a friend declaration is neither qualified nor
15904     //   a template-id and the declaration is a function or an
15905     //   elaborated-type-specifier, the lookup to determine whether
15906     //   the entity has been previously declared shall not consider
15907     //   any scopes outside the innermost enclosing namespace.
15908     //
15909     // MSVC doesn't implement the above rule for types, so a friend tag
15910     // declaration may be a redeclaration of a type declared in an enclosing
15911     // scope.  They do implement this rule for friend functions.
15912     //
15913     // Does it matter that this should be by scope instead of by
15914     // semantic context?
15915     if (!Previous.empty() && TUK == TUK_Friend) {
15916       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15917       LookupResult::Filter F = Previous.makeFilter();
15918       bool FriendSawTagOutsideEnclosingNamespace = false;
15919       while (F.hasNext()) {
15920         NamedDecl *ND = F.next();
15921         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15922         if (DC->isFileContext() &&
15923             !EnclosingNS->Encloses(ND->getDeclContext())) {
15924           if (getLangOpts().MSVCCompat)
15925             FriendSawTagOutsideEnclosingNamespace = true;
15926           else
15927             F.erase();
15928         }
15929       }
15930       F.done();
15931 
15932       // Diagnose this MSVC extension in the easy case where lookup would have
15933       // unambiguously found something outside the enclosing namespace.
15934       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15935         NamedDecl *ND = Previous.getFoundDecl();
15936         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15937             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15938       }
15939     }
15940 
15941     // Note:  there used to be some attempt at recovery here.
15942     if (Previous.isAmbiguous())
15943       return nullptr;
15944 
15945     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15946       // FIXME: This makes sure that we ignore the contexts associated
15947       // with C structs, unions, and enums when looking for a matching
15948       // tag declaration or definition. See the similar lookup tweak
15949       // in Sema::LookupName; is there a better way to deal with this?
15950       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15951         SearchDC = SearchDC->getParent();
15952     }
15953   }
15954 
15955   if (Previous.isSingleResult() &&
15956       Previous.getFoundDecl()->isTemplateParameter()) {
15957     // Maybe we will complain about the shadowed template parameter.
15958     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15959     // Just pretend that we didn't see the previous declaration.
15960     Previous.clear();
15961   }
15962 
15963   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15964       DC->Equals(getStdNamespace())) {
15965     if (Name->isStr("bad_alloc")) {
15966       // This is a declaration of or a reference to "std::bad_alloc".
15967       isStdBadAlloc = true;
15968 
15969       // If std::bad_alloc has been implicitly declared (but made invisible to
15970       // name lookup), fill in this implicit declaration as the previous
15971       // declaration, so that the declarations get chained appropriately.
15972       if (Previous.empty() && StdBadAlloc)
15973         Previous.addDecl(getStdBadAlloc());
15974     } else if (Name->isStr("align_val_t")) {
15975       isStdAlignValT = true;
15976       if (Previous.empty() && StdAlignValT)
15977         Previous.addDecl(getStdAlignValT());
15978     }
15979   }
15980 
15981   // If we didn't find a previous declaration, and this is a reference
15982   // (or friend reference), move to the correct scope.  In C++, we
15983   // also need to do a redeclaration lookup there, just in case
15984   // there's a shadow friend decl.
15985   if (Name && Previous.empty() &&
15986       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15987     if (Invalid) goto CreateNewDecl;
15988     assert(SS.isEmpty());
15989 
15990     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15991       // C++ [basic.scope.pdecl]p5:
15992       //   -- for an elaborated-type-specifier of the form
15993       //
15994       //          class-key identifier
15995       //
15996       //      if the elaborated-type-specifier is used in the
15997       //      decl-specifier-seq or parameter-declaration-clause of a
15998       //      function defined in namespace scope, the identifier is
15999       //      declared as a class-name in the namespace that contains
16000       //      the declaration; otherwise, except as a friend
16001       //      declaration, the identifier is declared in the smallest
16002       //      non-class, non-function-prototype scope that contains the
16003       //      declaration.
16004       //
16005       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16006       // C structs and unions.
16007       //
16008       // It is an error in C++ to declare (rather than define) an enum
16009       // type, including via an elaborated type specifier.  We'll
16010       // diagnose that later; for now, declare the enum in the same
16011       // scope as we would have picked for any other tag type.
16012       //
16013       // GNU C also supports this behavior as part of its incomplete
16014       // enum types extension, while GNU C++ does not.
16015       //
16016       // Find the context where we'll be declaring the tag.
16017       // FIXME: We would like to maintain the current DeclContext as the
16018       // lexical context,
16019       SearchDC = getTagInjectionContext(SearchDC);
16020 
16021       // Find the scope where we'll be declaring the tag.
16022       S = getTagInjectionScope(S, getLangOpts());
16023     } else {
16024       assert(TUK == TUK_Friend);
16025       // C++ [namespace.memdef]p3:
16026       //   If a friend declaration in a non-local class first declares a
16027       //   class or function, the friend class or function is a member of
16028       //   the innermost enclosing namespace.
16029       SearchDC = SearchDC->getEnclosingNamespaceContext();
16030     }
16031 
16032     // In C++, we need to do a redeclaration lookup to properly
16033     // diagnose some problems.
16034     // FIXME: redeclaration lookup is also used (with and without C++) to find a
16035     // hidden declaration so that we don't get ambiguity errors when using a
16036     // type declared by an elaborated-type-specifier.  In C that is not correct
16037     // and we should instead merge compatible types found by lookup.
16038     if (getLangOpts().CPlusPlus) {
16039       // FIXME: This can perform qualified lookups into function contexts,
16040       // which are meaningless.
16041       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16042       LookupQualifiedName(Previous, SearchDC);
16043     } else {
16044       Previous.setRedeclarationKind(forRedeclarationInCurContext());
16045       LookupName(Previous, S);
16046     }
16047   }
16048 
16049   // If we have a known previous declaration to use, then use it.
16050   if (Previous.empty() && SkipBody && SkipBody->Previous)
16051     Previous.addDecl(SkipBody->Previous);
16052 
16053   if (!Previous.empty()) {
16054     NamedDecl *PrevDecl = Previous.getFoundDecl();
16055     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16056 
16057     // It's okay to have a tag decl in the same scope as a typedef
16058     // which hides a tag decl in the same scope.  Finding this
16059     // with a redeclaration lookup can only actually happen in C++.
16060     //
16061     // This is also okay for elaborated-type-specifiers, which is
16062     // technically forbidden by the current standard but which is
16063     // okay according to the likely resolution of an open issue;
16064     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16065     if (getLangOpts().CPlusPlus) {
16066       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16067         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16068           TagDecl *Tag = TT->getDecl();
16069           if (Tag->getDeclName() == Name &&
16070               Tag->getDeclContext()->getRedeclContext()
16071                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
16072             PrevDecl = Tag;
16073             Previous.clear();
16074             Previous.addDecl(Tag);
16075             Previous.resolveKind();
16076           }
16077         }
16078       }
16079     }
16080 
16081     // If this is a redeclaration of a using shadow declaration, it must
16082     // declare a tag in the same context. In MSVC mode, we allow a
16083     // redefinition if either context is within the other.
16084     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16085       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16086       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16087           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16088           !(OldTag && isAcceptableTagRedeclContext(
16089                           *this, OldTag->getDeclContext(), SearchDC))) {
16090         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16091         Diag(Shadow->getTargetDecl()->getLocation(),
16092              diag::note_using_decl_target);
16093         Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16094             << 0;
16095         // Recover by ignoring the old declaration.
16096         Previous.clear();
16097         goto CreateNewDecl;
16098       }
16099     }
16100 
16101     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16102       // If this is a use of a previous tag, or if the tag is already declared
16103       // in the same scope (so that the definition/declaration completes or
16104       // rementions the tag), reuse the decl.
16105       if (TUK == TUK_Reference || TUK == TUK_Friend ||
16106           isDeclInScope(DirectPrevDecl, SearchDC, S,
16107                         SS.isNotEmpty() || isMemberSpecialization)) {
16108         // Make sure that this wasn't declared as an enum and now used as a
16109         // struct or something similar.
16110         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16111                                           TUK == TUK_Definition, KWLoc,
16112                                           Name)) {
16113           bool SafeToContinue
16114             = (PrevTagDecl->getTagKind() != TTK_Enum &&
16115                Kind != TTK_Enum);
16116           if (SafeToContinue)
16117             Diag(KWLoc, diag::err_use_with_wrong_tag)
16118               << Name
16119               << FixItHint::CreateReplacement(SourceRange(KWLoc),
16120                                               PrevTagDecl->getKindName());
16121           else
16122             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16123           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16124 
16125           if (SafeToContinue)
16126             Kind = PrevTagDecl->getTagKind();
16127           else {
16128             // Recover by making this an anonymous redefinition.
16129             Name = nullptr;
16130             Previous.clear();
16131             Invalid = true;
16132           }
16133         }
16134 
16135         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16136           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16137           if (TUK == TUK_Reference || TUK == TUK_Friend)
16138             return PrevTagDecl;
16139 
16140           QualType EnumUnderlyingTy;
16141           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16142             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16143           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16144             EnumUnderlyingTy = QualType(T, 0);
16145 
16146           // All conflicts with previous declarations are recovered by
16147           // returning the previous declaration, unless this is a definition,
16148           // in which case we want the caller to bail out.
16149           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16150                                      ScopedEnum, EnumUnderlyingTy,
16151                                      IsFixed, PrevEnum))
16152             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16153         }
16154 
16155         // C++11 [class.mem]p1:
16156         //   A member shall not be declared twice in the member-specification,
16157         //   except that a nested class or member class template can be declared
16158         //   and then later defined.
16159         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16160             S->isDeclScope(PrevDecl)) {
16161           Diag(NameLoc, diag::ext_member_redeclared);
16162           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16163         }
16164 
16165         if (!Invalid) {
16166           // If this is a use, just return the declaration we found, unless
16167           // we have attributes.
16168           if (TUK == TUK_Reference || TUK == TUK_Friend) {
16169             if (!Attrs.empty()) {
16170               // FIXME: Diagnose these attributes. For now, we create a new
16171               // declaration to hold them.
16172             } else if (TUK == TUK_Reference &&
16173                        (PrevTagDecl->getFriendObjectKind() ==
16174                             Decl::FOK_Undeclared ||
16175                         PrevDecl->getOwningModule() != getCurrentModule()) &&
16176                        SS.isEmpty()) {
16177               // This declaration is a reference to an existing entity, but
16178               // has different visibility from that entity: it either makes
16179               // a friend visible or it makes a type visible in a new module.
16180               // In either case, create a new declaration. We only do this if
16181               // the declaration would have meant the same thing if no prior
16182               // declaration were found, that is, if it was found in the same
16183               // scope where we would have injected a declaration.
16184               if (!getTagInjectionContext(CurContext)->getRedeclContext()
16185                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16186                 return PrevTagDecl;
16187               // This is in the injected scope, create a new declaration in
16188               // that scope.
16189               S = getTagInjectionScope(S, getLangOpts());
16190             } else {
16191               return PrevTagDecl;
16192             }
16193           }
16194 
16195           // Diagnose attempts to redefine a tag.
16196           if (TUK == TUK_Definition) {
16197             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16198               // If we're defining a specialization and the previous definition
16199               // is from an implicit instantiation, don't emit an error
16200               // here; we'll catch this in the general case below.
16201               bool IsExplicitSpecializationAfterInstantiation = false;
16202               if (isMemberSpecialization) {
16203                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16204                   IsExplicitSpecializationAfterInstantiation =
16205                     RD->getTemplateSpecializationKind() !=
16206                     TSK_ExplicitSpecialization;
16207                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16208                   IsExplicitSpecializationAfterInstantiation =
16209                     ED->getTemplateSpecializationKind() !=
16210                     TSK_ExplicitSpecialization;
16211               }
16212 
16213               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16214               // not keep more that one definition around (merge them). However,
16215               // ensure the decl passes the structural compatibility check in
16216               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16217               NamedDecl *Hidden = nullptr;
16218               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16219                 // There is a definition of this tag, but it is not visible. We
16220                 // explicitly make use of C++'s one definition rule here, and
16221                 // assume that this definition is identical to the hidden one
16222                 // we already have. Make the existing definition visible and
16223                 // use it in place of this one.
16224                 if (!getLangOpts().CPlusPlus) {
16225                   // Postpone making the old definition visible until after we
16226                   // complete parsing the new one and do the structural
16227                   // comparison.
16228                   SkipBody->CheckSameAsPrevious = true;
16229                   SkipBody->New = createTagFromNewDecl();
16230                   SkipBody->Previous = Def;
16231                   return Def;
16232                 } else {
16233                   SkipBody->ShouldSkip = true;
16234                   SkipBody->Previous = Def;
16235                   makeMergedDefinitionVisible(Hidden);
16236                   // Carry on and handle it like a normal definition. We'll
16237                   // skip starting the definitiion later.
16238                 }
16239               } else if (!IsExplicitSpecializationAfterInstantiation) {
16240                 // A redeclaration in function prototype scope in C isn't
16241                 // visible elsewhere, so merely issue a warning.
16242                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16243                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16244                 else
16245                   Diag(NameLoc, diag::err_redefinition) << Name;
16246                 notePreviousDefinition(Def,
16247                                        NameLoc.isValid() ? NameLoc : KWLoc);
16248                 // If this is a redefinition, recover by making this
16249                 // struct be anonymous, which will make any later
16250                 // references get the previous definition.
16251                 Name = nullptr;
16252                 Previous.clear();
16253                 Invalid = true;
16254               }
16255             } else {
16256               // If the type is currently being defined, complain
16257               // about a nested redefinition.
16258               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16259               if (TD->isBeingDefined()) {
16260                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16261                 Diag(PrevTagDecl->getLocation(),
16262                      diag::note_previous_definition);
16263                 Name = nullptr;
16264                 Previous.clear();
16265                 Invalid = true;
16266               }
16267             }
16268 
16269             // Okay, this is definition of a previously declared or referenced
16270             // tag. We're going to create a new Decl for it.
16271           }
16272 
16273           // Okay, we're going to make a redeclaration.  If this is some kind
16274           // of reference, make sure we build the redeclaration in the same DC
16275           // as the original, and ignore the current access specifier.
16276           if (TUK == TUK_Friend || TUK == TUK_Reference) {
16277             SearchDC = PrevTagDecl->getDeclContext();
16278             AS = AS_none;
16279           }
16280         }
16281         // If we get here we have (another) forward declaration or we
16282         // have a definition.  Just create a new decl.
16283 
16284       } else {
16285         // If we get here, this is a definition of a new tag type in a nested
16286         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16287         // new decl/type.  We set PrevDecl to NULL so that the entities
16288         // have distinct types.
16289         Previous.clear();
16290       }
16291       // If we get here, we're going to create a new Decl. If PrevDecl
16292       // is non-NULL, it's a definition of the tag declared by
16293       // PrevDecl. If it's NULL, we have a new definition.
16294 
16295     // Otherwise, PrevDecl is not a tag, but was found with tag
16296     // lookup.  This is only actually possible in C++, where a few
16297     // things like templates still live in the tag namespace.
16298     } else {
16299       // Use a better diagnostic if an elaborated-type-specifier
16300       // found the wrong kind of type on the first
16301       // (non-redeclaration) lookup.
16302       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16303           !Previous.isForRedeclaration()) {
16304         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16305         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16306                                                        << Kind;
16307         Diag(PrevDecl->getLocation(), diag::note_declared_at);
16308         Invalid = true;
16309 
16310       // Otherwise, only diagnose if the declaration is in scope.
16311       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16312                                 SS.isNotEmpty() || isMemberSpecialization)) {
16313         // do nothing
16314 
16315       // Diagnose implicit declarations introduced by elaborated types.
16316       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16317         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16318         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16319         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16320         Invalid = true;
16321 
16322       // Otherwise it's a declaration.  Call out a particularly common
16323       // case here.
16324       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16325         unsigned Kind = 0;
16326         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16327         Diag(NameLoc, diag::err_tag_definition_of_typedef)
16328           << Name << Kind << TND->getUnderlyingType();
16329         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16330         Invalid = true;
16331 
16332       // Otherwise, diagnose.
16333       } else {
16334         // The tag name clashes with something else in the target scope,
16335         // issue an error and recover by making this tag be anonymous.
16336         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16337         notePreviousDefinition(PrevDecl, NameLoc);
16338         Name = nullptr;
16339         Invalid = true;
16340       }
16341 
16342       // The existing declaration isn't relevant to us; we're in a
16343       // new scope, so clear out the previous declaration.
16344       Previous.clear();
16345     }
16346   }
16347 
16348 CreateNewDecl:
16349 
16350   TagDecl *PrevDecl = nullptr;
16351   if (Previous.isSingleResult())
16352     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16353 
16354   // If there is an identifier, use the location of the identifier as the
16355   // location of the decl, otherwise use the location of the struct/union
16356   // keyword.
16357   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16358 
16359   // Otherwise, create a new declaration. If there is a previous
16360   // declaration of the same entity, the two will be linked via
16361   // PrevDecl.
16362   TagDecl *New;
16363 
16364   if (Kind == TTK_Enum) {
16365     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16366     // enum X { A, B, C } D;    D should chain to X.
16367     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16368                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16369                            ScopedEnumUsesClassTag, IsFixed);
16370 
16371     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16372       StdAlignValT = cast<EnumDecl>(New);
16373 
16374     // If this is an undefined enum, warn.
16375     if (TUK != TUK_Definition && !Invalid) {
16376       TagDecl *Def;
16377       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16378         // C++0x: 7.2p2: opaque-enum-declaration.
16379         // Conflicts are diagnosed above. Do nothing.
16380       }
16381       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16382         Diag(Loc, diag::ext_forward_ref_enum_def)
16383           << New;
16384         Diag(Def->getLocation(), diag::note_previous_definition);
16385       } else {
16386         unsigned DiagID = diag::ext_forward_ref_enum;
16387         if (getLangOpts().MSVCCompat)
16388           DiagID = diag::ext_ms_forward_ref_enum;
16389         else if (getLangOpts().CPlusPlus)
16390           DiagID = diag::err_forward_ref_enum;
16391         Diag(Loc, DiagID);
16392       }
16393     }
16394 
16395     if (EnumUnderlying) {
16396       EnumDecl *ED = cast<EnumDecl>(New);
16397       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16398         ED->setIntegerTypeSourceInfo(TI);
16399       else
16400         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16401       ED->setPromotionType(ED->getIntegerType());
16402       assert(ED->isComplete() && "enum with type should be complete");
16403     }
16404   } else {
16405     // struct/union/class
16406 
16407     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16408     // struct X { int A; } D;    D should chain to X.
16409     if (getLangOpts().CPlusPlus) {
16410       // FIXME: Look for a way to use RecordDecl for simple structs.
16411       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16412                                   cast_or_null<CXXRecordDecl>(PrevDecl));
16413 
16414       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16415         StdBadAlloc = cast<CXXRecordDecl>(New);
16416     } else
16417       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16418                                cast_or_null<RecordDecl>(PrevDecl));
16419   }
16420 
16421   // C++11 [dcl.type]p3:
16422   //   A type-specifier-seq shall not define a class or enumeration [...].
16423   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16424       TUK == TUK_Definition) {
16425     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16426       << Context.getTagDeclType(New);
16427     Invalid = true;
16428   }
16429 
16430   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16431       DC->getDeclKind() == Decl::Enum) {
16432     Diag(New->getLocation(), diag::err_type_defined_in_enum)
16433       << Context.getTagDeclType(New);
16434     Invalid = true;
16435   }
16436 
16437   // Maybe add qualifier info.
16438   if (SS.isNotEmpty()) {
16439     if (SS.isSet()) {
16440       // If this is either a declaration or a definition, check the
16441       // nested-name-specifier against the current context.
16442       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16443           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16444                                        isMemberSpecialization))
16445         Invalid = true;
16446 
16447       New->setQualifierInfo(SS.getWithLocInContext(Context));
16448       if (TemplateParameterLists.size() > 0) {
16449         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16450       }
16451     }
16452     else
16453       Invalid = true;
16454   }
16455 
16456   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16457     // Add alignment attributes if necessary; these attributes are checked when
16458     // the ASTContext lays out the structure.
16459     //
16460     // It is important for implementing the correct semantics that this
16461     // happen here (in ActOnTag). The #pragma pack stack is
16462     // maintained as a result of parser callbacks which can occur at
16463     // many points during the parsing of a struct declaration (because
16464     // the #pragma tokens are effectively skipped over during the
16465     // parsing of the struct).
16466     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16467       AddAlignmentAttributesForRecord(RD);
16468       AddMsStructLayoutForRecord(RD);
16469     }
16470   }
16471 
16472   if (ModulePrivateLoc.isValid()) {
16473     if (isMemberSpecialization)
16474       Diag(New->getLocation(), diag::err_module_private_specialization)
16475         << 2
16476         << FixItHint::CreateRemoval(ModulePrivateLoc);
16477     // __module_private__ does not apply to local classes. However, we only
16478     // diagnose this as an error when the declaration specifiers are
16479     // freestanding. Here, we just ignore the __module_private__.
16480     else if (!SearchDC->isFunctionOrMethod())
16481       New->setModulePrivate();
16482   }
16483 
16484   // If this is a specialization of a member class (of a class template),
16485   // check the specialization.
16486   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16487     Invalid = true;
16488 
16489   // If we're declaring or defining a tag in function prototype scope in C,
16490   // note that this type can only be used within the function and add it to
16491   // the list of decls to inject into the function definition scope.
16492   if ((Name || Kind == TTK_Enum) &&
16493       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16494     if (getLangOpts().CPlusPlus) {
16495       // C++ [dcl.fct]p6:
16496       //   Types shall not be defined in return or parameter types.
16497       if (TUK == TUK_Definition && !IsTypeSpecifier) {
16498         Diag(Loc, diag::err_type_defined_in_param_type)
16499             << Name;
16500         Invalid = true;
16501       }
16502     } else if (!PrevDecl) {
16503       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16504     }
16505   }
16506 
16507   if (Invalid)
16508     New->setInvalidDecl();
16509 
16510   // Set the lexical context. If the tag has a C++ scope specifier, the
16511   // lexical context will be different from the semantic context.
16512   New->setLexicalDeclContext(CurContext);
16513 
16514   // Mark this as a friend decl if applicable.
16515   // In Microsoft mode, a friend declaration also acts as a forward
16516   // declaration so we always pass true to setObjectOfFriendDecl to make
16517   // the tag name visible.
16518   if (TUK == TUK_Friend)
16519     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16520 
16521   // Set the access specifier.
16522   if (!Invalid && SearchDC->isRecord())
16523     SetMemberAccessSpecifier(New, PrevDecl, AS);
16524 
16525   if (PrevDecl)
16526     CheckRedeclarationModuleOwnership(New, PrevDecl);
16527 
16528   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16529     New->startDefinition();
16530 
16531   ProcessDeclAttributeList(S, New, Attrs);
16532   AddPragmaAttributes(S, New);
16533 
16534   // If this has an identifier, add it to the scope stack.
16535   if (TUK == TUK_Friend) {
16536     // We might be replacing an existing declaration in the lookup tables;
16537     // if so, borrow its access specifier.
16538     if (PrevDecl)
16539       New->setAccess(PrevDecl->getAccess());
16540 
16541     DeclContext *DC = New->getDeclContext()->getRedeclContext();
16542     DC->makeDeclVisibleInContext(New);
16543     if (Name) // can be null along some error paths
16544       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16545         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16546   } else if (Name) {
16547     S = getNonFieldDeclScope(S);
16548     PushOnScopeChains(New, S, true);
16549   } else {
16550     CurContext->addDecl(New);
16551   }
16552 
16553   // If this is the C FILE type, notify the AST context.
16554   if (IdentifierInfo *II = New->getIdentifier())
16555     if (!New->isInvalidDecl() &&
16556         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16557         II->isStr("FILE"))
16558       Context.setFILEDecl(New);
16559 
16560   if (PrevDecl)
16561     mergeDeclAttributes(New, PrevDecl);
16562 
16563   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16564     inferGslOwnerPointerAttribute(CXXRD);
16565 
16566   // If there's a #pragma GCC visibility in scope, set the visibility of this
16567   // record.
16568   AddPushedVisibilityAttribute(New);
16569 
16570   if (isMemberSpecialization && !New->isInvalidDecl())
16571     CompleteMemberSpecialization(New, Previous);
16572 
16573   OwnedDecl = true;
16574   // In C++, don't return an invalid declaration. We can't recover well from
16575   // the cases where we make the type anonymous.
16576   if (Invalid && getLangOpts().CPlusPlus) {
16577     if (New->isBeingDefined())
16578       if (auto RD = dyn_cast<RecordDecl>(New))
16579         RD->completeDefinition();
16580     return nullptr;
16581   } else if (SkipBody && SkipBody->ShouldSkip) {
16582     return SkipBody->Previous;
16583   } else {
16584     return New;
16585   }
16586 }
16587 
16588 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16589   AdjustDeclIfTemplate(TagD);
16590   TagDecl *Tag = cast<TagDecl>(TagD);
16591 
16592   // Enter the tag context.
16593   PushDeclContext(S, Tag);
16594 
16595   ActOnDocumentableDecl(TagD);
16596 
16597   // If there's a #pragma GCC visibility in scope, set the visibility of this
16598   // record.
16599   AddPushedVisibilityAttribute(Tag);
16600 }
16601 
16602 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16603                                     SkipBodyInfo &SkipBody) {
16604   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16605     return false;
16606 
16607   // Make the previous decl visible.
16608   makeMergedDefinitionVisible(SkipBody.Previous);
16609   return true;
16610 }
16611 
16612 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16613   assert(isa<ObjCContainerDecl>(IDecl) &&
16614          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16615   DeclContext *OCD = cast<DeclContext>(IDecl);
16616   assert(OCD->getLexicalParent() == CurContext &&
16617       "The next DeclContext should be lexically contained in the current one.");
16618   CurContext = OCD;
16619   return IDecl;
16620 }
16621 
16622 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16623                                            SourceLocation FinalLoc,
16624                                            bool IsFinalSpelledSealed,
16625                                            bool IsAbstract,
16626                                            SourceLocation LBraceLoc) {
16627   AdjustDeclIfTemplate(TagD);
16628   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16629 
16630   FieldCollector->StartClass();
16631 
16632   if (!Record->getIdentifier())
16633     return;
16634 
16635   if (IsAbstract)
16636     Record->markAbstract();
16637 
16638   if (FinalLoc.isValid()) {
16639     Record->addAttr(FinalAttr::Create(
16640         Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16641         static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16642   }
16643   // C++ [class]p2:
16644   //   [...] The class-name is also inserted into the scope of the
16645   //   class itself; this is known as the injected-class-name. For
16646   //   purposes of access checking, the injected-class-name is treated
16647   //   as if it were a public member name.
16648   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16649       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16650       Record->getLocation(), Record->getIdentifier(),
16651       /*PrevDecl=*/nullptr,
16652       /*DelayTypeCreation=*/true);
16653   Context.getTypeDeclType(InjectedClassName, Record);
16654   InjectedClassName->setImplicit();
16655   InjectedClassName->setAccess(AS_public);
16656   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16657       InjectedClassName->setDescribedClassTemplate(Template);
16658   PushOnScopeChains(InjectedClassName, S);
16659   assert(InjectedClassName->isInjectedClassName() &&
16660          "Broken injected-class-name");
16661 }
16662 
16663 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16664                                     SourceRange BraceRange) {
16665   AdjustDeclIfTemplate(TagD);
16666   TagDecl *Tag = cast<TagDecl>(TagD);
16667   Tag->setBraceRange(BraceRange);
16668 
16669   // Make sure we "complete" the definition even it is invalid.
16670   if (Tag->isBeingDefined()) {
16671     assert(Tag->isInvalidDecl() && "We should already have completed it");
16672     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16673       RD->completeDefinition();
16674   }
16675 
16676   if (isa<CXXRecordDecl>(Tag)) {
16677     FieldCollector->FinishClass();
16678   }
16679 
16680   // Exit this scope of this tag's definition.
16681   PopDeclContext();
16682 
16683   if (getCurLexicalContext()->isObjCContainer() &&
16684       Tag->getDeclContext()->isFileContext())
16685     Tag->setTopLevelDeclInObjCContainer();
16686 
16687   // Notify the consumer that we've defined a tag.
16688   if (!Tag->isInvalidDecl())
16689     Consumer.HandleTagDeclDefinition(Tag);
16690 
16691   // Clangs implementation of #pragma align(packed) differs in bitfield layout
16692   // from XLs and instead matches the XL #pragma pack(1) behavior.
16693   if (Context.getTargetInfo().getTriple().isOSAIX() &&
16694       AlignPackStack.hasValue()) {
16695     AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16696     // Only diagnose #pragma align(packed).
16697     if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16698       return;
16699     const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16700     if (!RD)
16701       return;
16702     // Only warn if there is at least 1 bitfield member.
16703     if (llvm::any_of(RD->fields(),
16704                      [](const FieldDecl *FD) { return FD->isBitField(); }))
16705       Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16706   }
16707 }
16708 
16709 void Sema::ActOnObjCContainerFinishDefinition() {
16710   // Exit this scope of this interface definition.
16711   PopDeclContext();
16712 }
16713 
16714 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16715   assert(DC == CurContext && "Mismatch of container contexts");
16716   OriginalLexicalContext = DC;
16717   ActOnObjCContainerFinishDefinition();
16718 }
16719 
16720 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16721   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16722   OriginalLexicalContext = nullptr;
16723 }
16724 
16725 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16726   AdjustDeclIfTemplate(TagD);
16727   TagDecl *Tag = cast<TagDecl>(TagD);
16728   Tag->setInvalidDecl();
16729 
16730   // Make sure we "complete" the definition even it is invalid.
16731   if (Tag->isBeingDefined()) {
16732     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16733       RD->completeDefinition();
16734   }
16735 
16736   // We're undoing ActOnTagStartDefinition here, not
16737   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16738   // the FieldCollector.
16739 
16740   PopDeclContext();
16741 }
16742 
16743 // Note that FieldName may be null for anonymous bitfields.
16744 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16745                                 IdentifierInfo *FieldName,
16746                                 QualType FieldTy, bool IsMsStruct,
16747                                 Expr *BitWidth, bool *ZeroWidth) {
16748   assert(BitWidth);
16749   if (BitWidth->containsErrors())
16750     return ExprError();
16751 
16752   // Default to true; that shouldn't confuse checks for emptiness
16753   if (ZeroWidth)
16754     *ZeroWidth = true;
16755 
16756   // C99 6.7.2.1p4 - verify the field type.
16757   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16758   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16759     // Handle incomplete and sizeless types with a specific error.
16760     if (RequireCompleteSizedType(FieldLoc, FieldTy,
16761                                  diag::err_field_incomplete_or_sizeless))
16762       return ExprError();
16763     if (FieldName)
16764       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16765         << FieldName << FieldTy << BitWidth->getSourceRange();
16766     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16767       << FieldTy << BitWidth->getSourceRange();
16768   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16769                                              UPPC_BitFieldWidth))
16770     return ExprError();
16771 
16772   // If the bit-width is type- or value-dependent, don't try to check
16773   // it now.
16774   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16775     return BitWidth;
16776 
16777   llvm::APSInt Value;
16778   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16779   if (ICE.isInvalid())
16780     return ICE;
16781   BitWidth = ICE.get();
16782 
16783   if (Value != 0 && ZeroWidth)
16784     *ZeroWidth = false;
16785 
16786   // Zero-width bitfield is ok for anonymous field.
16787   if (Value == 0 && FieldName)
16788     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16789 
16790   if (Value.isSigned() && Value.isNegative()) {
16791     if (FieldName)
16792       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16793                << FieldName << toString(Value, 10);
16794     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16795       << toString(Value, 10);
16796   }
16797 
16798   // The size of the bit-field must not exceed our maximum permitted object
16799   // size.
16800   if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16801     return Diag(FieldLoc, diag::err_bitfield_too_wide)
16802            << !FieldName << FieldName << toString(Value, 10);
16803   }
16804 
16805   if (!FieldTy->isDependentType()) {
16806     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16807     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16808     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16809 
16810     // Over-wide bitfields are an error in C or when using the MSVC bitfield
16811     // ABI.
16812     bool CStdConstraintViolation =
16813         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16814     bool MSBitfieldViolation =
16815         Value.ugt(TypeStorageSize) &&
16816         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16817     if (CStdConstraintViolation || MSBitfieldViolation) {
16818       unsigned DiagWidth =
16819           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16820       return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16821              << (bool)FieldName << FieldName << toString(Value, 10)
16822              << !CStdConstraintViolation << DiagWidth;
16823     }
16824 
16825     // Warn on types where the user might conceivably expect to get all
16826     // specified bits as value bits: that's all integral types other than
16827     // 'bool'.
16828     if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16829       Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16830           << FieldName << toString(Value, 10)
16831           << (unsigned)TypeWidth;
16832     }
16833   }
16834 
16835   return BitWidth;
16836 }
16837 
16838 /// ActOnField - Each field of a C struct/union is passed into this in order
16839 /// to create a FieldDecl object for it.
16840 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16841                        Declarator &D, Expr *BitfieldWidth) {
16842   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16843                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16844                                /*InitStyle=*/ICIS_NoInit, AS_public);
16845   return Res;
16846 }
16847 
16848 /// HandleField - Analyze a field of a C struct or a C++ data member.
16849 ///
16850 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16851                              SourceLocation DeclStart,
16852                              Declarator &D, Expr *BitWidth,
16853                              InClassInitStyle InitStyle,
16854                              AccessSpecifier AS) {
16855   if (D.isDecompositionDeclarator()) {
16856     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16857     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16858       << Decomp.getSourceRange();
16859     return nullptr;
16860   }
16861 
16862   IdentifierInfo *II = D.getIdentifier();
16863   SourceLocation Loc = DeclStart;
16864   if (II) Loc = D.getIdentifierLoc();
16865 
16866   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16867   QualType T = TInfo->getType();
16868   if (getLangOpts().CPlusPlus) {
16869     CheckExtraCXXDefaultArguments(D);
16870 
16871     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16872                                         UPPC_DataMemberType)) {
16873       D.setInvalidType();
16874       T = Context.IntTy;
16875       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16876     }
16877   }
16878 
16879   DiagnoseFunctionSpecifiers(D.getDeclSpec());
16880 
16881   if (D.getDeclSpec().isInlineSpecified())
16882     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16883         << getLangOpts().CPlusPlus17;
16884   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16885     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16886          diag::err_invalid_thread)
16887       << DeclSpec::getSpecifierName(TSCS);
16888 
16889   // Check to see if this name was declared as a member previously
16890   NamedDecl *PrevDecl = nullptr;
16891   LookupResult Previous(*this, II, Loc, LookupMemberName,
16892                         ForVisibleRedeclaration);
16893   LookupName(Previous, S);
16894   switch (Previous.getResultKind()) {
16895     case LookupResult::Found:
16896     case LookupResult::FoundUnresolvedValue:
16897       PrevDecl = Previous.getAsSingle<NamedDecl>();
16898       break;
16899 
16900     case LookupResult::FoundOverloaded:
16901       PrevDecl = Previous.getRepresentativeDecl();
16902       break;
16903 
16904     case LookupResult::NotFound:
16905     case LookupResult::NotFoundInCurrentInstantiation:
16906     case LookupResult::Ambiguous:
16907       break;
16908   }
16909   Previous.suppressDiagnostics();
16910 
16911   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16912     // Maybe we will complain about the shadowed template parameter.
16913     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16914     // Just pretend that we didn't see the previous declaration.
16915     PrevDecl = nullptr;
16916   }
16917 
16918   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16919     PrevDecl = nullptr;
16920 
16921   bool Mutable
16922     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16923   SourceLocation TSSL = D.getBeginLoc();
16924   FieldDecl *NewFD
16925     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16926                      TSSL, AS, PrevDecl, &D);
16927 
16928   if (NewFD->isInvalidDecl())
16929     Record->setInvalidDecl();
16930 
16931   if (D.getDeclSpec().isModulePrivateSpecified())
16932     NewFD->setModulePrivate();
16933 
16934   if (NewFD->isInvalidDecl() && PrevDecl) {
16935     // Don't introduce NewFD into scope; there's already something
16936     // with the same name in the same scope.
16937   } else if (II) {
16938     PushOnScopeChains(NewFD, S);
16939   } else
16940     Record->addDecl(NewFD);
16941 
16942   return NewFD;
16943 }
16944 
16945 /// Build a new FieldDecl and check its well-formedness.
16946 ///
16947 /// This routine builds a new FieldDecl given the fields name, type,
16948 /// record, etc. \p PrevDecl should refer to any previous declaration
16949 /// with the same name and in the same scope as the field to be
16950 /// created.
16951 ///
16952 /// \returns a new FieldDecl.
16953 ///
16954 /// \todo The Declarator argument is a hack. It will be removed once
16955 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16956                                 TypeSourceInfo *TInfo,
16957                                 RecordDecl *Record, SourceLocation Loc,
16958                                 bool Mutable, Expr *BitWidth,
16959                                 InClassInitStyle InitStyle,
16960                                 SourceLocation TSSL,
16961                                 AccessSpecifier AS, NamedDecl *PrevDecl,
16962                                 Declarator *D) {
16963   IdentifierInfo *II = Name.getAsIdentifierInfo();
16964   bool InvalidDecl = false;
16965   if (D) InvalidDecl = D->isInvalidType();
16966 
16967   // If we receive a broken type, recover by assuming 'int' and
16968   // marking this declaration as invalid.
16969   if (T.isNull() || T->containsErrors()) {
16970     InvalidDecl = true;
16971     T = Context.IntTy;
16972   }
16973 
16974   QualType EltTy = Context.getBaseElementType(T);
16975   if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16976     if (RequireCompleteSizedType(Loc, EltTy,
16977                                  diag::err_field_incomplete_or_sizeless)) {
16978       // Fields of incomplete type force their record to be invalid.
16979       Record->setInvalidDecl();
16980       InvalidDecl = true;
16981     } else {
16982       NamedDecl *Def;
16983       EltTy->isIncompleteType(&Def);
16984       if (Def && Def->isInvalidDecl()) {
16985         Record->setInvalidDecl();
16986         InvalidDecl = true;
16987       }
16988     }
16989   }
16990 
16991   // TR 18037 does not allow fields to be declared with address space
16992   if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16993       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16994     Diag(Loc, diag::err_field_with_address_space);
16995     Record->setInvalidDecl();
16996     InvalidDecl = true;
16997   }
16998 
16999   if (LangOpts.OpenCL) {
17000     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17001     // used as structure or union field: image, sampler, event or block types.
17002     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17003         T->isBlockPointerType()) {
17004       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17005       Record->setInvalidDecl();
17006       InvalidDecl = true;
17007     }
17008     // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17009     // is enabled.
17010     if (BitWidth && !getOpenCLOptions().isAvailableOption(
17011                         "__cl_clang_bitfields", LangOpts)) {
17012       Diag(Loc, diag::err_opencl_bitfields);
17013       InvalidDecl = true;
17014     }
17015   }
17016 
17017   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17018   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17019       T.hasQualifiers()) {
17020     InvalidDecl = true;
17021     Diag(Loc, diag::err_anon_bitfield_qualifiers);
17022   }
17023 
17024   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17025   // than a variably modified type.
17026   if (!InvalidDecl && T->isVariablyModifiedType()) {
17027     if (!tryToFixVariablyModifiedVarType(
17028             TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17029       InvalidDecl = true;
17030   }
17031 
17032   // Fields can not have abstract class types
17033   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17034                                              diag::err_abstract_type_in_decl,
17035                                              AbstractFieldType))
17036     InvalidDecl = true;
17037 
17038   bool ZeroWidth = false;
17039   if (InvalidDecl)
17040     BitWidth = nullptr;
17041   // If this is declared as a bit-field, check the bit-field.
17042   if (BitWidth) {
17043     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17044                               &ZeroWidth).get();
17045     if (!BitWidth) {
17046       InvalidDecl = true;
17047       BitWidth = nullptr;
17048       ZeroWidth = false;
17049     }
17050   }
17051 
17052   // Check that 'mutable' is consistent with the type of the declaration.
17053   if (!InvalidDecl && Mutable) {
17054     unsigned DiagID = 0;
17055     if (T->isReferenceType())
17056       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17057                                         : diag::err_mutable_reference;
17058     else if (T.isConstQualified())
17059       DiagID = diag::err_mutable_const;
17060 
17061     if (DiagID) {
17062       SourceLocation ErrLoc = Loc;
17063       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17064         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17065       Diag(ErrLoc, DiagID);
17066       if (DiagID != diag::ext_mutable_reference) {
17067         Mutable = false;
17068         InvalidDecl = true;
17069       }
17070     }
17071   }
17072 
17073   // C++11 [class.union]p8 (DR1460):
17074   //   At most one variant member of a union may have a
17075   //   brace-or-equal-initializer.
17076   if (InitStyle != ICIS_NoInit)
17077     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17078 
17079   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17080                                        BitWidth, Mutable, InitStyle);
17081   if (InvalidDecl)
17082     NewFD->setInvalidDecl();
17083 
17084   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17085     Diag(Loc, diag::err_duplicate_member) << II;
17086     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17087     NewFD->setInvalidDecl();
17088   }
17089 
17090   if (!InvalidDecl && getLangOpts().CPlusPlus) {
17091     if (Record->isUnion()) {
17092       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17093         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17094         if (RDecl->getDefinition()) {
17095           // C++ [class.union]p1: An object of a class with a non-trivial
17096           // constructor, a non-trivial copy constructor, a non-trivial
17097           // destructor, or a non-trivial copy assignment operator
17098           // cannot be a member of a union, nor can an array of such
17099           // objects.
17100           if (CheckNontrivialField(NewFD))
17101             NewFD->setInvalidDecl();
17102         }
17103       }
17104 
17105       // C++ [class.union]p1: If a union contains a member of reference type,
17106       // the program is ill-formed, except when compiling with MSVC extensions
17107       // enabled.
17108       if (EltTy->isReferenceType()) {
17109         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17110                                     diag::ext_union_member_of_reference_type :
17111                                     diag::err_union_member_of_reference_type)
17112           << NewFD->getDeclName() << EltTy;
17113         if (!getLangOpts().MicrosoftExt)
17114           NewFD->setInvalidDecl();
17115       }
17116     }
17117   }
17118 
17119   // FIXME: We need to pass in the attributes given an AST
17120   // representation, not a parser representation.
17121   if (D) {
17122     // FIXME: The current scope is almost... but not entirely... correct here.
17123     ProcessDeclAttributes(getCurScope(), NewFD, *D);
17124 
17125     if (NewFD->hasAttrs())
17126       CheckAlignasUnderalignment(NewFD);
17127   }
17128 
17129   // In auto-retain/release, infer strong retension for fields of
17130   // retainable type.
17131   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17132     NewFD->setInvalidDecl();
17133 
17134   if (T.isObjCGCWeak())
17135     Diag(Loc, diag::warn_attribute_weak_on_field);
17136 
17137   // PPC MMA non-pointer types are not allowed as field types.
17138   if (Context.getTargetInfo().getTriple().isPPC64() &&
17139       CheckPPCMMAType(T, NewFD->getLocation()))
17140     NewFD->setInvalidDecl();
17141 
17142   NewFD->setAccess(AS);
17143   return NewFD;
17144 }
17145 
17146 bool Sema::CheckNontrivialField(FieldDecl *FD) {
17147   assert(FD);
17148   assert(getLangOpts().CPlusPlus && "valid check only for C++");
17149 
17150   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17151     return false;
17152 
17153   QualType EltTy = Context.getBaseElementType(FD->getType());
17154   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17155     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17156     if (RDecl->getDefinition()) {
17157       // We check for copy constructors before constructors
17158       // because otherwise we'll never get complaints about
17159       // copy constructors.
17160 
17161       CXXSpecialMember member = CXXInvalid;
17162       // We're required to check for any non-trivial constructors. Since the
17163       // implicit default constructor is suppressed if there are any
17164       // user-declared constructors, we just need to check that there is a
17165       // trivial default constructor and a trivial copy constructor. (We don't
17166       // worry about move constructors here, since this is a C++98 check.)
17167       if (RDecl->hasNonTrivialCopyConstructor())
17168         member = CXXCopyConstructor;
17169       else if (!RDecl->hasTrivialDefaultConstructor())
17170         member = CXXDefaultConstructor;
17171       else if (RDecl->hasNonTrivialCopyAssignment())
17172         member = CXXCopyAssignment;
17173       else if (RDecl->hasNonTrivialDestructor())
17174         member = CXXDestructor;
17175 
17176       if (member != CXXInvalid) {
17177         if (!getLangOpts().CPlusPlus11 &&
17178             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17179           // Objective-C++ ARC: it is an error to have a non-trivial field of
17180           // a union. However, system headers in Objective-C programs
17181           // occasionally have Objective-C lifetime objects within unions,
17182           // and rather than cause the program to fail, we make those
17183           // members unavailable.
17184           SourceLocation Loc = FD->getLocation();
17185           if (getSourceManager().isInSystemHeader(Loc)) {
17186             if (!FD->hasAttr<UnavailableAttr>())
17187               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17188                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17189             return false;
17190           }
17191         }
17192 
17193         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17194                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17195                diag::err_illegal_union_or_anon_struct_member)
17196           << FD->getParent()->isUnion() << FD->getDeclName() << member;
17197         DiagnoseNontrivial(RDecl, member);
17198         return !getLangOpts().CPlusPlus11;
17199       }
17200     }
17201   }
17202 
17203   return false;
17204 }
17205 
17206 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17207 ///  AST enum value.
17208 static ObjCIvarDecl::AccessControl
17209 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17210   switch (ivarVisibility) {
17211   default: llvm_unreachable("Unknown visitibility kind");
17212   case tok::objc_private: return ObjCIvarDecl::Private;
17213   case tok::objc_public: return ObjCIvarDecl::Public;
17214   case tok::objc_protected: return ObjCIvarDecl::Protected;
17215   case tok::objc_package: return ObjCIvarDecl::Package;
17216   }
17217 }
17218 
17219 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17220 /// in order to create an IvarDecl object for it.
17221 Decl *Sema::ActOnIvar(Scope *S,
17222                                 SourceLocation DeclStart,
17223                                 Declarator &D, Expr *BitfieldWidth,
17224                                 tok::ObjCKeywordKind Visibility) {
17225 
17226   IdentifierInfo *II = D.getIdentifier();
17227   Expr *BitWidth = (Expr*)BitfieldWidth;
17228   SourceLocation Loc = DeclStart;
17229   if (II) Loc = D.getIdentifierLoc();
17230 
17231   // FIXME: Unnamed fields can be handled in various different ways, for
17232   // example, unnamed unions inject all members into the struct namespace!
17233 
17234   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17235   QualType T = TInfo->getType();
17236 
17237   if (BitWidth) {
17238     // 6.7.2.1p3, 6.7.2.1p4
17239     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17240     if (!BitWidth)
17241       D.setInvalidType();
17242   } else {
17243     // Not a bitfield.
17244 
17245     // validate II.
17246 
17247   }
17248   if (T->isReferenceType()) {
17249     Diag(Loc, diag::err_ivar_reference_type);
17250     D.setInvalidType();
17251   }
17252   // C99 6.7.2.1p8: A member of a structure or union may have any type other
17253   // than a variably modified type.
17254   else if (T->isVariablyModifiedType()) {
17255     if (!tryToFixVariablyModifiedVarType(
17256             TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17257       D.setInvalidType();
17258   }
17259 
17260   // Get the visibility (access control) for this ivar.
17261   ObjCIvarDecl::AccessControl ac =
17262     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17263                                         : ObjCIvarDecl::None;
17264   // Must set ivar's DeclContext to its enclosing interface.
17265   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17266   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17267     return nullptr;
17268   ObjCContainerDecl *EnclosingContext;
17269   if (ObjCImplementationDecl *IMPDecl =
17270       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17271     if (LangOpts.ObjCRuntime.isFragile()) {
17272     // Case of ivar declared in an implementation. Context is that of its class.
17273       EnclosingContext = IMPDecl->getClassInterface();
17274       assert(EnclosingContext && "Implementation has no class interface!");
17275     }
17276     else
17277       EnclosingContext = EnclosingDecl;
17278   } else {
17279     if (ObjCCategoryDecl *CDecl =
17280         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17281       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17282         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17283         return nullptr;
17284       }
17285     }
17286     EnclosingContext = EnclosingDecl;
17287   }
17288 
17289   // Construct the decl.
17290   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17291                                              DeclStart, Loc, II, T,
17292                                              TInfo, ac, (Expr *)BitfieldWidth);
17293 
17294   if (II) {
17295     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17296                                            ForVisibleRedeclaration);
17297     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17298         && !isa<TagDecl>(PrevDecl)) {
17299       Diag(Loc, diag::err_duplicate_member) << II;
17300       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17301       NewID->setInvalidDecl();
17302     }
17303   }
17304 
17305   // Process attributes attached to the ivar.
17306   ProcessDeclAttributes(S, NewID, D);
17307 
17308   if (D.isInvalidType())
17309     NewID->setInvalidDecl();
17310 
17311   // In ARC, infer 'retaining' for ivars of retainable type.
17312   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17313     NewID->setInvalidDecl();
17314 
17315   if (D.getDeclSpec().isModulePrivateSpecified())
17316     NewID->setModulePrivate();
17317 
17318   if (II) {
17319     // FIXME: When interfaces are DeclContexts, we'll need to add
17320     // these to the interface.
17321     S->AddDecl(NewID);
17322     IdResolver.AddDecl(NewID);
17323   }
17324 
17325   if (LangOpts.ObjCRuntime.isNonFragile() &&
17326       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17327     Diag(Loc, diag::warn_ivars_in_interface);
17328 
17329   return NewID;
17330 }
17331 
17332 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17333 /// class and class extensions. For every class \@interface and class
17334 /// extension \@interface, if the last ivar is a bitfield of any type,
17335 /// then add an implicit `char :0` ivar to the end of that interface.
17336 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17337                              SmallVectorImpl<Decl *> &AllIvarDecls) {
17338   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17339     return;
17340 
17341   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17342   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17343 
17344   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17345     return;
17346   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17347   if (!ID) {
17348     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17349       if (!CD->IsClassExtension())
17350         return;
17351     }
17352     // No need to add this to end of @implementation.
17353     else
17354       return;
17355   }
17356   // All conditions are met. Add a new bitfield to the tail end of ivars.
17357   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17358   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17359 
17360   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17361                               DeclLoc, DeclLoc, nullptr,
17362                               Context.CharTy,
17363                               Context.getTrivialTypeSourceInfo(Context.CharTy,
17364                                                                DeclLoc),
17365                               ObjCIvarDecl::Private, BW,
17366                               true);
17367   AllIvarDecls.push_back(Ivar);
17368 }
17369 
17370 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17371                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
17372                        SourceLocation RBrac,
17373                        const ParsedAttributesView &Attrs) {
17374   assert(EnclosingDecl && "missing record or interface decl");
17375 
17376   // If this is an Objective-C @implementation or category and we have
17377   // new fields here we should reset the layout of the interface since
17378   // it will now change.
17379   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17380     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17381     switch (DC->getKind()) {
17382     default: break;
17383     case Decl::ObjCCategory:
17384       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17385       break;
17386     case Decl::ObjCImplementation:
17387       Context.
17388         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17389       break;
17390     }
17391   }
17392 
17393   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17394   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17395 
17396   // Start counting up the number of named members; make sure to include
17397   // members of anonymous structs and unions in the total.
17398   unsigned NumNamedMembers = 0;
17399   if (Record) {
17400     for (const auto *I : Record->decls()) {
17401       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17402         if (IFD->getDeclName())
17403           ++NumNamedMembers;
17404     }
17405   }
17406 
17407   // Verify that all the fields are okay.
17408   SmallVector<FieldDecl*, 32> RecFields;
17409 
17410   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17411        i != end; ++i) {
17412     FieldDecl *FD = cast<FieldDecl>(*i);
17413 
17414     // Get the type for the field.
17415     const Type *FDTy = FD->getType().getTypePtr();
17416 
17417     if (!FD->isAnonymousStructOrUnion()) {
17418       // Remember all fields written by the user.
17419       RecFields.push_back(FD);
17420     }
17421 
17422     // If the field is already invalid for some reason, don't emit more
17423     // diagnostics about it.
17424     if (FD->isInvalidDecl()) {
17425       EnclosingDecl->setInvalidDecl();
17426       continue;
17427     }
17428 
17429     // C99 6.7.2.1p2:
17430     //   A structure or union shall not contain a member with
17431     //   incomplete or function type (hence, a structure shall not
17432     //   contain an instance of itself, but may contain a pointer to
17433     //   an instance of itself), except that the last member of a
17434     //   structure with more than one named member may have incomplete
17435     //   array type; such a structure (and any union containing,
17436     //   possibly recursively, a member that is such a structure)
17437     //   shall not be a member of a structure or an element of an
17438     //   array.
17439     bool IsLastField = (i + 1 == Fields.end());
17440     if (FDTy->isFunctionType()) {
17441       // Field declared as a function.
17442       Diag(FD->getLocation(), diag::err_field_declared_as_function)
17443         << FD->getDeclName();
17444       FD->setInvalidDecl();
17445       EnclosingDecl->setInvalidDecl();
17446       continue;
17447     } else if (FDTy->isIncompleteArrayType() &&
17448                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17449       if (Record) {
17450         // Flexible array member.
17451         // Microsoft and g++ is more permissive regarding flexible array.
17452         // It will accept flexible array in union and also
17453         // as the sole element of a struct/class.
17454         unsigned DiagID = 0;
17455         if (!Record->isUnion() && !IsLastField) {
17456           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17457             << FD->getDeclName() << FD->getType() << Record->getTagKind();
17458           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17459           FD->setInvalidDecl();
17460           EnclosingDecl->setInvalidDecl();
17461           continue;
17462         } else if (Record->isUnion())
17463           DiagID = getLangOpts().MicrosoftExt
17464                        ? diag::ext_flexible_array_union_ms
17465                        : getLangOpts().CPlusPlus
17466                              ? diag::ext_flexible_array_union_gnu
17467                              : diag::err_flexible_array_union;
17468         else if (NumNamedMembers < 1)
17469           DiagID = getLangOpts().MicrosoftExt
17470                        ? diag::ext_flexible_array_empty_aggregate_ms
17471                        : getLangOpts().CPlusPlus
17472                              ? diag::ext_flexible_array_empty_aggregate_gnu
17473                              : diag::err_flexible_array_empty_aggregate;
17474 
17475         if (DiagID)
17476           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17477                                           << Record->getTagKind();
17478         // While the layout of types that contain virtual bases is not specified
17479         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17480         // virtual bases after the derived members.  This would make a flexible
17481         // array member declared at the end of an object not adjacent to the end
17482         // of the type.
17483         if (CXXRecord && CXXRecord->getNumVBases() != 0)
17484           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17485               << FD->getDeclName() << Record->getTagKind();
17486         if (!getLangOpts().C99)
17487           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17488             << FD->getDeclName() << Record->getTagKind();
17489 
17490         // If the element type has a non-trivial destructor, we would not
17491         // implicitly destroy the elements, so disallow it for now.
17492         //
17493         // FIXME: GCC allows this. We should probably either implicitly delete
17494         // the destructor of the containing class, or just allow this.
17495         QualType BaseElem = Context.getBaseElementType(FD->getType());
17496         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17497           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17498             << FD->getDeclName() << FD->getType();
17499           FD->setInvalidDecl();
17500           EnclosingDecl->setInvalidDecl();
17501           continue;
17502         }
17503         // Okay, we have a legal flexible array member at the end of the struct.
17504         Record->setHasFlexibleArrayMember(true);
17505       } else {
17506         // In ObjCContainerDecl ivars with incomplete array type are accepted,
17507         // unless they are followed by another ivar. That check is done
17508         // elsewhere, after synthesized ivars are known.
17509       }
17510     } else if (!FDTy->isDependentType() &&
17511                RequireCompleteSizedType(
17512                    FD->getLocation(), FD->getType(),
17513                    diag::err_field_incomplete_or_sizeless)) {
17514       // Incomplete type
17515       FD->setInvalidDecl();
17516       EnclosingDecl->setInvalidDecl();
17517       continue;
17518     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17519       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17520         // A type which contains a flexible array member is considered to be a
17521         // flexible array member.
17522         Record->setHasFlexibleArrayMember(true);
17523         if (!Record->isUnion()) {
17524           // If this is a struct/class and this is not the last element, reject
17525           // it.  Note that GCC supports variable sized arrays in the middle of
17526           // structures.
17527           if (!IsLastField)
17528             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17529               << FD->getDeclName() << FD->getType();
17530           else {
17531             // We support flexible arrays at the end of structs in
17532             // other structs as an extension.
17533             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17534               << FD->getDeclName();
17535           }
17536         }
17537       }
17538       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17539           RequireNonAbstractType(FD->getLocation(), FD->getType(),
17540                                  diag::err_abstract_type_in_decl,
17541                                  AbstractIvarType)) {
17542         // Ivars can not have abstract class types
17543         FD->setInvalidDecl();
17544       }
17545       if (Record && FDTTy->getDecl()->hasObjectMember())
17546         Record->setHasObjectMember(true);
17547       if (Record && FDTTy->getDecl()->hasVolatileMember())
17548         Record->setHasVolatileMember(true);
17549     } else if (FDTy->isObjCObjectType()) {
17550       /// A field cannot be an Objective-c object
17551       Diag(FD->getLocation(), diag::err_statically_allocated_object)
17552         << FixItHint::CreateInsertion(FD->getLocation(), "*");
17553       QualType T = Context.getObjCObjectPointerType(FD->getType());
17554       FD->setType(T);
17555     } else if (Record && Record->isUnion() &&
17556                FD->getType().hasNonTrivialObjCLifetime() &&
17557                getSourceManager().isInSystemHeader(FD->getLocation()) &&
17558                !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17559                (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17560                 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17561       // For backward compatibility, fields of C unions declared in system
17562       // headers that have non-trivial ObjC ownership qualifications are marked
17563       // as unavailable unless the qualifier is explicit and __strong. This can
17564       // break ABI compatibility between programs compiled with ARC and MRR, but
17565       // is a better option than rejecting programs using those unions under
17566       // ARC.
17567       FD->addAttr(UnavailableAttr::CreateImplicit(
17568           Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17569           FD->getLocation()));
17570     } else if (getLangOpts().ObjC &&
17571                getLangOpts().getGC() != LangOptions::NonGC && Record &&
17572                !Record->hasObjectMember()) {
17573       if (FD->getType()->isObjCObjectPointerType() ||
17574           FD->getType().isObjCGCStrong())
17575         Record->setHasObjectMember(true);
17576       else if (Context.getAsArrayType(FD->getType())) {
17577         QualType BaseType = Context.getBaseElementType(FD->getType());
17578         if (BaseType->isRecordType() &&
17579             BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17580           Record->setHasObjectMember(true);
17581         else if (BaseType->isObjCObjectPointerType() ||
17582                  BaseType.isObjCGCStrong())
17583                Record->setHasObjectMember(true);
17584       }
17585     }
17586 
17587     if (Record && !getLangOpts().CPlusPlus &&
17588         !shouldIgnoreForRecordTriviality(FD)) {
17589       QualType FT = FD->getType();
17590       if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17591         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17592         if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17593             Record->isUnion())
17594           Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17595       }
17596       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17597       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17598         Record->setNonTrivialToPrimitiveCopy(true);
17599         if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17600           Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17601       }
17602       if (FT.isDestructedType()) {
17603         Record->setNonTrivialToPrimitiveDestroy(true);
17604         Record->setParamDestroyedInCallee(true);
17605         if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17606           Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17607       }
17608 
17609       if (const auto *RT = FT->getAs<RecordType>()) {
17610         if (RT->getDecl()->getArgPassingRestrictions() ==
17611             RecordDecl::APK_CanNeverPassInRegs)
17612           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17613       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17614         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17615     }
17616 
17617     if (Record && FD->getType().isVolatileQualified())
17618       Record->setHasVolatileMember(true);
17619     // Keep track of the number of named members.
17620     if (FD->getIdentifier())
17621       ++NumNamedMembers;
17622   }
17623 
17624   // Okay, we successfully defined 'Record'.
17625   if (Record) {
17626     bool Completed = false;
17627     if (CXXRecord) {
17628       if (!CXXRecord->isInvalidDecl()) {
17629         // Set access bits correctly on the directly-declared conversions.
17630         for (CXXRecordDecl::conversion_iterator
17631                I = CXXRecord->conversion_begin(),
17632                E = CXXRecord->conversion_end(); I != E; ++I)
17633           I.setAccess((*I)->getAccess());
17634       }
17635 
17636       // Add any implicitly-declared members to this class.
17637       AddImplicitlyDeclaredMembersToClass(CXXRecord);
17638 
17639       if (!CXXRecord->isDependentType()) {
17640         if (!CXXRecord->isInvalidDecl()) {
17641           // If we have virtual base classes, we may end up finding multiple
17642           // final overriders for a given virtual function. Check for this
17643           // problem now.
17644           if (CXXRecord->getNumVBases()) {
17645             CXXFinalOverriderMap FinalOverriders;
17646             CXXRecord->getFinalOverriders(FinalOverriders);
17647 
17648             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17649                                              MEnd = FinalOverriders.end();
17650                  M != MEnd; ++M) {
17651               for (OverridingMethods::iterator SO = M->second.begin(),
17652                                             SOEnd = M->second.end();
17653                    SO != SOEnd; ++SO) {
17654                 assert(SO->second.size() > 0 &&
17655                        "Virtual function without overriding functions?");
17656                 if (SO->second.size() == 1)
17657                   continue;
17658 
17659                 // C++ [class.virtual]p2:
17660                 //   In a derived class, if a virtual member function of a base
17661                 //   class subobject has more than one final overrider the
17662                 //   program is ill-formed.
17663                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17664                   << (const NamedDecl *)M->first << Record;
17665                 Diag(M->first->getLocation(),
17666                      diag::note_overridden_virtual_function);
17667                 for (OverridingMethods::overriding_iterator
17668                           OM = SO->second.begin(),
17669                        OMEnd = SO->second.end();
17670                      OM != OMEnd; ++OM)
17671                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
17672                     << (const NamedDecl *)M->first << OM->Method->getParent();
17673 
17674                 Record->setInvalidDecl();
17675               }
17676             }
17677             CXXRecord->completeDefinition(&FinalOverriders);
17678             Completed = true;
17679           }
17680         }
17681       }
17682     }
17683 
17684     if (!Completed)
17685       Record->completeDefinition();
17686 
17687     // Handle attributes before checking the layout.
17688     ProcessDeclAttributeList(S, Record, Attrs);
17689 
17690     // We may have deferred checking for a deleted destructor. Check now.
17691     if (CXXRecord) {
17692       auto *Dtor = CXXRecord->getDestructor();
17693       if (Dtor && Dtor->isImplicit() &&
17694           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17695         CXXRecord->setImplicitDestructorIsDeleted();
17696         SetDeclDeleted(Dtor, CXXRecord->getLocation());
17697       }
17698     }
17699 
17700     if (Record->hasAttrs()) {
17701       CheckAlignasUnderalignment(Record);
17702 
17703       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17704         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17705                                            IA->getRange(), IA->getBestCase(),
17706                                            IA->getInheritanceModel());
17707     }
17708 
17709     // Check if the structure/union declaration is a type that can have zero
17710     // size in C. For C this is a language extension, for C++ it may cause
17711     // compatibility problems.
17712     bool CheckForZeroSize;
17713     if (!getLangOpts().CPlusPlus) {
17714       CheckForZeroSize = true;
17715     } else {
17716       // For C++ filter out types that cannot be referenced in C code.
17717       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17718       CheckForZeroSize =
17719           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17720           !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17721           CXXRecord->isCLike();
17722     }
17723     if (CheckForZeroSize) {
17724       bool ZeroSize = true;
17725       bool IsEmpty = true;
17726       unsigned NonBitFields = 0;
17727       for (RecordDecl::field_iterator I = Record->field_begin(),
17728                                       E = Record->field_end();
17729            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17730         IsEmpty = false;
17731         if (I->isUnnamedBitfield()) {
17732           if (!I->isZeroLengthBitField(Context))
17733             ZeroSize = false;
17734         } else {
17735           ++NonBitFields;
17736           QualType FieldType = I->getType();
17737           if (FieldType->isIncompleteType() ||
17738               !Context.getTypeSizeInChars(FieldType).isZero())
17739             ZeroSize = false;
17740         }
17741       }
17742 
17743       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17744       // allowed in C++, but warn if its declaration is inside
17745       // extern "C" block.
17746       if (ZeroSize) {
17747         Diag(RecLoc, getLangOpts().CPlusPlus ?
17748                          diag::warn_zero_size_struct_union_in_extern_c :
17749                          diag::warn_zero_size_struct_union_compat)
17750           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17751       }
17752 
17753       // Structs without named members are extension in C (C99 6.7.2.1p7),
17754       // but are accepted by GCC.
17755       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17756         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17757                                diag::ext_no_named_members_in_struct_union)
17758           << Record->isUnion();
17759       }
17760     }
17761   } else {
17762     ObjCIvarDecl **ClsFields =
17763       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17764     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17765       ID->setEndOfDefinitionLoc(RBrac);
17766       // Add ivar's to class's DeclContext.
17767       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17768         ClsFields[i]->setLexicalDeclContext(ID);
17769         ID->addDecl(ClsFields[i]);
17770       }
17771       // Must enforce the rule that ivars in the base classes may not be
17772       // duplicates.
17773       if (ID->getSuperClass())
17774         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17775     } else if (ObjCImplementationDecl *IMPDecl =
17776                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17777       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17778       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17779         // Ivar declared in @implementation never belongs to the implementation.
17780         // Only it is in implementation's lexical context.
17781         ClsFields[I]->setLexicalDeclContext(IMPDecl);
17782       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17783       IMPDecl->setIvarLBraceLoc(LBrac);
17784       IMPDecl->setIvarRBraceLoc(RBrac);
17785     } else if (ObjCCategoryDecl *CDecl =
17786                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17787       // case of ivars in class extension; all other cases have been
17788       // reported as errors elsewhere.
17789       // FIXME. Class extension does not have a LocEnd field.
17790       // CDecl->setLocEnd(RBrac);
17791       // Add ivar's to class extension's DeclContext.
17792       // Diagnose redeclaration of private ivars.
17793       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17794       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17795         if (IDecl) {
17796           if (const ObjCIvarDecl *ClsIvar =
17797               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17798             Diag(ClsFields[i]->getLocation(),
17799                  diag::err_duplicate_ivar_declaration);
17800             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17801             continue;
17802           }
17803           for (const auto *Ext : IDecl->known_extensions()) {
17804             if (const ObjCIvarDecl *ClsExtIvar
17805                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17806               Diag(ClsFields[i]->getLocation(),
17807                    diag::err_duplicate_ivar_declaration);
17808               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17809               continue;
17810             }
17811           }
17812         }
17813         ClsFields[i]->setLexicalDeclContext(CDecl);
17814         CDecl->addDecl(ClsFields[i]);
17815       }
17816       CDecl->setIvarLBraceLoc(LBrac);
17817       CDecl->setIvarRBraceLoc(RBrac);
17818     }
17819   }
17820 }
17821 
17822 /// Determine whether the given integral value is representable within
17823 /// the given type T.
17824 static bool isRepresentableIntegerValue(ASTContext &Context,
17825                                         llvm::APSInt &Value,
17826                                         QualType T) {
17827   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
17828          "Integral type required!");
17829   unsigned BitWidth = Context.getIntWidth(T);
17830 
17831   if (Value.isUnsigned() || Value.isNonNegative()) {
17832     if (T->isSignedIntegerOrEnumerationType())
17833       --BitWidth;
17834     return Value.getActiveBits() <= BitWidth;
17835   }
17836   return Value.getMinSignedBits() <= BitWidth;
17837 }
17838 
17839 // Given an integral type, return the next larger integral type
17840 // (or a NULL type of no such type exists).
17841 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17842   // FIXME: Int128/UInt128 support, which also needs to be introduced into
17843   // enum checking below.
17844   assert((T->isIntegralType(Context) ||
17845          T->isEnumeralType()) && "Integral type required!");
17846   const unsigned NumTypes = 4;
17847   QualType SignedIntegralTypes[NumTypes] = {
17848     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17849   };
17850   QualType UnsignedIntegralTypes[NumTypes] = {
17851     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17852     Context.UnsignedLongLongTy
17853   };
17854 
17855   unsigned BitWidth = Context.getTypeSize(T);
17856   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17857                                                         : UnsignedIntegralTypes;
17858   for (unsigned I = 0; I != NumTypes; ++I)
17859     if (Context.getTypeSize(Types[I]) > BitWidth)
17860       return Types[I];
17861 
17862   return QualType();
17863 }
17864 
17865 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17866                                           EnumConstantDecl *LastEnumConst,
17867                                           SourceLocation IdLoc,
17868                                           IdentifierInfo *Id,
17869                                           Expr *Val) {
17870   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17871   llvm::APSInt EnumVal(IntWidth);
17872   QualType EltTy;
17873 
17874   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17875     Val = nullptr;
17876 
17877   if (Val)
17878     Val = DefaultLvalueConversion(Val).get();
17879 
17880   if (Val) {
17881     if (Enum->isDependentType() || Val->isTypeDependent() ||
17882         Val->containsErrors())
17883       EltTy = Context.DependentTy;
17884     else {
17885       // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17886       // underlying type, but do allow it in all other contexts.
17887       if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17888         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17889         // constant-expression in the enumerator-definition shall be a converted
17890         // constant expression of the underlying type.
17891         EltTy = Enum->getIntegerType();
17892         ExprResult Converted =
17893           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17894                                            CCEK_Enumerator);
17895         if (Converted.isInvalid())
17896           Val = nullptr;
17897         else
17898           Val = Converted.get();
17899       } else if (!Val->isValueDependent() &&
17900                  !(Val =
17901                        VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17902                            .get())) {
17903         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17904       } else {
17905         if (Enum->isComplete()) {
17906           EltTy = Enum->getIntegerType();
17907 
17908           // In Obj-C and Microsoft mode, require the enumeration value to be
17909           // representable in the underlying type of the enumeration. In C++11,
17910           // we perform a non-narrowing conversion as part of converted constant
17911           // expression checking.
17912           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17913             if (Context.getTargetInfo()
17914                     .getTriple()
17915                     .isWindowsMSVCEnvironment()) {
17916               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17917             } else {
17918               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17919             }
17920           }
17921 
17922           // Cast to the underlying type.
17923           Val = ImpCastExprToType(Val, EltTy,
17924                                   EltTy->isBooleanType() ? CK_IntegralToBoolean
17925                                                          : CK_IntegralCast)
17926                     .get();
17927         } else if (getLangOpts().CPlusPlus) {
17928           // C++11 [dcl.enum]p5:
17929           //   If the underlying type is not fixed, the type of each enumerator
17930           //   is the type of its initializing value:
17931           //     - If an initializer is specified for an enumerator, the
17932           //       initializing value has the same type as the expression.
17933           EltTy = Val->getType();
17934         } else {
17935           // C99 6.7.2.2p2:
17936           //   The expression that defines the value of an enumeration constant
17937           //   shall be an integer constant expression that has a value
17938           //   representable as an int.
17939 
17940           // Complain if the value is not representable in an int.
17941           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17942             Diag(IdLoc, diag::ext_enum_value_not_int)
17943               << toString(EnumVal, 10) << Val->getSourceRange()
17944               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17945           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17946             // Force the type of the expression to 'int'.
17947             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17948           }
17949           EltTy = Val->getType();
17950         }
17951       }
17952     }
17953   }
17954 
17955   if (!Val) {
17956     if (Enum->isDependentType())
17957       EltTy = Context.DependentTy;
17958     else if (!LastEnumConst) {
17959       // C++0x [dcl.enum]p5:
17960       //   If the underlying type is not fixed, the type of each enumerator
17961       //   is the type of its initializing value:
17962       //     - If no initializer is specified for the first enumerator, the
17963       //       initializing value has an unspecified integral type.
17964       //
17965       // GCC uses 'int' for its unspecified integral type, as does
17966       // C99 6.7.2.2p3.
17967       if (Enum->isFixed()) {
17968         EltTy = Enum->getIntegerType();
17969       }
17970       else {
17971         EltTy = Context.IntTy;
17972       }
17973     } else {
17974       // Assign the last value + 1.
17975       EnumVal = LastEnumConst->getInitVal();
17976       ++EnumVal;
17977       EltTy = LastEnumConst->getType();
17978 
17979       // Check for overflow on increment.
17980       if (EnumVal < LastEnumConst->getInitVal()) {
17981         // C++0x [dcl.enum]p5:
17982         //   If the underlying type is not fixed, the type of each enumerator
17983         //   is the type of its initializing value:
17984         //
17985         //     - Otherwise the type of the initializing value is the same as
17986         //       the type of the initializing value of the preceding enumerator
17987         //       unless the incremented value is not representable in that type,
17988         //       in which case the type is an unspecified integral type
17989         //       sufficient to contain the incremented value. If no such type
17990         //       exists, the program is ill-formed.
17991         QualType T = getNextLargerIntegralType(Context, EltTy);
17992         if (T.isNull() || Enum->isFixed()) {
17993           // There is no integral type larger enough to represent this
17994           // value. Complain, then allow the value to wrap around.
17995           EnumVal = LastEnumConst->getInitVal();
17996           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17997           ++EnumVal;
17998           if (Enum->isFixed())
17999             // When the underlying type is fixed, this is ill-formed.
18000             Diag(IdLoc, diag::err_enumerator_wrapped)
18001               << toString(EnumVal, 10)
18002               << EltTy;
18003           else
18004             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18005               << toString(EnumVal, 10);
18006         } else {
18007           EltTy = T;
18008         }
18009 
18010         // Retrieve the last enumerator's value, extent that type to the
18011         // type that is supposed to be large enough to represent the incremented
18012         // value, then increment.
18013         EnumVal = LastEnumConst->getInitVal();
18014         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18015         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18016         ++EnumVal;
18017 
18018         // If we're not in C++, diagnose the overflow of enumerator values,
18019         // which in C99 means that the enumerator value is not representable in
18020         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18021         // permits enumerator values that are representable in some larger
18022         // integral type.
18023         if (!getLangOpts().CPlusPlus && !T.isNull())
18024           Diag(IdLoc, diag::warn_enum_value_overflow);
18025       } else if (!getLangOpts().CPlusPlus &&
18026                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18027         // Enforce C99 6.7.2.2p2 even when we compute the next value.
18028         Diag(IdLoc, diag::ext_enum_value_not_int)
18029           << toString(EnumVal, 10) << 1;
18030       }
18031     }
18032   }
18033 
18034   if (!EltTy->isDependentType()) {
18035     // Make the enumerator value match the signedness and size of the
18036     // enumerator's type.
18037     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18038     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18039   }
18040 
18041   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18042                                   Val, EnumVal);
18043 }
18044 
18045 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
18046                                                 SourceLocation IILoc) {
18047   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18048       !getLangOpts().CPlusPlus)
18049     return SkipBodyInfo();
18050 
18051   // We have an anonymous enum definition. Look up the first enumerator to
18052   // determine if we should merge the definition with an existing one and
18053   // skip the body.
18054   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18055                                          forRedeclarationInCurContext());
18056   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18057   if (!PrevECD)
18058     return SkipBodyInfo();
18059 
18060   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18061   NamedDecl *Hidden;
18062   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18063     SkipBodyInfo Skip;
18064     Skip.Previous = Hidden;
18065     return Skip;
18066   }
18067 
18068   return SkipBodyInfo();
18069 }
18070 
18071 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18072                               SourceLocation IdLoc, IdentifierInfo *Id,
18073                               const ParsedAttributesView &Attrs,
18074                               SourceLocation EqualLoc, Expr *Val) {
18075   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18076   EnumConstantDecl *LastEnumConst =
18077     cast_or_null<EnumConstantDecl>(lastEnumConst);
18078 
18079   // The scope passed in may not be a decl scope.  Zip up the scope tree until
18080   // we find one that is.
18081   S = getNonFieldDeclScope(S);
18082 
18083   // Verify that there isn't already something declared with this name in this
18084   // scope.
18085   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18086   LookupName(R, S);
18087   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18088 
18089   if (PrevDecl && PrevDecl->isTemplateParameter()) {
18090     // Maybe we will complain about the shadowed template parameter.
18091     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18092     // Just pretend that we didn't see the previous declaration.
18093     PrevDecl = nullptr;
18094   }
18095 
18096   // C++ [class.mem]p15:
18097   // If T is the name of a class, then each of the following shall have a name
18098   // different from T:
18099   // - every enumerator of every member of class T that is an unscoped
18100   // enumerated type
18101   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18102     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18103                             DeclarationNameInfo(Id, IdLoc));
18104 
18105   EnumConstantDecl *New =
18106     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18107   if (!New)
18108     return nullptr;
18109 
18110   if (PrevDecl) {
18111     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18112       // Check for other kinds of shadowing not already handled.
18113       CheckShadow(New, PrevDecl, R);
18114     }
18115 
18116     // When in C++, we may get a TagDecl with the same name; in this case the
18117     // enum constant will 'hide' the tag.
18118     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18119            "Received TagDecl when not in C++!");
18120     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18121       if (isa<EnumConstantDecl>(PrevDecl))
18122         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18123       else
18124         Diag(IdLoc, diag::err_redefinition) << Id;
18125       notePreviousDefinition(PrevDecl, IdLoc);
18126       return nullptr;
18127     }
18128   }
18129 
18130   // Process attributes.
18131   ProcessDeclAttributeList(S, New, Attrs);
18132   AddPragmaAttributes(S, New);
18133 
18134   // Register this decl in the current scope stack.
18135   New->setAccess(TheEnumDecl->getAccess());
18136   PushOnScopeChains(New, S);
18137 
18138   ActOnDocumentableDecl(New);
18139 
18140   return New;
18141 }
18142 
18143 // Returns true when the enum initial expression does not trigger the
18144 // duplicate enum warning.  A few common cases are exempted as follows:
18145 // Element2 = Element1
18146 // Element2 = Element1 + 1
18147 // Element2 = Element1 - 1
18148 // Where Element2 and Element1 are from the same enum.
18149 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18150   Expr *InitExpr = ECD->getInitExpr();
18151   if (!InitExpr)
18152     return true;
18153   InitExpr = InitExpr->IgnoreImpCasts();
18154 
18155   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18156     if (!BO->isAdditiveOp())
18157       return true;
18158     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18159     if (!IL)
18160       return true;
18161     if (IL->getValue() != 1)
18162       return true;
18163 
18164     InitExpr = BO->getLHS();
18165   }
18166 
18167   // This checks if the elements are from the same enum.
18168   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18169   if (!DRE)
18170     return true;
18171 
18172   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18173   if (!EnumConstant)
18174     return true;
18175 
18176   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18177       Enum)
18178     return true;
18179 
18180   return false;
18181 }
18182 
18183 // Emits a warning when an element is implicitly set a value that
18184 // a previous element has already been set to.
18185 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18186                                         EnumDecl *Enum, QualType EnumType) {
18187   // Avoid anonymous enums
18188   if (!Enum->getIdentifier())
18189     return;
18190 
18191   // Only check for small enums.
18192   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18193     return;
18194 
18195   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18196     return;
18197 
18198   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18199   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18200 
18201   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18202 
18203   // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18204   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18205 
18206   // Use int64_t as a key to avoid needing special handling for map keys.
18207   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18208     llvm::APSInt Val = D->getInitVal();
18209     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18210   };
18211 
18212   DuplicatesVector DupVector;
18213   ValueToVectorMap EnumMap;
18214 
18215   // Populate the EnumMap with all values represented by enum constants without
18216   // an initializer.
18217   for (auto *Element : Elements) {
18218     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18219 
18220     // Null EnumConstantDecl means a previous diagnostic has been emitted for
18221     // this constant.  Skip this enum since it may be ill-formed.
18222     if (!ECD) {
18223       return;
18224     }
18225 
18226     // Constants with initalizers are handled in the next loop.
18227     if (ECD->getInitExpr())
18228       continue;
18229 
18230     // Duplicate values are handled in the next loop.
18231     EnumMap.insert({EnumConstantToKey(ECD), ECD});
18232   }
18233 
18234   if (EnumMap.size() == 0)
18235     return;
18236 
18237   // Create vectors for any values that has duplicates.
18238   for (auto *Element : Elements) {
18239     // The last loop returned if any constant was null.
18240     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18241     if (!ValidDuplicateEnum(ECD, Enum))
18242       continue;
18243 
18244     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18245     if (Iter == EnumMap.end())
18246       continue;
18247 
18248     DeclOrVector& Entry = Iter->second;
18249     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18250       // Ensure constants are different.
18251       if (D == ECD)
18252         continue;
18253 
18254       // Create new vector and push values onto it.
18255       auto Vec = std::make_unique<ECDVector>();
18256       Vec->push_back(D);
18257       Vec->push_back(ECD);
18258 
18259       // Update entry to point to the duplicates vector.
18260       Entry = Vec.get();
18261 
18262       // Store the vector somewhere we can consult later for quick emission of
18263       // diagnostics.
18264       DupVector.emplace_back(std::move(Vec));
18265       continue;
18266     }
18267 
18268     ECDVector *Vec = Entry.get<ECDVector*>();
18269     // Make sure constants are not added more than once.
18270     if (*Vec->begin() == ECD)
18271       continue;
18272 
18273     Vec->push_back(ECD);
18274   }
18275 
18276   // Emit diagnostics.
18277   for (const auto &Vec : DupVector) {
18278     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18279 
18280     // Emit warning for one enum constant.
18281     auto *FirstECD = Vec->front();
18282     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18283       << FirstECD << toString(FirstECD->getInitVal(), 10)
18284       << FirstECD->getSourceRange();
18285 
18286     // Emit one note for each of the remaining enum constants with
18287     // the same value.
18288     for (auto *ECD : llvm::drop_begin(*Vec))
18289       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18290         << ECD << toString(ECD->getInitVal(), 10)
18291         << ECD->getSourceRange();
18292   }
18293 }
18294 
18295 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18296                              bool AllowMask) const {
18297   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18298   assert(ED->isCompleteDefinition() && "expected enum definition");
18299 
18300   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18301   llvm::APInt &FlagBits = R.first->second;
18302 
18303   if (R.second) {
18304     for (auto *E : ED->enumerators()) {
18305       const auto &EVal = E->getInitVal();
18306       // Only single-bit enumerators introduce new flag values.
18307       if (EVal.isPowerOf2())
18308         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18309     }
18310   }
18311 
18312   // A value is in a flag enum if either its bits are a subset of the enum's
18313   // flag bits (the first condition) or we are allowing masks and the same is
18314   // true of its complement (the second condition). When masks are allowed, we
18315   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18316   //
18317   // While it's true that any value could be used as a mask, the assumption is
18318   // that a mask will have all of the insignificant bits set. Anything else is
18319   // likely a logic error.
18320   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18321   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18322 }
18323 
18324 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18325                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18326                          const ParsedAttributesView &Attrs) {
18327   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18328   QualType EnumType = Context.getTypeDeclType(Enum);
18329 
18330   ProcessDeclAttributeList(S, Enum, Attrs);
18331 
18332   if (Enum->isDependentType()) {
18333     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18334       EnumConstantDecl *ECD =
18335         cast_or_null<EnumConstantDecl>(Elements[i]);
18336       if (!ECD) continue;
18337 
18338       ECD->setType(EnumType);
18339     }
18340 
18341     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18342     return;
18343   }
18344 
18345   // TODO: If the result value doesn't fit in an int, it must be a long or long
18346   // long value.  ISO C does not support this, but GCC does as an extension,
18347   // emit a warning.
18348   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18349   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18350   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18351 
18352   // Verify that all the values are okay, compute the size of the values, and
18353   // reverse the list.
18354   unsigned NumNegativeBits = 0;
18355   unsigned NumPositiveBits = 0;
18356 
18357   // Keep track of whether all elements have type int.
18358   bool AllElementsInt = true;
18359 
18360   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18361     EnumConstantDecl *ECD =
18362       cast_or_null<EnumConstantDecl>(Elements[i]);
18363     if (!ECD) continue;  // Already issued a diagnostic.
18364 
18365     const llvm::APSInt &InitVal = ECD->getInitVal();
18366 
18367     // Keep track of the size of positive and negative values.
18368     if (InitVal.isUnsigned() || InitVal.isNonNegative())
18369       NumPositiveBits = std::max(NumPositiveBits,
18370                                  (unsigned)InitVal.getActiveBits());
18371     else
18372       NumNegativeBits = std::max(NumNegativeBits,
18373                                  (unsigned)InitVal.getMinSignedBits());
18374 
18375     // Keep track of whether every enum element has type int (very common).
18376     if (AllElementsInt)
18377       AllElementsInt = ECD->getType() == Context.IntTy;
18378   }
18379 
18380   // Figure out the type that should be used for this enum.
18381   QualType BestType;
18382   unsigned BestWidth;
18383 
18384   // C++0x N3000 [conv.prom]p3:
18385   //   An rvalue of an unscoped enumeration type whose underlying
18386   //   type is not fixed can be converted to an rvalue of the first
18387   //   of the following types that can represent all the values of
18388   //   the enumeration: int, unsigned int, long int, unsigned long
18389   //   int, long long int, or unsigned long long int.
18390   // C99 6.4.4.3p2:
18391   //   An identifier declared as an enumeration constant has type int.
18392   // The C99 rule is modified by a gcc extension
18393   QualType BestPromotionType;
18394 
18395   bool Packed = Enum->hasAttr<PackedAttr>();
18396   // -fshort-enums is the equivalent to specifying the packed attribute on all
18397   // enum definitions.
18398   if (LangOpts.ShortEnums)
18399     Packed = true;
18400 
18401   // If the enum already has a type because it is fixed or dictated by the
18402   // target, promote that type instead of analyzing the enumerators.
18403   if (Enum->isComplete()) {
18404     BestType = Enum->getIntegerType();
18405     if (BestType->isPromotableIntegerType())
18406       BestPromotionType = Context.getPromotedIntegerType(BestType);
18407     else
18408       BestPromotionType = BestType;
18409 
18410     BestWidth = Context.getIntWidth(BestType);
18411   }
18412   else if (NumNegativeBits) {
18413     // If there is a negative value, figure out the smallest integer type (of
18414     // int/long/longlong) that fits.
18415     // If it's packed, check also if it fits a char or a short.
18416     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18417       BestType = Context.SignedCharTy;
18418       BestWidth = CharWidth;
18419     } else if (Packed && NumNegativeBits <= ShortWidth &&
18420                NumPositiveBits < ShortWidth) {
18421       BestType = Context.ShortTy;
18422       BestWidth = ShortWidth;
18423     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18424       BestType = Context.IntTy;
18425       BestWidth = IntWidth;
18426     } else {
18427       BestWidth = Context.getTargetInfo().getLongWidth();
18428 
18429       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18430         BestType = Context.LongTy;
18431       } else {
18432         BestWidth = Context.getTargetInfo().getLongLongWidth();
18433 
18434         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18435           Diag(Enum->getLocation(), diag::ext_enum_too_large);
18436         BestType = Context.LongLongTy;
18437       }
18438     }
18439     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18440   } else {
18441     // If there is no negative value, figure out the smallest type that fits
18442     // all of the enumerator values.
18443     // If it's packed, check also if it fits a char or a short.
18444     if (Packed && NumPositiveBits <= CharWidth) {
18445       BestType = Context.UnsignedCharTy;
18446       BestPromotionType = Context.IntTy;
18447       BestWidth = CharWidth;
18448     } else if (Packed && NumPositiveBits <= ShortWidth) {
18449       BestType = Context.UnsignedShortTy;
18450       BestPromotionType = Context.IntTy;
18451       BestWidth = ShortWidth;
18452     } else if (NumPositiveBits <= IntWidth) {
18453       BestType = Context.UnsignedIntTy;
18454       BestWidth = IntWidth;
18455       BestPromotionType
18456         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18457                            ? Context.UnsignedIntTy : Context.IntTy;
18458     } else if (NumPositiveBits <=
18459                (BestWidth = Context.getTargetInfo().getLongWidth())) {
18460       BestType = Context.UnsignedLongTy;
18461       BestPromotionType
18462         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18463                            ? Context.UnsignedLongTy : Context.LongTy;
18464     } else {
18465       BestWidth = Context.getTargetInfo().getLongLongWidth();
18466       assert(NumPositiveBits <= BestWidth &&
18467              "How could an initializer get larger than ULL?");
18468       BestType = Context.UnsignedLongLongTy;
18469       BestPromotionType
18470         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18471                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
18472     }
18473   }
18474 
18475   // Loop over all of the enumerator constants, changing their types to match
18476   // the type of the enum if needed.
18477   for (auto *D : Elements) {
18478     auto *ECD = cast_or_null<EnumConstantDecl>(D);
18479     if (!ECD) continue;  // Already issued a diagnostic.
18480 
18481     // Standard C says the enumerators have int type, but we allow, as an
18482     // extension, the enumerators to be larger than int size.  If each
18483     // enumerator value fits in an int, type it as an int, otherwise type it the
18484     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
18485     // that X has type 'int', not 'unsigned'.
18486 
18487     // Determine whether the value fits into an int.
18488     llvm::APSInt InitVal = ECD->getInitVal();
18489 
18490     // If it fits into an integer type, force it.  Otherwise force it to match
18491     // the enum decl type.
18492     QualType NewTy;
18493     unsigned NewWidth;
18494     bool NewSign;
18495     if (!getLangOpts().CPlusPlus &&
18496         !Enum->isFixed() &&
18497         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18498       NewTy = Context.IntTy;
18499       NewWidth = IntWidth;
18500       NewSign = true;
18501     } else if (ECD->getType() == BestType) {
18502       // Already the right type!
18503       if (getLangOpts().CPlusPlus)
18504         // C++ [dcl.enum]p4: Following the closing brace of an
18505         // enum-specifier, each enumerator has the type of its
18506         // enumeration.
18507         ECD->setType(EnumType);
18508       continue;
18509     } else {
18510       NewTy = BestType;
18511       NewWidth = BestWidth;
18512       NewSign = BestType->isSignedIntegerOrEnumerationType();
18513     }
18514 
18515     // Adjust the APSInt value.
18516     InitVal = InitVal.extOrTrunc(NewWidth);
18517     InitVal.setIsSigned(NewSign);
18518     ECD->setInitVal(InitVal);
18519 
18520     // Adjust the Expr initializer and type.
18521     if (ECD->getInitExpr() &&
18522         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18523       ECD->setInitExpr(ImplicitCastExpr::Create(
18524           Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18525           /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18526     if (getLangOpts().CPlusPlus)
18527       // C++ [dcl.enum]p4: Following the closing brace of an
18528       // enum-specifier, each enumerator has the type of its
18529       // enumeration.
18530       ECD->setType(EnumType);
18531     else
18532       ECD->setType(NewTy);
18533   }
18534 
18535   Enum->completeDefinition(BestType, BestPromotionType,
18536                            NumPositiveBits, NumNegativeBits);
18537 
18538   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18539 
18540   if (Enum->isClosedFlag()) {
18541     for (Decl *D : Elements) {
18542       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18543       if (!ECD) continue;  // Already issued a diagnostic.
18544 
18545       llvm::APSInt InitVal = ECD->getInitVal();
18546       if (InitVal != 0 && !InitVal.isPowerOf2() &&
18547           !IsValueInFlagEnum(Enum, InitVal, true))
18548         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18549           << ECD << Enum;
18550     }
18551   }
18552 
18553   // Now that the enum type is defined, ensure it's not been underaligned.
18554   if (Enum->hasAttrs())
18555     CheckAlignasUnderalignment(Enum);
18556 }
18557 
18558 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18559                                   SourceLocation StartLoc,
18560                                   SourceLocation EndLoc) {
18561   StringLiteral *AsmString = cast<StringLiteral>(expr);
18562 
18563   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18564                                                    AsmString, StartLoc,
18565                                                    EndLoc);
18566   CurContext->addDecl(New);
18567   return New;
18568 }
18569 
18570 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18571                                       IdentifierInfo* AliasName,
18572                                       SourceLocation PragmaLoc,
18573                                       SourceLocation NameLoc,
18574                                       SourceLocation AliasNameLoc) {
18575   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18576                                          LookupOrdinaryName);
18577   AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18578                            AttributeCommonInfo::AS_Pragma);
18579   AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18580       Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18581 
18582   // If a declaration that:
18583   // 1) declares a function or a variable
18584   // 2) has external linkage
18585   // already exists, add a label attribute to it.
18586   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18587     if (isDeclExternC(PrevDecl))
18588       PrevDecl->addAttr(Attr);
18589     else
18590       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18591           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18592   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18593   } else
18594     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18595 }
18596 
18597 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18598                              SourceLocation PragmaLoc,
18599                              SourceLocation NameLoc) {
18600   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18601 
18602   if (PrevDecl) {
18603     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18604   } else {
18605     (void)WeakUndeclaredIdentifiers.insert(
18606       std::pair<IdentifierInfo*,WeakInfo>
18607         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18608   }
18609 }
18610 
18611 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18612                                 IdentifierInfo* AliasName,
18613                                 SourceLocation PragmaLoc,
18614                                 SourceLocation NameLoc,
18615                                 SourceLocation AliasNameLoc) {
18616   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18617                                     LookupOrdinaryName);
18618   WeakInfo W = WeakInfo(Name, NameLoc);
18619 
18620   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18621     if (!PrevDecl->hasAttr<AliasAttr>())
18622       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18623         DeclApplyPragmaWeak(TUScope, ND, W);
18624   } else {
18625     (void)WeakUndeclaredIdentifiers.insert(
18626       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18627   }
18628 }
18629 
18630 Decl *Sema::getObjCDeclContext() const {
18631   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18632 }
18633 
18634 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18635                                                      bool Final) {
18636   assert(FD && "Expected non-null FunctionDecl");
18637 
18638   // SYCL functions can be template, so we check if they have appropriate
18639   // attribute prior to checking if it is a template.
18640   if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18641     return FunctionEmissionStatus::Emitted;
18642 
18643   // Templates are emitted when they're instantiated.
18644   if (FD->isDependentContext())
18645     return FunctionEmissionStatus::TemplateDiscarded;
18646 
18647   // Check whether this function is an externally visible definition.
18648   auto IsEmittedForExternalSymbol = [this, FD]() {
18649     // We have to check the GVA linkage of the function's *definition* -- if we
18650     // only have a declaration, we don't know whether or not the function will
18651     // be emitted, because (say) the definition could include "inline".
18652     FunctionDecl *Def = FD->getDefinition();
18653 
18654     return Def && !isDiscardableGVALinkage(
18655                       getASTContext().GetGVALinkageForFunction(Def));
18656   };
18657 
18658   if (LangOpts.OpenMPIsDevice) {
18659     // In OpenMP device mode we will not emit host only functions, or functions
18660     // we don't need due to their linkage.
18661     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18662         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18663     // DevTy may be changed later by
18664     //  #pragma omp declare target to(*) device_type(*).
18665     // Therefore DevTy having no value does not imply host. The emission status
18666     // will be checked again at the end of compilation unit with Final = true.
18667     if (DevTy.hasValue())
18668       if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18669         return FunctionEmissionStatus::OMPDiscarded;
18670     // If we have an explicit value for the device type, or we are in a target
18671     // declare context, we need to emit all extern and used symbols.
18672     if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18673       if (IsEmittedForExternalSymbol())
18674         return FunctionEmissionStatus::Emitted;
18675     // Device mode only emits what it must, if it wasn't tagged yet and needed,
18676     // we'll omit it.
18677     if (Final)
18678       return FunctionEmissionStatus::OMPDiscarded;
18679   } else if (LangOpts.OpenMP > 45) {
18680     // In OpenMP host compilation prior to 5.0 everything was an emitted host
18681     // function. In 5.0, no_host was introduced which might cause a function to
18682     // be ommitted.
18683     Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18684         OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18685     if (DevTy.hasValue())
18686       if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18687         return FunctionEmissionStatus::OMPDiscarded;
18688   }
18689 
18690   if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18691     return FunctionEmissionStatus::Emitted;
18692 
18693   if (LangOpts.CUDA) {
18694     // When compiling for device, host functions are never emitted.  Similarly,
18695     // when compiling for host, device and global functions are never emitted.
18696     // (Technically, we do emit a host-side stub for global functions, but this
18697     // doesn't count for our purposes here.)
18698     Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18699     if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18700       return FunctionEmissionStatus::CUDADiscarded;
18701     if (!LangOpts.CUDAIsDevice &&
18702         (T == Sema::CFT_Device || T == Sema::CFT_Global))
18703       return FunctionEmissionStatus::CUDADiscarded;
18704 
18705     if (IsEmittedForExternalSymbol())
18706       return FunctionEmissionStatus::Emitted;
18707   }
18708 
18709   // Otherwise, the function is known-emitted if it's in our set of
18710   // known-emitted functions.
18711   return FunctionEmissionStatus::Unknown;
18712 }
18713 
18714 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18715   // Host-side references to a __global__ function refer to the stub, so the
18716   // function itself is never emitted and therefore should not be marked.
18717   // If we have host fn calls kernel fn calls host+device, the HD function
18718   // does not get instantiated on the host. We model this by omitting at the
18719   // call to the kernel from the callgraph. This ensures that, when compiling
18720   // for host, only HD functions actually called from the host get marked as
18721   // known-emitted.
18722   return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18723          IdentifyCUDATarget(Callee) == CFT_Global;
18724 }
18725