1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142 
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150 
151   case tok::kw_char8_t:
152     return getLangOpts().Char8;
153 
154   default:
155     break;
156   }
157 
158   return false;
159 }
160 
161 namespace {
162 enum class UnqualifiedTypeNameLookupResult {
163   NotFound,
164   FoundNonType,
165   FoundType
166 };
167 } // end anonymous namespace
168 
169 /// Tries to perform unqualified lookup of the type decls in bases for
170 /// dependent class.
171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
172 /// type decl, \a FoundType if only type decls are found.
173 static UnqualifiedTypeNameLookupResult
174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
175                                 SourceLocation NameLoc,
176                                 const CXXRecordDecl *RD) {
177   if (!RD->hasDefinition())
178     return UnqualifiedTypeNameLookupResult::NotFound;
179   // Look for type decls in base classes.
180   UnqualifiedTypeNameLookupResult FoundTypeDecl =
181       UnqualifiedTypeNameLookupResult::NotFound;
182   for (const auto &Base : RD->bases()) {
183     const CXXRecordDecl *BaseRD = nullptr;
184     if (auto *BaseTT = Base.getType()->getAs<TagType>())
185       BaseRD = BaseTT->getAsCXXRecordDecl();
186     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
187       // Look for type decls in dependent base classes that have known primary
188       // templates.
189       if (!TST || !TST->isDependentType())
190         continue;
191       auto *TD = TST->getTemplateName().getAsTemplateDecl();
192       if (!TD)
193         continue;
194       if (auto *BasePrimaryTemplate =
195           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
196         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
197           BaseRD = BasePrimaryTemplate;
198         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
199           if (const ClassTemplatePartialSpecializationDecl *PS =
200                   CTD->findPartialSpecialization(Base.getType()))
201             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
202               BaseRD = PS;
203         }
204       }
205     }
206     if (BaseRD) {
207       for (NamedDecl *ND : BaseRD->lookup(&II)) {
208         if (!isa<TypeDecl>(ND))
209           return UnqualifiedTypeNameLookupResult::FoundNonType;
210         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
211       }
212       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
213         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
214         case UnqualifiedTypeNameLookupResult::FoundNonType:
215           return UnqualifiedTypeNameLookupResult::FoundNonType;
216         case UnqualifiedTypeNameLookupResult::FoundType:
217           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218           break;
219         case UnqualifiedTypeNameLookupResult::NotFound:
220           break;
221         }
222       }
223     }
224   }
225 
226   return FoundTypeDecl;
227 }
228 
229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
230                                                       const IdentifierInfo &II,
231                                                       SourceLocation NameLoc) {
232   // Lookup in the parent class template context, if any.
233   const CXXRecordDecl *RD = nullptr;
234   UnqualifiedTypeNameLookupResult FoundTypeDecl =
235       UnqualifiedTypeNameLookupResult::NotFound;
236   for (DeclContext *DC = S.CurContext;
237        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
238        DC = DC->getParent()) {
239     // Look for type decls in dependent base classes that have known primary
240     // templates.
241     RD = dyn_cast<CXXRecordDecl>(DC);
242     if (RD && RD->getDescribedClassTemplate())
243       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
244   }
245   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
246     return nullptr;
247 
248   // We found some types in dependent base classes.  Recover as if the user
249   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
250   // lookup during template instantiation.
251   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
252 
253   ASTContext &Context = S.Context;
254   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
255                                           cast<Type>(Context.getRecordType(RD)));
256   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
257 
258   CXXScopeSpec SS;
259   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
260 
261   TypeLocBuilder Builder;
262   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
263   DepTL.setNameLoc(NameLoc);
264   DepTL.setElaboratedKeywordLoc(SourceLocation());
265   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
266   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
267 }
268 
269 /// If the identifier refers to a type name within this scope,
270 /// return the declaration of that type.
271 ///
272 /// This routine performs ordinary name lookup of the identifier II
273 /// within the given scope, with optional C++ scope specifier SS, to
274 /// determine whether the name refers to a type. If so, returns an
275 /// opaque pointer (actually a QualType) corresponding to that
276 /// type. Otherwise, returns NULL.
277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
278                              Scope *S, CXXScopeSpec *SS,
279                              bool isClassName, bool HasTrailingDot,
280                              ParsedType ObjectTypePtr,
281                              bool IsCtorOrDtorName,
282                              bool WantNontrivialTypeSourceInfo,
283                              bool IsClassTemplateDeductionContext,
284                              IdentifierInfo **CorrectedII) {
285   // FIXME: Consider allowing this outside C++1z mode as an extension.
286   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
287                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
288                               !isClassName && !HasTrailingDot;
289 
290   // Determine where we will perform name lookup.
291   DeclContext *LookupCtx = nullptr;
292   if (ObjectTypePtr) {
293     QualType ObjectType = ObjectTypePtr.get();
294     if (ObjectType->isRecordType())
295       LookupCtx = computeDeclContext(ObjectType);
296   } else if (SS && SS->isNotEmpty()) {
297     LookupCtx = computeDeclContext(*SS, false);
298 
299     if (!LookupCtx) {
300       if (isDependentScopeSpecifier(*SS)) {
301         // C++ [temp.res]p3:
302         //   A qualified-id that refers to a type and in which the
303         //   nested-name-specifier depends on a template-parameter (14.6.2)
304         //   shall be prefixed by the keyword typename to indicate that the
305         //   qualified-id denotes a type, forming an
306         //   elaborated-type-specifier (7.1.5.3).
307         //
308         // We therefore do not perform any name lookup if the result would
309         // refer to a member of an unknown specialization.
310         if (!isClassName && !IsCtorOrDtorName)
311           return nullptr;
312 
313         // We know from the grammar that this name refers to a type,
314         // so build a dependent node to describe the type.
315         if (WantNontrivialTypeSourceInfo)
316           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
317 
318         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
319         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
320                                        II, NameLoc);
321         return ParsedType::make(T);
322       }
323 
324       return nullptr;
325     }
326 
327     if (!LookupCtx->isDependentContext() &&
328         RequireCompleteDeclContext(*SS, LookupCtx))
329       return nullptr;
330   }
331 
332   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
333   // lookup for class-names.
334   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
335                                       LookupOrdinaryName;
336   LookupResult Result(*this, &II, NameLoc, Kind);
337   if (LookupCtx) {
338     // Perform "qualified" name lookup into the declaration context we
339     // computed, which is either the type of the base of a member access
340     // expression or the declaration context associated with a prior
341     // nested-name-specifier.
342     LookupQualifiedName(Result, LookupCtx);
343 
344     if (ObjectTypePtr && Result.empty()) {
345       // C++ [basic.lookup.classref]p3:
346       //   If the unqualified-id is ~type-name, the type-name is looked up
347       //   in the context of the entire postfix-expression. If the type T of
348       //   the object expression is of a class type C, the type-name is also
349       //   looked up in the scope of class C. At least one of the lookups shall
350       //   find a name that refers to (possibly cv-qualified) T.
351       LookupName(Result, S);
352     }
353   } else {
354     // Perform unqualified name lookup.
355     LookupName(Result, S);
356 
357     // For unqualified lookup in a class template in MSVC mode, look into
358     // dependent base classes where the primary class template is known.
359     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
360       if (ParsedType TypeInBase =
361               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
362         return TypeInBase;
363     }
364   }
365 
366   NamedDecl *IIDecl = nullptr;
367   switch (Result.getResultKind()) {
368   case LookupResult::NotFound:
369   case LookupResult::NotFoundInCurrentInstantiation:
370     if (CorrectedII) {
371       TypoCorrection Correction =
372           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
373                       llvm::make_unique<TypeNameValidatorCCC>(
374                           true, isClassName, AllowDeducedTemplate),
375                       CTK_ErrorRecovery);
376       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
377       TemplateTy Template;
378       bool MemberOfUnknownSpecialization;
379       UnqualifiedId TemplateName;
380       TemplateName.setIdentifier(NewII, NameLoc);
381       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
382       CXXScopeSpec NewSS, *NewSSPtr = SS;
383       if (SS && NNS) {
384         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
385         NewSSPtr = &NewSS;
386       }
387       if (Correction && (NNS || NewII != &II) &&
388           // Ignore a correction to a template type as the to-be-corrected
389           // identifier is not a template (typo correction for template names
390           // is handled elsewhere).
391           !(getLangOpts().CPlusPlus && NewSSPtr &&
392             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
393                            Template, MemberOfUnknownSpecialization))) {
394         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
395                                     isClassName, HasTrailingDot, ObjectTypePtr,
396                                     IsCtorOrDtorName,
397                                     WantNontrivialTypeSourceInfo,
398                                     IsClassTemplateDeductionContext);
399         if (Ty) {
400           diagnoseTypo(Correction,
401                        PDiag(diag::err_unknown_type_or_class_name_suggest)
402                          << Result.getLookupName() << isClassName);
403           if (SS && NNS)
404             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
405           *CorrectedII = NewII;
406           return Ty;
407         }
408       }
409     }
410     // If typo correction failed or was not performed, fall through
411     LLVM_FALLTHROUGH;
412   case LookupResult::FoundOverloaded:
413   case LookupResult::FoundUnresolvedValue:
414     Result.suppressDiagnostics();
415     return nullptr;
416 
417   case LookupResult::Ambiguous:
418     // Recover from type-hiding ambiguities by hiding the type.  We'll
419     // do the lookup again when looking for an object, and we can
420     // diagnose the error then.  If we don't do this, then the error
421     // about hiding the type will be immediately followed by an error
422     // that only makes sense if the identifier was treated like a type.
423     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
424       Result.suppressDiagnostics();
425       return nullptr;
426     }
427 
428     // Look to see if we have a type anywhere in the list of results.
429     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
430          Res != ResEnd; ++Res) {
431       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
432           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
433         if (!IIDecl ||
434             (*Res)->getLocation().getRawEncoding() <
435               IIDecl->getLocation().getRawEncoding())
436           IIDecl = *Res;
437       }
438     }
439 
440     if (!IIDecl) {
441       // None of the entities we found is a type, so there is no way
442       // to even assume that the result is a type. In this case, don't
443       // complain about the ambiguity. The parser will either try to
444       // perform this lookup again (e.g., as an object name), which
445       // will produce the ambiguity, or will complain that it expected
446       // a type name.
447       Result.suppressDiagnostics();
448       return nullptr;
449     }
450 
451     // We found a type within the ambiguous lookup; diagnose the
452     // ambiguity and then return that type. This might be the right
453     // answer, or it might not be, but it suppresses any attempt to
454     // perform the name lookup again.
455     break;
456 
457   case LookupResult::Found:
458     IIDecl = Result.getFoundDecl();
459     break;
460   }
461 
462   assert(IIDecl && "Didn't find decl");
463 
464   QualType T;
465   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
466     // C++ [class.qual]p2: A lookup that would find the injected-class-name
467     // instead names the constructors of the class, except when naming a class.
468     // This is ill-formed when we're not actually forming a ctor or dtor name.
469     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
470     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
471     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
472         FoundRD->isInjectedClassName() &&
473         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
474       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
475           << &II << /*Type*/1;
476 
477     DiagnoseUseOfDecl(IIDecl, NameLoc);
478 
479     T = Context.getTypeDeclType(TD);
480     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
481   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
482     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
483     if (!HasTrailingDot)
484       T = Context.getObjCInterfaceType(IDecl);
485   } else if (AllowDeducedTemplate) {
486     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
487       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
488                                                        QualType(), false);
489   }
490 
491   if (T.isNull()) {
492     // If it's not plausibly a type, suppress diagnostics.
493     Result.suppressDiagnostics();
494     return nullptr;
495   }
496 
497   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
498   // constructor or destructor name (in such a case, the scope specifier
499   // will be attached to the enclosing Expr or Decl node).
500   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
501       !isa<ObjCInterfaceDecl>(IIDecl)) {
502     if (WantNontrivialTypeSourceInfo) {
503       // Construct a type with type-source information.
504       TypeLocBuilder Builder;
505       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
506 
507       T = getElaboratedType(ETK_None, *SS, T);
508       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
509       ElabTL.setElaboratedKeywordLoc(SourceLocation());
510       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
511       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
512     } else {
513       T = getElaboratedType(ETK_None, *SS, T);
514     }
515   }
516 
517   return ParsedType::make(T);
518 }
519 
520 // Builds a fake NNS for the given decl context.
521 static NestedNameSpecifier *
522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
523   for (;; DC = DC->getLookupParent()) {
524     DC = DC->getPrimaryContext();
525     auto *ND = dyn_cast<NamespaceDecl>(DC);
526     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
527       return NestedNameSpecifier::Create(Context, nullptr, ND);
528     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
529       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
530                                          RD->getTypeForDecl());
531     else if (isa<TranslationUnitDecl>(DC))
532       return NestedNameSpecifier::GlobalSpecifier(Context);
533   }
534   llvm_unreachable("something isn't in TU scope?");
535 }
536 
537 /// Find the parent class with dependent bases of the innermost enclosing method
538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
539 /// up allowing unqualified dependent type names at class-level, which MSVC
540 /// correctly rejects.
541 static const CXXRecordDecl *
542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
543   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
544     DC = DC->getPrimaryContext();
545     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
546       if (MD->getParent()->hasAnyDependentBases())
547         return MD->getParent();
548   }
549   return nullptr;
550 }
551 
552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
553                                           SourceLocation NameLoc,
554                                           bool IsTemplateTypeArg) {
555   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
556 
557   NestedNameSpecifier *NNS = nullptr;
558   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
559     // If we weren't able to parse a default template argument, delay lookup
560     // until instantiation time by making a non-dependent DependentTypeName. We
561     // pretend we saw a NestedNameSpecifier referring to the current scope, and
562     // lookup is retried.
563     // FIXME: This hurts our diagnostic quality, since we get errors like "no
564     // type named 'Foo' in 'current_namespace'" when the user didn't write any
565     // name specifiers.
566     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
567     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
568   } else if (const CXXRecordDecl *RD =
569                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
570     // Build a DependentNameType that will perform lookup into RD at
571     // instantiation time.
572     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
573                                       RD->getTypeForDecl());
574 
575     // Diagnose that this identifier was undeclared, and retry the lookup during
576     // template instantiation.
577     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
578                                                                       << RD;
579   } else {
580     // This is not a situation that we should recover from.
581     return ParsedType();
582   }
583 
584   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
585 
586   // Build type location information.  We synthesized the qualifier, so we have
587   // to build a fake NestedNameSpecifierLoc.
588   NestedNameSpecifierLocBuilder NNSLocBuilder;
589   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
590   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
591 
592   TypeLocBuilder Builder;
593   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
594   DepTL.setNameLoc(NameLoc);
595   DepTL.setElaboratedKeywordLoc(SourceLocation());
596   DepTL.setQualifierLoc(QualifierLoc);
597   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
598 }
599 
600 /// isTagName() - This method is called *for error recovery purposes only*
601 /// to determine if the specified name is a valid tag name ("struct foo").  If
602 /// so, this returns the TST for the tag corresponding to it (TST_enum,
603 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
604 /// cases in C where the user forgot to specify the tag.
605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
606   // Do a tag name lookup in this scope.
607   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
608   LookupName(R, S, false);
609   R.suppressDiagnostics();
610   if (R.getResultKind() == LookupResult::Found)
611     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
612       switch (TD->getTagKind()) {
613       case TTK_Struct: return DeclSpec::TST_struct;
614       case TTK_Interface: return DeclSpec::TST_interface;
615       case TTK_Union:  return DeclSpec::TST_union;
616       case TTK_Class:  return DeclSpec::TST_class;
617       case TTK_Enum:   return DeclSpec::TST_enum;
618       }
619     }
620 
621   return DeclSpec::TST_unspecified;
622 }
623 
624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
626 /// then downgrade the missing typename error to a warning.
627 /// This is needed for MSVC compatibility; Example:
628 /// @code
629 /// template<class T> class A {
630 /// public:
631 ///   typedef int TYPE;
632 /// };
633 /// template<class T> class B : public A<T> {
634 /// public:
635 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
636 /// };
637 /// @endcode
638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
639   if (CurContext->isRecord()) {
640     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
641       return true;
642 
643     const Type *Ty = SS->getScopeRep()->getAsType();
644 
645     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
646     for (const auto &Base : RD->bases())
647       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
648         return true;
649     return S->isFunctionPrototypeScope();
650   }
651   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
652 }
653 
654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
655                                    SourceLocation IILoc,
656                                    Scope *S,
657                                    CXXScopeSpec *SS,
658                                    ParsedType &SuggestedType,
659                                    bool IsTemplateName) {
660   // Don't report typename errors for editor placeholders.
661   if (II->isEditorPlaceholder())
662     return;
663   // We don't have anything to suggest (yet).
664   SuggestedType = nullptr;
665 
666   // There may have been a typo in the name of the type. Look up typo
667   // results, in case we have something that we can suggest.
668   if (TypoCorrection Corrected =
669           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
670                       llvm::make_unique<TypeNameValidatorCCC>(
671                           false, false, IsTemplateName, !IsTemplateName),
672                       CTK_ErrorRecovery)) {
673     // FIXME: Support error recovery for the template-name case.
674     bool CanRecover = !IsTemplateName;
675     if (Corrected.isKeyword()) {
676       // We corrected to a keyword.
677       diagnoseTypo(Corrected,
678                    PDiag(IsTemplateName ? diag::err_no_template_suggest
679                                         : diag::err_unknown_typename_suggest)
680                        << II);
681       II = Corrected.getCorrectionAsIdentifierInfo();
682     } else {
683       // We found a similarly-named type or interface; suggest that.
684       if (!SS || !SS->isSet()) {
685         diagnoseTypo(Corrected,
686                      PDiag(IsTemplateName ? diag::err_no_template_suggest
687                                           : diag::err_unknown_typename_suggest)
688                          << II, CanRecover);
689       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
690         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
691         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
692                                 II->getName().equals(CorrectedStr);
693         diagnoseTypo(Corrected,
694                      PDiag(IsTemplateName
695                                ? diag::err_no_member_template_suggest
696                                : diag::err_unknown_nested_typename_suggest)
697                          << II << DC << DroppedSpecifier << SS->getRange(),
698                      CanRecover);
699       } else {
700         llvm_unreachable("could not have corrected a typo here");
701       }
702 
703       if (!CanRecover)
704         return;
705 
706       CXXScopeSpec tmpSS;
707       if (Corrected.getCorrectionSpecifier())
708         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
709                           SourceRange(IILoc));
710       // FIXME: Support class template argument deduction here.
711       SuggestedType =
712           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
713                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
714                       /*IsCtorOrDtorName=*/false,
715                       /*NonTrivialTypeSourceInfo=*/true);
716     }
717     return;
718   }
719 
720   if (getLangOpts().CPlusPlus && !IsTemplateName) {
721     // See if II is a class template that the user forgot to pass arguments to.
722     UnqualifiedId Name;
723     Name.setIdentifier(II, IILoc);
724     CXXScopeSpec EmptySS;
725     TemplateTy TemplateResult;
726     bool MemberOfUnknownSpecialization;
727     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
728                        Name, nullptr, true, TemplateResult,
729                        MemberOfUnknownSpecialization) == TNK_Type_template) {
730       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
731       return;
732     }
733   }
734 
735   // FIXME: Should we move the logic that tries to recover from a missing tag
736   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
737 
738   if (!SS || (!SS->isSet() && !SS->isInvalid()))
739     Diag(IILoc, IsTemplateName ? diag::err_no_template
740                                : diag::err_unknown_typename)
741         << II;
742   else if (DeclContext *DC = computeDeclContext(*SS, false))
743     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
744                                : diag::err_typename_nested_not_found)
745         << II << DC << SS->getRange();
746   else if (isDependentScopeSpecifier(*SS)) {
747     unsigned DiagID = diag::err_typename_missing;
748     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
749       DiagID = diag::ext_typename_missing;
750 
751     Diag(SS->getRange().getBegin(), DiagID)
752       << SS->getScopeRep() << II->getName()
753       << SourceRange(SS->getRange().getBegin(), IILoc)
754       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
755     SuggestedType = ActOnTypenameType(S, SourceLocation(),
756                                       *SS, *II, IILoc).get();
757   } else {
758     assert(SS && SS->isInvalid() &&
759            "Invalid scope specifier has already been diagnosed");
760   }
761 }
762 
763 /// Determine whether the given result set contains either a type name
764 /// or
765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
766   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
767                        NextToken.is(tok::less);
768 
769   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
770     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
771       return true;
772 
773     if (CheckTemplate && isa<TemplateDecl>(*I))
774       return true;
775   }
776 
777   return false;
778 }
779 
780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
781                                     Scope *S, CXXScopeSpec &SS,
782                                     IdentifierInfo *&Name,
783                                     SourceLocation NameLoc) {
784   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
785   SemaRef.LookupParsedName(R, S, &SS);
786   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
787     StringRef FixItTagName;
788     switch (Tag->getTagKind()) {
789       case TTK_Class:
790         FixItTagName = "class ";
791         break;
792 
793       case TTK_Enum:
794         FixItTagName = "enum ";
795         break;
796 
797       case TTK_Struct:
798         FixItTagName = "struct ";
799         break;
800 
801       case TTK_Interface:
802         FixItTagName = "__interface ";
803         break;
804 
805       case TTK_Union:
806         FixItTagName = "union ";
807         break;
808     }
809 
810     StringRef TagName = FixItTagName.drop_back();
811     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
812       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
813       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
814 
815     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
816          I != IEnd; ++I)
817       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
818         << Name << TagName;
819 
820     // Replace lookup results with just the tag decl.
821     Result.clear(Sema::LookupTagName);
822     SemaRef.LookupParsedName(Result, S, &SS);
823     return true;
824   }
825 
826   return false;
827 }
828 
829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
831                                   QualType T, SourceLocation NameLoc) {
832   ASTContext &Context = S.Context;
833 
834   TypeLocBuilder Builder;
835   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
836 
837   T = S.getElaboratedType(ETK_None, SS, T);
838   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
839   ElabTL.setElaboratedKeywordLoc(SourceLocation());
840   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
841   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
842 }
843 
844 Sema::NameClassification
845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
846                    SourceLocation NameLoc, const Token &NextToken,
847                    bool IsAddressOfOperand,
848                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
849   DeclarationNameInfo NameInfo(Name, NameLoc);
850   ObjCMethodDecl *CurMethod = getCurMethodDecl();
851 
852   if (NextToken.is(tok::coloncolon)) {
853     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
854     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
855   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
856              isCurrentClassName(*Name, S, &SS)) {
857     // Per [class.qual]p2, this names the constructors of SS, not the
858     // injected-class-name. We don't have a classification for that.
859     // There's not much point caching this result, since the parser
860     // will reject it later.
861     return NameClassification::Unknown();
862   }
863 
864   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
865   LookupParsedName(Result, S, &SS, !CurMethod);
866 
867   // For unqualified lookup in a class template in MSVC mode, look into
868   // dependent base classes where the primary class template is known.
869   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
870     if (ParsedType TypeInBase =
871             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
872       return TypeInBase;
873   }
874 
875   // Perform lookup for Objective-C instance variables (including automatically
876   // synthesized instance variables), if we're in an Objective-C method.
877   // FIXME: This lookup really, really needs to be folded in to the normal
878   // unqualified lookup mechanism.
879   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
880     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
881     if (E.get() || E.isInvalid())
882       return E;
883   }
884 
885   bool SecondTry = false;
886   bool IsFilteredTemplateName = false;
887 
888 Corrected:
889   switch (Result.getResultKind()) {
890   case LookupResult::NotFound:
891     // If an unqualified-id is followed by a '(', then we have a function
892     // call.
893     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
894       // In C++, this is an ADL-only call.
895       // FIXME: Reference?
896       if (getLangOpts().CPlusPlus)
897         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
898 
899       // C90 6.3.2.2:
900       //   If the expression that precedes the parenthesized argument list in a
901       //   function call consists solely of an identifier, and if no
902       //   declaration is visible for this identifier, the identifier is
903       //   implicitly declared exactly as if, in the innermost block containing
904       //   the function call, the declaration
905       //
906       //     extern int identifier ();
907       //
908       //   appeared.
909       //
910       // We also allow this in C99 as an extension.
911       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
912         Result.addDecl(D);
913         Result.resolveKind();
914         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
915       }
916     }
917 
918     // In C, we first see whether there is a tag type by the same name, in
919     // which case it's likely that the user just forgot to write "enum",
920     // "struct", or "union".
921     if (!getLangOpts().CPlusPlus && !SecondTry &&
922         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
923       break;
924     }
925 
926     // Perform typo correction to determine if there is another name that is
927     // close to this name.
928     if (!SecondTry && CCC) {
929       SecondTry = true;
930       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
931                                                  Result.getLookupKind(), S,
932                                                  &SS, std::move(CCC),
933                                                  CTK_ErrorRecovery)) {
934         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
935         unsigned QualifiedDiag = diag::err_no_member_suggest;
936 
937         NamedDecl *FirstDecl = Corrected.getFoundDecl();
938         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
939         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
940             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
941           UnqualifiedDiag = diag::err_no_template_suggest;
942           QualifiedDiag = diag::err_no_member_template_suggest;
943         } else if (UnderlyingFirstDecl &&
944                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
946                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
947           UnqualifiedDiag = diag::err_unknown_typename_suggest;
948           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
949         }
950 
951         if (SS.isEmpty()) {
952           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
953         } else {// FIXME: is this even reachable? Test it.
954           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
955           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
956                                   Name->getName().equals(CorrectedStr);
957           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
958                                     << Name << computeDeclContext(SS, false)
959                                     << DroppedSpecifier << SS.getRange());
960         }
961 
962         // Update the name, so that the caller has the new name.
963         Name = Corrected.getCorrectionAsIdentifierInfo();
964 
965         // Typo correction corrected to a keyword.
966         if (Corrected.isKeyword())
967           return Name;
968 
969         // Also update the LookupResult...
970         // FIXME: This should probably go away at some point
971         Result.clear();
972         Result.setLookupName(Corrected.getCorrection());
973         if (FirstDecl)
974           Result.addDecl(FirstDecl);
975 
976         // If we found an Objective-C instance variable, let
977         // LookupInObjCMethod build the appropriate expression to
978         // reference the ivar.
979         // FIXME: This is a gross hack.
980         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
981           Result.clear();
982           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
983           return E;
984         }
985 
986         goto Corrected;
987       }
988     }
989 
990     // We failed to correct; just fall through and let the parser deal with it.
991     Result.suppressDiagnostics();
992     return NameClassification::Unknown();
993 
994   case LookupResult::NotFoundInCurrentInstantiation: {
995     // We performed name lookup into the current instantiation, and there were
996     // dependent bases, so we treat this result the same way as any other
997     // dependent nested-name-specifier.
998 
999     // C++ [temp.res]p2:
1000     //   A name used in a template declaration or definition and that is
1001     //   dependent on a template-parameter is assumed not to name a type
1002     //   unless the applicable name lookup finds a type name or the name is
1003     //   qualified by the keyword typename.
1004     //
1005     // FIXME: If the next token is '<', we might want to ask the parser to
1006     // perform some heroics to see if we actually have a
1007     // template-argument-list, which would indicate a missing 'template'
1008     // keyword here.
1009     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1010                                       NameInfo, IsAddressOfOperand,
1011                                       /*TemplateArgs=*/nullptr);
1012   }
1013 
1014   case LookupResult::Found:
1015   case LookupResult::FoundOverloaded:
1016   case LookupResult::FoundUnresolvedValue:
1017     break;
1018 
1019   case LookupResult::Ambiguous:
1020     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1021         hasAnyAcceptableTemplateNames(Result)) {
1022       // C++ [temp.local]p3:
1023       //   A lookup that finds an injected-class-name (10.2) can result in an
1024       //   ambiguity in certain cases (for example, if it is found in more than
1025       //   one base class). If all of the injected-class-names that are found
1026       //   refer to specializations of the same class template, and if the name
1027       //   is followed by a template-argument-list, the reference refers to the
1028       //   class template itself and not a specialization thereof, and is not
1029       //   ambiguous.
1030       //
1031       // This filtering can make an ambiguous result into an unambiguous one,
1032       // so try again after filtering out template names.
1033       FilterAcceptableTemplateNames(Result);
1034       if (!Result.isAmbiguous()) {
1035         IsFilteredTemplateName = true;
1036         break;
1037       }
1038     }
1039 
1040     // Diagnose the ambiguity and return an error.
1041     return NameClassification::Error();
1042   }
1043 
1044   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1046     // C++ [temp.names]p3:
1047     //   After name lookup (3.4) finds that a name is a template-name or that
1048     //   an operator-function-id or a literal- operator-id refers to a set of
1049     //   overloaded functions any member of which is a function template if
1050     //   this is followed by a <, the < is always taken as the delimiter of a
1051     //   template-argument-list and never as the less-than operator.
1052     if (!IsFilteredTemplateName)
1053       FilterAcceptableTemplateNames(Result);
1054 
1055     if (!Result.empty()) {
1056       bool IsFunctionTemplate;
1057       bool IsVarTemplate;
1058       TemplateName Template;
1059       if (Result.end() - Result.begin() > 1) {
1060         IsFunctionTemplate = true;
1061         Template = Context.getOverloadedTemplateName(Result.begin(),
1062                                                      Result.end());
1063       } else {
1064         TemplateDecl *TD
1065           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1066         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1067         IsVarTemplate = isa<VarTemplateDecl>(TD);
1068 
1069         if (SS.isSet() && !SS.isInvalid())
1070           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1071                                                     /*TemplateKeyword=*/false,
1072                                                       TD);
1073         else
1074           Template = TemplateName(TD);
1075       }
1076 
1077       if (IsFunctionTemplate) {
1078         // Function templates always go through overload resolution, at which
1079         // point we'll perform the various checks (e.g., accessibility) we need
1080         // to based on which function we selected.
1081         Result.suppressDiagnostics();
1082 
1083         return NameClassification::FunctionTemplate(Template);
1084       }
1085 
1086       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1087                            : NameClassification::TypeTemplate(Template);
1088     }
1089   }
1090 
1091   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1092   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1093     DiagnoseUseOfDecl(Type, NameLoc);
1094     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1095     QualType T = Context.getTypeDeclType(Type);
1096     if (SS.isNotEmpty())
1097       return buildNestedType(*this, SS, T, NameLoc);
1098     return ParsedType::make(T);
1099   }
1100 
1101   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1102   if (!Class) {
1103     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1104     if (ObjCCompatibleAliasDecl *Alias =
1105             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1106       Class = Alias->getClassInterface();
1107   }
1108 
1109   if (Class) {
1110     DiagnoseUseOfDecl(Class, NameLoc);
1111 
1112     if (NextToken.is(tok::period)) {
1113       // Interface. <something> is parsed as a property reference expression.
1114       // Just return "unknown" as a fall-through for now.
1115       Result.suppressDiagnostics();
1116       return NameClassification::Unknown();
1117     }
1118 
1119     QualType T = Context.getObjCInterfaceType(Class);
1120     return ParsedType::make(T);
1121   }
1122 
1123   // We can have a type template here if we're classifying a template argument.
1124   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1125       !isa<VarTemplateDecl>(FirstDecl))
1126     return NameClassification::TypeTemplate(
1127         TemplateName(cast<TemplateDecl>(FirstDecl)));
1128 
1129   // Check for a tag type hidden by a non-type decl in a few cases where it
1130   // seems likely a type is wanted instead of the non-type that was found.
1131   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1132   if ((NextToken.is(tok::identifier) ||
1133        (NextIsOp &&
1134         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1135       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1136     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1137     DiagnoseUseOfDecl(Type, NameLoc);
1138     QualType T = Context.getTypeDeclType(Type);
1139     if (SS.isNotEmpty())
1140       return buildNestedType(*this, SS, T, NameLoc);
1141     return ParsedType::make(T);
1142   }
1143 
1144   if (FirstDecl->isCXXClassMember())
1145     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1146                                            nullptr, S);
1147 
1148   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1149   return BuildDeclarationNameExpr(SS, Result, ADL);
1150 }
1151 
1152 Sema::TemplateNameKindForDiagnostics
1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1154   auto *TD = Name.getAsTemplateDecl();
1155   if (!TD)
1156     return TemplateNameKindForDiagnostics::DependentTemplate;
1157   if (isa<ClassTemplateDecl>(TD))
1158     return TemplateNameKindForDiagnostics::ClassTemplate;
1159   if (isa<FunctionTemplateDecl>(TD))
1160     return TemplateNameKindForDiagnostics::FunctionTemplate;
1161   if (isa<VarTemplateDecl>(TD))
1162     return TemplateNameKindForDiagnostics::VarTemplate;
1163   if (isa<TypeAliasTemplateDecl>(TD))
1164     return TemplateNameKindForDiagnostics::AliasTemplate;
1165   if (isa<TemplateTemplateParmDecl>(TD))
1166     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1167   return TemplateNameKindForDiagnostics::DependentTemplate;
1168 }
1169 
1170 // Determines the context to return to after temporarily entering a
1171 // context.  This depends in an unnecessarily complicated way on the
1172 // exact ordering of callbacks from the parser.
1173 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1174 
1175   // Functions defined inline within classes aren't parsed until we've
1176   // finished parsing the top-level class, so the top-level class is
1177   // the context we'll need to return to.
1178   // A Lambda call operator whose parent is a class must not be treated
1179   // as an inline member function.  A Lambda can be used legally
1180   // either as an in-class member initializer or a default argument.  These
1181   // are parsed once the class has been marked complete and so the containing
1182   // context would be the nested class (when the lambda is defined in one);
1183   // If the class is not complete, then the lambda is being used in an
1184   // ill-formed fashion (such as to specify the width of a bit-field, or
1185   // in an array-bound) - in which case we still want to return the
1186   // lexically containing DC (which could be a nested class).
1187   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1188     DC = DC->getLexicalParent();
1189 
1190     // A function not defined within a class will always return to its
1191     // lexical context.
1192     if (!isa<CXXRecordDecl>(DC))
1193       return DC;
1194 
1195     // A C++ inline method/friend is parsed *after* the topmost class
1196     // it was declared in is fully parsed ("complete");  the topmost
1197     // class is the context we need to return to.
1198     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1199       DC = RD;
1200 
1201     // Return the declaration context of the topmost class the inline method is
1202     // declared in.
1203     return DC;
1204   }
1205 
1206   return DC->getLexicalParent();
1207 }
1208 
1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1210   assert(getContainingDC(DC) == CurContext &&
1211       "The next DeclContext should be lexically contained in the current one.");
1212   CurContext = DC;
1213   S->setEntity(DC);
1214 }
1215 
1216 void Sema::PopDeclContext() {
1217   assert(CurContext && "DeclContext imbalance!");
1218 
1219   CurContext = getContainingDC(CurContext);
1220   assert(CurContext && "Popped translation unit!");
1221 }
1222 
1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1224                                                                     Decl *D) {
1225   // Unlike PushDeclContext, the context to which we return is not necessarily
1226   // the containing DC of TD, because the new context will be some pre-existing
1227   // TagDecl definition instead of a fresh one.
1228   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1229   CurContext = cast<TagDecl>(D)->getDefinition();
1230   assert(CurContext && "skipping definition of undefined tag");
1231   // Start lookups from the parent of the current context; we don't want to look
1232   // into the pre-existing complete definition.
1233   S->setEntity(CurContext->getLookupParent());
1234   return Result;
1235 }
1236 
1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1238   CurContext = static_cast<decltype(CurContext)>(Context);
1239 }
1240 
1241 /// EnterDeclaratorContext - Used when we must lookup names in the context
1242 /// of a declarator's nested name specifier.
1243 ///
1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1245   // C++0x [basic.lookup.unqual]p13:
1246   //   A name used in the definition of a static data member of class
1247   //   X (after the qualified-id of the static member) is looked up as
1248   //   if the name was used in a member function of X.
1249   // C++0x [basic.lookup.unqual]p14:
1250   //   If a variable member of a namespace is defined outside of the
1251   //   scope of its namespace then any name used in the definition of
1252   //   the variable member (after the declarator-id) is looked up as
1253   //   if the definition of the variable member occurred in its
1254   //   namespace.
1255   // Both of these imply that we should push a scope whose context
1256   // is the semantic context of the declaration.  We can't use
1257   // PushDeclContext here because that context is not necessarily
1258   // lexically contained in the current context.  Fortunately,
1259   // the containing scope should have the appropriate information.
1260 
1261   assert(!S->getEntity() && "scope already has entity");
1262 
1263 #ifndef NDEBUG
1264   Scope *Ancestor = S->getParent();
1265   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1266   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1267 #endif
1268 
1269   CurContext = DC;
1270   S->setEntity(DC);
1271 }
1272 
1273 void Sema::ExitDeclaratorContext(Scope *S) {
1274   assert(S->getEntity() == CurContext && "Context imbalance!");
1275 
1276   // Switch back to the lexical context.  The safety of this is
1277   // enforced by an assert in EnterDeclaratorContext.
1278   Scope *Ancestor = S->getParent();
1279   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1280   CurContext = Ancestor->getEntity();
1281 
1282   // We don't need to do anything with the scope, which is going to
1283   // disappear.
1284 }
1285 
1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1287   // We assume that the caller has already called
1288   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1289   FunctionDecl *FD = D->getAsFunction();
1290   if (!FD)
1291     return;
1292 
1293   // Same implementation as PushDeclContext, but enters the context
1294   // from the lexical parent, rather than the top-level class.
1295   assert(CurContext == FD->getLexicalParent() &&
1296     "The next DeclContext should be lexically contained in the current one.");
1297   CurContext = FD;
1298   S->setEntity(CurContext);
1299 
1300   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1301     ParmVarDecl *Param = FD->getParamDecl(P);
1302     // If the parameter has an identifier, then add it to the scope
1303     if (Param->getIdentifier()) {
1304       S->AddDecl(Param);
1305       IdResolver.AddDecl(Param);
1306     }
1307   }
1308 }
1309 
1310 void Sema::ActOnExitFunctionContext() {
1311   // Same implementation as PopDeclContext, but returns to the lexical parent,
1312   // rather than the top-level class.
1313   assert(CurContext && "DeclContext imbalance!");
1314   CurContext = CurContext->getLexicalParent();
1315   assert(CurContext && "Popped translation unit!");
1316 }
1317 
1318 /// Determine whether we allow overloading of the function
1319 /// PrevDecl with another declaration.
1320 ///
1321 /// This routine determines whether overloading is possible, not
1322 /// whether some new function is actually an overload. It will return
1323 /// true in C++ (where we can always provide overloads) or, as an
1324 /// extension, in C when the previous function is already an
1325 /// overloaded function declaration or has the "overloadable"
1326 /// attribute.
1327 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1328                                        ASTContext &Context,
1329                                        const FunctionDecl *New) {
1330   if (Context.getLangOpts().CPlusPlus)
1331     return true;
1332 
1333   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1334     return true;
1335 
1336   return Previous.getResultKind() == LookupResult::Found &&
1337          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1338           New->hasAttr<OverloadableAttr>());
1339 }
1340 
1341 /// Add this decl to the scope shadowed decl chains.
1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343   // Move up the scope chain until we find the nearest enclosing
1344   // non-transparent context. The declaration will be introduced into this
1345   // scope.
1346   while (S->getEntity() && S->getEntity()->isTransparentContext())
1347     S = S->getParent();
1348 
1349   // Add scoped declarations into their context, so that they can be
1350   // found later. Declarations without a context won't be inserted
1351   // into any context.
1352   if (AddToContext)
1353     CurContext->addDecl(D);
1354 
1355   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356   // are function-local declarations.
1357   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358       !D->getDeclContext()->getRedeclContext()->Equals(
1359         D->getLexicalDeclContext()->getRedeclContext()) &&
1360       !D->getLexicalDeclContext()->isFunctionOrMethod())
1361     return;
1362 
1363   // Template instantiations should also not be pushed into scope.
1364   if (isa<FunctionDecl>(D) &&
1365       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366     return;
1367 
1368   // If this replaces anything in the current scope,
1369   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370                                IEnd = IdResolver.end();
1371   for (; I != IEnd; ++I) {
1372     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373       S->RemoveDecl(*I);
1374       IdResolver.RemoveDecl(*I);
1375 
1376       // Should only need to replace one decl.
1377       break;
1378     }
1379   }
1380 
1381   S->AddDecl(D);
1382 
1383   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384     // Implicitly-generated labels may end up getting generated in an order that
1385     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386     // the label at the appropriate place in the identifier chain.
1387     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389       if (IDC == CurContext) {
1390         if (!S->isDeclScope(*I))
1391           continue;
1392       } else if (IDC->Encloses(CurContext))
1393         break;
1394     }
1395 
1396     IdResolver.InsertDeclAfter(I, D);
1397   } else {
1398     IdResolver.AddDecl(D);
1399   }
1400 }
1401 
1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404     TUScope->AddDecl(D);
1405 }
1406 
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411 
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419 
1420   return nullptr;
1421 }
1422 
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426 
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435 
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438 
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441 
1442     F.erase();
1443   }
1444 
1445   F.done();
1446 }
1447 
1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1449 /// have compatible owning modules.
1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1451   // FIXME: The Modules TS is not clear about how friend declarations are
1452   // to be treated. It's not meaningful to have different owning modules for
1453   // linkage in redeclarations of the same entity, so for now allow the
1454   // redeclaration and change the owning modules to match.
1455   if (New->getFriendObjectKind() &&
1456       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1457     New->setLocalOwningModule(Old->getOwningModule());
1458     makeMergedDefinitionVisible(New);
1459     return false;
1460   }
1461 
1462   Module *NewM = New->getOwningModule();
1463   Module *OldM = Old->getOwningModule();
1464   if (NewM == OldM)
1465     return false;
1466 
1467   // FIXME: Check proclaimed-ownership-declarations here too.
1468   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1469   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1470   if (NewIsModuleInterface || OldIsModuleInterface) {
1471     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1472     //   if a declaration of D [...] appears in the purview of a module, all
1473     //   other such declarations shall appear in the purview of the same module
1474     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1475       << New
1476       << NewIsModuleInterface
1477       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1478       << OldIsModuleInterface
1479       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1480     Diag(Old->getLocation(), diag::note_previous_declaration);
1481     New->setInvalidDecl();
1482     return true;
1483   }
1484 
1485   return false;
1486 }
1487 
1488 static bool isUsingDecl(NamedDecl *D) {
1489   return isa<UsingShadowDecl>(D) ||
1490          isa<UnresolvedUsingTypenameDecl>(D) ||
1491          isa<UnresolvedUsingValueDecl>(D);
1492 }
1493 
1494 /// Removes using shadow declarations from the lookup results.
1495 static void RemoveUsingDecls(LookupResult &R) {
1496   LookupResult::Filter F = R.makeFilter();
1497   while (F.hasNext())
1498     if (isUsingDecl(F.next()))
1499       F.erase();
1500 
1501   F.done();
1502 }
1503 
1504 /// Check for this common pattern:
1505 /// @code
1506 /// class S {
1507 ///   S(const S&); // DO NOT IMPLEMENT
1508 ///   void operator=(const S&); // DO NOT IMPLEMENT
1509 /// };
1510 /// @endcode
1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1512   // FIXME: Should check for private access too but access is set after we get
1513   // the decl here.
1514   if (D->doesThisDeclarationHaveABody())
1515     return false;
1516 
1517   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1518     return CD->isCopyConstructor();
1519   return D->isCopyAssignmentOperator();
1520 }
1521 
1522 // We need this to handle
1523 //
1524 // typedef struct {
1525 //   void *foo() { return 0; }
1526 // } A;
1527 //
1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1529 // for example. If 'A', foo will have external linkage. If we have '*A',
1530 // foo will have no linkage. Since we can't know until we get to the end
1531 // of the typedef, this function finds out if D might have non-external linkage.
1532 // Callers should verify at the end of the TU if it D has external linkage or
1533 // not.
1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1535   const DeclContext *DC = D->getDeclContext();
1536   while (!DC->isTranslationUnit()) {
1537     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1538       if (!RD->hasNameForLinkage())
1539         return true;
1540     }
1541     DC = DC->getParent();
1542   }
1543 
1544   return !D->isExternallyVisible();
1545 }
1546 
1547 // FIXME: This needs to be refactored; some other isInMainFile users want
1548 // these semantics.
1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1550   if (S.TUKind != TU_Complete)
1551     return false;
1552   return S.SourceMgr.isInMainFile(Loc);
1553 }
1554 
1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1556   assert(D);
1557 
1558   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1559     return false;
1560 
1561   // Ignore all entities declared within templates, and out-of-line definitions
1562   // of members of class templates.
1563   if (D->getDeclContext()->isDependentContext() ||
1564       D->getLexicalDeclContext()->isDependentContext())
1565     return false;
1566 
1567   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1568     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1569       return false;
1570     // A non-out-of-line declaration of a member specialization was implicitly
1571     // instantiated; it's the out-of-line declaration that we're interested in.
1572     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1573         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1574       return false;
1575 
1576     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1577       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1578         return false;
1579     } else {
1580       // 'static inline' functions are defined in headers; don't warn.
1581       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1582         return false;
1583     }
1584 
1585     if (FD->doesThisDeclarationHaveABody() &&
1586         Context.DeclMustBeEmitted(FD))
1587       return false;
1588   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1589     // Constants and utility variables are defined in headers with internal
1590     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1591     // like "inline".)
1592     if (!isMainFileLoc(*this, VD->getLocation()))
1593       return false;
1594 
1595     if (Context.DeclMustBeEmitted(VD))
1596       return false;
1597 
1598     if (VD->isStaticDataMember() &&
1599         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1600       return false;
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1603         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1604       return false;
1605 
1606     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1607       return false;
1608   } else {
1609     return false;
1610   }
1611 
1612   // Only warn for unused decls internal to the translation unit.
1613   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1614   // for inline functions defined in the main source file, for instance.
1615   return mightHaveNonExternalLinkage(D);
1616 }
1617 
1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1619   if (!D)
1620     return;
1621 
1622   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1623     const FunctionDecl *First = FD->getFirstDecl();
1624     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1625       return; // First should already be in the vector.
1626   }
1627 
1628   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1629     const VarDecl *First = VD->getFirstDecl();
1630     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1631       return; // First should already be in the vector.
1632   }
1633 
1634   if (ShouldWarnIfUnusedFileScopedDecl(D))
1635     UnusedFileScopedDecls.push_back(D);
1636 }
1637 
1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1639   if (D->isInvalidDecl())
1640     return false;
1641 
1642   bool Referenced = false;
1643   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1644     // For a decomposition declaration, warn if none of the bindings are
1645     // referenced, instead of if the variable itself is referenced (which
1646     // it is, by the bindings' expressions).
1647     for (auto *BD : DD->bindings()) {
1648       if (BD->isReferenced()) {
1649         Referenced = true;
1650         break;
1651       }
1652     }
1653   } else if (!D->getDeclName()) {
1654     return false;
1655   } else if (D->isReferenced() || D->isUsed()) {
1656     Referenced = true;
1657   }
1658 
1659   if (Referenced || D->hasAttr<UnusedAttr>() ||
1660       D->hasAttr<ObjCPreciseLifetimeAttr>())
1661     return false;
1662 
1663   if (isa<LabelDecl>(D))
1664     return true;
1665 
1666   // Except for labels, we only care about unused decls that are local to
1667   // functions.
1668   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1669   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1670     // For dependent types, the diagnostic is deferred.
1671     WithinFunction =
1672         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1673   if (!WithinFunction)
1674     return false;
1675 
1676   if (isa<TypedefNameDecl>(D))
1677     return true;
1678 
1679   // White-list anything that isn't a local variable.
1680   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1681     return false;
1682 
1683   // Types of valid local variables should be complete, so this should succeed.
1684   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1685 
1686     // White-list anything with an __attribute__((unused)) type.
1687     const auto *Ty = VD->getType().getTypePtr();
1688 
1689     // Only look at the outermost level of typedef.
1690     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1691       if (TT->getDecl()->hasAttr<UnusedAttr>())
1692         return false;
1693     }
1694 
1695     // If we failed to complete the type for some reason, or if the type is
1696     // dependent, don't diagnose the variable.
1697     if (Ty->isIncompleteType() || Ty->isDependentType())
1698       return false;
1699 
1700     // Look at the element type to ensure that the warning behaviour is
1701     // consistent for both scalars and arrays.
1702     Ty = Ty->getBaseElementTypeUnsafe();
1703 
1704     if (const TagType *TT = Ty->getAs<TagType>()) {
1705       const TagDecl *Tag = TT->getDecl();
1706       if (Tag->hasAttr<UnusedAttr>())
1707         return false;
1708 
1709       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1710         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1711           return false;
1712 
1713         if (const Expr *Init = VD->getInit()) {
1714           if (const ExprWithCleanups *Cleanups =
1715                   dyn_cast<ExprWithCleanups>(Init))
1716             Init = Cleanups->getSubExpr();
1717           const CXXConstructExpr *Construct =
1718             dyn_cast<CXXConstructExpr>(Init);
1719           if (Construct && !Construct->isElidable()) {
1720             CXXConstructorDecl *CD = Construct->getConstructor();
1721             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1722                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1723               return false;
1724           }
1725         }
1726       }
1727     }
1728 
1729     // TODO: __attribute__((unused)) templates?
1730   }
1731 
1732   return true;
1733 }
1734 
1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1736                                      FixItHint &Hint) {
1737   if (isa<LabelDecl>(D)) {
1738     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1739         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1740         true);
1741     if (AfterColon.isInvalid())
1742       return;
1743     Hint = FixItHint::CreateRemoval(
1744         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1745   }
1746 }
1747 
1748 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1749   if (D->getTypeForDecl()->isDependentType())
1750     return;
1751 
1752   for (auto *TmpD : D->decls()) {
1753     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1754       DiagnoseUnusedDecl(T);
1755     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1756       DiagnoseUnusedNestedTypedefs(R);
1757   }
1758 }
1759 
1760 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1761 /// unless they are marked attr(unused).
1762 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1763   if (!ShouldDiagnoseUnusedDecl(D))
1764     return;
1765 
1766   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1767     // typedefs can be referenced later on, so the diagnostics are emitted
1768     // at end-of-translation-unit.
1769     UnusedLocalTypedefNameCandidates.insert(TD);
1770     return;
1771   }
1772 
1773   FixItHint Hint;
1774   GenerateFixForUnusedDecl(D, Context, Hint);
1775 
1776   unsigned DiagID;
1777   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1778     DiagID = diag::warn_unused_exception_param;
1779   else if (isa<LabelDecl>(D))
1780     DiagID = diag::warn_unused_label;
1781   else
1782     DiagID = diag::warn_unused_variable;
1783 
1784   Diag(D->getLocation(), DiagID) << D << Hint;
1785 }
1786 
1787 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1788   // Verify that we have no forward references left.  If so, there was a goto
1789   // or address of a label taken, but no definition of it.  Label fwd
1790   // definitions are indicated with a null substmt which is also not a resolved
1791   // MS inline assembly label name.
1792   bool Diagnose = false;
1793   if (L->isMSAsmLabel())
1794     Diagnose = !L->isResolvedMSAsmLabel();
1795   else
1796     Diagnose = L->getStmt() == nullptr;
1797   if (Diagnose)
1798     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1799 }
1800 
1801 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1802   S->mergeNRVOIntoParent();
1803 
1804   if (S->decl_empty()) return;
1805   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1806          "Scope shouldn't contain decls!");
1807 
1808   for (auto *TmpD : S->decls()) {
1809     assert(TmpD && "This decl didn't get pushed??");
1810 
1811     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1812     NamedDecl *D = cast<NamedDecl>(TmpD);
1813 
1814     // Diagnose unused variables in this scope.
1815     if (!S->hasUnrecoverableErrorOccurred()) {
1816       DiagnoseUnusedDecl(D);
1817       if (const auto *RD = dyn_cast<RecordDecl>(D))
1818         DiagnoseUnusedNestedTypedefs(RD);
1819     }
1820 
1821     if (!D->getDeclName()) continue;
1822 
1823     // If this was a forward reference to a label, verify it was defined.
1824     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1825       CheckPoppedLabel(LD, *this);
1826 
1827     // Remove this name from our lexical scope, and warn on it if we haven't
1828     // already.
1829     IdResolver.RemoveDecl(D);
1830     auto ShadowI = ShadowingDecls.find(D);
1831     if (ShadowI != ShadowingDecls.end()) {
1832       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1833         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1834             << D << FD << FD->getParent();
1835         Diag(FD->getLocation(), diag::note_previous_declaration);
1836       }
1837       ShadowingDecls.erase(ShadowI);
1838     }
1839   }
1840 }
1841 
1842 /// Look for an Objective-C class in the translation unit.
1843 ///
1844 /// \param Id The name of the Objective-C class we're looking for. If
1845 /// typo-correction fixes this name, the Id will be updated
1846 /// to the fixed name.
1847 ///
1848 /// \param IdLoc The location of the name in the translation unit.
1849 ///
1850 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1851 /// if there is no class with the given name.
1852 ///
1853 /// \returns The declaration of the named Objective-C class, or NULL if the
1854 /// class could not be found.
1855 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1856                                               SourceLocation IdLoc,
1857                                               bool DoTypoCorrection) {
1858   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1859   // creation from this context.
1860   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1861 
1862   if (!IDecl && DoTypoCorrection) {
1863     // Perform typo correction at the given location, but only if we
1864     // find an Objective-C class name.
1865     if (TypoCorrection C = CorrectTypo(
1866             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1867             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1868             CTK_ErrorRecovery)) {
1869       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1870       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1871       Id = IDecl->getIdentifier();
1872     }
1873   }
1874   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1875   // This routine must always return a class definition, if any.
1876   if (Def && Def->getDefinition())
1877       Def = Def->getDefinition();
1878   return Def;
1879 }
1880 
1881 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1882 /// from S, where a non-field would be declared. This routine copes
1883 /// with the difference between C and C++ scoping rules in structs and
1884 /// unions. For example, the following code is well-formed in C but
1885 /// ill-formed in C++:
1886 /// @code
1887 /// struct S6 {
1888 ///   enum { BAR } e;
1889 /// };
1890 ///
1891 /// void test_S6() {
1892 ///   struct S6 a;
1893 ///   a.e = BAR;
1894 /// }
1895 /// @endcode
1896 /// For the declaration of BAR, this routine will return a different
1897 /// scope. The scope S will be the scope of the unnamed enumeration
1898 /// within S6. In C++, this routine will return the scope associated
1899 /// with S6, because the enumeration's scope is a transparent
1900 /// context but structures can contain non-field names. In C, this
1901 /// routine will return the translation unit scope, since the
1902 /// enumeration's scope is a transparent context and structures cannot
1903 /// contain non-field names.
1904 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1905   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1906          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1907          (S->isClassScope() && !getLangOpts().CPlusPlus))
1908     S = S->getParent();
1909   return S;
1910 }
1911 
1912 /// Looks up the declaration of "struct objc_super" and
1913 /// saves it for later use in building builtin declaration of
1914 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1915 /// pre-existing declaration exists no action takes place.
1916 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1917                                         IdentifierInfo *II) {
1918   if (!II->isStr("objc_msgSendSuper"))
1919     return;
1920   ASTContext &Context = ThisSema.Context;
1921 
1922   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1923                       SourceLocation(), Sema::LookupTagName);
1924   ThisSema.LookupName(Result, S);
1925   if (Result.getResultKind() == LookupResult::Found)
1926     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1927       Context.setObjCSuperType(Context.getTagDeclType(TD));
1928 }
1929 
1930 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1931   switch (Error) {
1932   case ASTContext::GE_None:
1933     return "";
1934   case ASTContext::GE_Missing_stdio:
1935     return "stdio.h";
1936   case ASTContext::GE_Missing_setjmp:
1937     return "setjmp.h";
1938   case ASTContext::GE_Missing_ucontext:
1939     return "ucontext.h";
1940   }
1941   llvm_unreachable("unhandled error kind");
1942 }
1943 
1944 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1945 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1946 /// if we're creating this built-in in anticipation of redeclaring the
1947 /// built-in.
1948 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1949                                      Scope *S, bool ForRedeclaration,
1950                                      SourceLocation Loc) {
1951   LookupPredefedObjCSuperType(*this, S, II);
1952 
1953   ASTContext::GetBuiltinTypeError Error;
1954   QualType R = Context.GetBuiltinType(ID, Error);
1955   if (Error) {
1956     if (ForRedeclaration)
1957       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1958           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1959     return nullptr;
1960   }
1961 
1962   if (!ForRedeclaration &&
1963       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1964        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1965     Diag(Loc, diag::ext_implicit_lib_function_decl)
1966         << Context.BuiltinInfo.getName(ID) << R;
1967     if (Context.BuiltinInfo.getHeaderName(ID) &&
1968         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1969       Diag(Loc, diag::note_include_header_or_declare)
1970           << Context.BuiltinInfo.getHeaderName(ID)
1971           << Context.BuiltinInfo.getName(ID);
1972   }
1973 
1974   if (R.isNull())
1975     return nullptr;
1976 
1977   DeclContext *Parent = Context.getTranslationUnitDecl();
1978   if (getLangOpts().CPlusPlus) {
1979     LinkageSpecDecl *CLinkageDecl =
1980         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1981                                 LinkageSpecDecl::lang_c, false);
1982     CLinkageDecl->setImplicit();
1983     Parent->addDecl(CLinkageDecl);
1984     Parent = CLinkageDecl;
1985   }
1986 
1987   FunctionDecl *New = FunctionDecl::Create(Context,
1988                                            Parent,
1989                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1990                                            SC_Extern,
1991                                            false,
1992                                            R->isFunctionProtoType());
1993   New->setImplicit();
1994 
1995   // Create Decl objects for each parameter, adding them to the
1996   // FunctionDecl.
1997   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1998     SmallVector<ParmVarDecl*, 16> Params;
1999     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2000       ParmVarDecl *parm =
2001           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2002                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2003                               SC_None, nullptr);
2004       parm->setScopeInfo(0, i);
2005       Params.push_back(parm);
2006     }
2007     New->setParams(Params);
2008   }
2009 
2010   AddKnownFunctionAttributes(New);
2011   RegisterLocallyScopedExternCDecl(New, S);
2012 
2013   // TUScope is the translation-unit scope to insert this function into.
2014   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2015   // relate Scopes to DeclContexts, and probably eliminate CurContext
2016   // entirely, but we're not there yet.
2017   DeclContext *SavedContext = CurContext;
2018   CurContext = Parent;
2019   PushOnScopeChains(New, TUScope);
2020   CurContext = SavedContext;
2021   return New;
2022 }
2023 
2024 /// Typedef declarations don't have linkage, but they still denote the same
2025 /// entity if their types are the same.
2026 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2027 /// isSameEntity.
2028 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2029                                                      TypedefNameDecl *Decl,
2030                                                      LookupResult &Previous) {
2031   // This is only interesting when modules are enabled.
2032   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2033     return;
2034 
2035   // Empty sets are uninteresting.
2036   if (Previous.empty())
2037     return;
2038 
2039   LookupResult::Filter Filter = Previous.makeFilter();
2040   while (Filter.hasNext()) {
2041     NamedDecl *Old = Filter.next();
2042 
2043     // Non-hidden declarations are never ignored.
2044     if (S.isVisible(Old))
2045       continue;
2046 
2047     // Declarations of the same entity are not ignored, even if they have
2048     // different linkages.
2049     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2050       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2051                                 Decl->getUnderlyingType()))
2052         continue;
2053 
2054       // If both declarations give a tag declaration a typedef name for linkage
2055       // purposes, then they declare the same entity.
2056       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2057           Decl->getAnonDeclWithTypedefName())
2058         continue;
2059     }
2060 
2061     Filter.erase();
2062   }
2063 
2064   Filter.done();
2065 }
2066 
2067 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2068   QualType OldType;
2069   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2070     OldType = OldTypedef->getUnderlyingType();
2071   else
2072     OldType = Context.getTypeDeclType(Old);
2073   QualType NewType = New->getUnderlyingType();
2074 
2075   if (NewType->isVariablyModifiedType()) {
2076     // Must not redefine a typedef with a variably-modified type.
2077     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2078     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2079       << Kind << NewType;
2080     if (Old->getLocation().isValid())
2081       notePreviousDefinition(Old, New->getLocation());
2082     New->setInvalidDecl();
2083     return true;
2084   }
2085 
2086   if (OldType != NewType &&
2087       !OldType->isDependentType() &&
2088       !NewType->isDependentType() &&
2089       !Context.hasSameType(OldType, NewType)) {
2090     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2091     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2092       << Kind << NewType << OldType;
2093     if (Old->getLocation().isValid())
2094       notePreviousDefinition(Old, New->getLocation());
2095     New->setInvalidDecl();
2096     return true;
2097   }
2098   return false;
2099 }
2100 
2101 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2102 /// same name and scope as a previous declaration 'Old'.  Figure out
2103 /// how to resolve this situation, merging decls or emitting
2104 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2105 ///
2106 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2107                                 LookupResult &OldDecls) {
2108   // If the new decl is known invalid already, don't bother doing any
2109   // merging checks.
2110   if (New->isInvalidDecl()) return;
2111 
2112   // Allow multiple definitions for ObjC built-in typedefs.
2113   // FIXME: Verify the underlying types are equivalent!
2114   if (getLangOpts().ObjC1) {
2115     const IdentifierInfo *TypeID = New->getIdentifier();
2116     switch (TypeID->getLength()) {
2117     default: break;
2118     case 2:
2119       {
2120         if (!TypeID->isStr("id"))
2121           break;
2122         QualType T = New->getUnderlyingType();
2123         if (!T->isPointerType())
2124           break;
2125         if (!T->isVoidPointerType()) {
2126           QualType PT = T->getAs<PointerType>()->getPointeeType();
2127           if (!PT->isStructureType())
2128             break;
2129         }
2130         Context.setObjCIdRedefinitionType(T);
2131         // Install the built-in type for 'id', ignoring the current definition.
2132         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2133         return;
2134       }
2135     case 5:
2136       if (!TypeID->isStr("Class"))
2137         break;
2138       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2139       // Install the built-in type for 'Class', ignoring the current definition.
2140       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2141       return;
2142     case 3:
2143       if (!TypeID->isStr("SEL"))
2144         break;
2145       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2146       // Install the built-in type for 'SEL', ignoring the current definition.
2147       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2148       return;
2149     }
2150     // Fall through - the typedef name was not a builtin type.
2151   }
2152 
2153   // Verify the old decl was also a type.
2154   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2155   if (!Old) {
2156     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2157       << New->getDeclName();
2158 
2159     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2160     if (OldD->getLocation().isValid())
2161       notePreviousDefinition(OldD, New->getLocation());
2162 
2163     return New->setInvalidDecl();
2164   }
2165 
2166   // If the old declaration is invalid, just give up here.
2167   if (Old->isInvalidDecl())
2168     return New->setInvalidDecl();
2169 
2170   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2171     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2172     auto *NewTag = New->getAnonDeclWithTypedefName();
2173     NamedDecl *Hidden = nullptr;
2174     if (OldTag && NewTag &&
2175         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2176         !hasVisibleDefinition(OldTag, &Hidden)) {
2177       // There is a definition of this tag, but it is not visible. Use it
2178       // instead of our tag.
2179       New->setTypeForDecl(OldTD->getTypeForDecl());
2180       if (OldTD->isModed())
2181         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2182                                     OldTD->getUnderlyingType());
2183       else
2184         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2185 
2186       // Make the old tag definition visible.
2187       makeMergedDefinitionVisible(Hidden);
2188 
2189       // If this was an unscoped enumeration, yank all of its enumerators
2190       // out of the scope.
2191       if (isa<EnumDecl>(NewTag)) {
2192         Scope *EnumScope = getNonFieldDeclScope(S);
2193         for (auto *D : NewTag->decls()) {
2194           auto *ED = cast<EnumConstantDecl>(D);
2195           assert(EnumScope->isDeclScope(ED));
2196           EnumScope->RemoveDecl(ED);
2197           IdResolver.RemoveDecl(ED);
2198           ED->getLexicalDeclContext()->removeDecl(ED);
2199         }
2200       }
2201     }
2202   }
2203 
2204   // If the typedef types are not identical, reject them in all languages and
2205   // with any extensions enabled.
2206   if (isIncompatibleTypedef(Old, New))
2207     return;
2208 
2209   // The types match.  Link up the redeclaration chain and merge attributes if
2210   // the old declaration was a typedef.
2211   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2212     New->setPreviousDecl(Typedef);
2213     mergeDeclAttributes(New, Old);
2214   }
2215 
2216   if (getLangOpts().MicrosoftExt)
2217     return;
2218 
2219   if (getLangOpts().CPlusPlus) {
2220     // C++ [dcl.typedef]p2:
2221     //   In a given non-class scope, a typedef specifier can be used to
2222     //   redefine the name of any type declared in that scope to refer
2223     //   to the type to which it already refers.
2224     if (!isa<CXXRecordDecl>(CurContext))
2225       return;
2226 
2227     // C++0x [dcl.typedef]p4:
2228     //   In a given class scope, a typedef specifier can be used to redefine
2229     //   any class-name declared in that scope that is not also a typedef-name
2230     //   to refer to the type to which it already refers.
2231     //
2232     // This wording came in via DR424, which was a correction to the
2233     // wording in DR56, which accidentally banned code like:
2234     //
2235     //   struct S {
2236     //     typedef struct A { } A;
2237     //   };
2238     //
2239     // in the C++03 standard. We implement the C++0x semantics, which
2240     // allow the above but disallow
2241     //
2242     //   struct S {
2243     //     typedef int I;
2244     //     typedef int I;
2245     //   };
2246     //
2247     // since that was the intent of DR56.
2248     if (!isa<TypedefNameDecl>(Old))
2249       return;
2250 
2251     Diag(New->getLocation(), diag::err_redefinition)
2252       << New->getDeclName();
2253     notePreviousDefinition(Old, New->getLocation());
2254     return New->setInvalidDecl();
2255   }
2256 
2257   // Modules always permit redefinition of typedefs, as does C11.
2258   if (getLangOpts().Modules || getLangOpts().C11)
2259     return;
2260 
2261   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2262   // is normally mapped to an error, but can be controlled with
2263   // -Wtypedef-redefinition.  If either the original or the redefinition is
2264   // in a system header, don't emit this for compatibility with GCC.
2265   if (getDiagnostics().getSuppressSystemWarnings() &&
2266       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2267       (Old->isImplicit() ||
2268        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2269        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2270     return;
2271 
2272   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2273     << New->getDeclName();
2274   notePreviousDefinition(Old, New->getLocation());
2275 }
2276 
2277 /// DeclhasAttr - returns true if decl Declaration already has the target
2278 /// attribute.
2279 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2280   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2281   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2282   for (const auto *i : D->attrs())
2283     if (i->getKind() == A->getKind()) {
2284       if (Ann) {
2285         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2286           return true;
2287         continue;
2288       }
2289       // FIXME: Don't hardcode this check
2290       if (OA && isa<OwnershipAttr>(i))
2291         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2292       return true;
2293     }
2294 
2295   return false;
2296 }
2297 
2298 static bool isAttributeTargetADefinition(Decl *D) {
2299   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2300     return VD->isThisDeclarationADefinition();
2301   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2302     return TD->isCompleteDefinition() || TD->isBeingDefined();
2303   return true;
2304 }
2305 
2306 /// Merge alignment attributes from \p Old to \p New, taking into account the
2307 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2308 ///
2309 /// \return \c true if any attributes were added to \p New.
2310 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2311   // Look for alignas attributes on Old, and pick out whichever attribute
2312   // specifies the strictest alignment requirement.
2313   AlignedAttr *OldAlignasAttr = nullptr;
2314   AlignedAttr *OldStrictestAlignAttr = nullptr;
2315   unsigned OldAlign = 0;
2316   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2317     // FIXME: We have no way of representing inherited dependent alignments
2318     // in a case like:
2319     //   template<int A, int B> struct alignas(A) X;
2320     //   template<int A, int B> struct alignas(B) X {};
2321     // For now, we just ignore any alignas attributes which are not on the
2322     // definition in such a case.
2323     if (I->isAlignmentDependent())
2324       return false;
2325 
2326     if (I->isAlignas())
2327       OldAlignasAttr = I;
2328 
2329     unsigned Align = I->getAlignment(S.Context);
2330     if (Align > OldAlign) {
2331       OldAlign = Align;
2332       OldStrictestAlignAttr = I;
2333     }
2334   }
2335 
2336   // Look for alignas attributes on New.
2337   AlignedAttr *NewAlignasAttr = nullptr;
2338   unsigned NewAlign = 0;
2339   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2340     if (I->isAlignmentDependent())
2341       return false;
2342 
2343     if (I->isAlignas())
2344       NewAlignasAttr = I;
2345 
2346     unsigned Align = I->getAlignment(S.Context);
2347     if (Align > NewAlign)
2348       NewAlign = Align;
2349   }
2350 
2351   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2352     // Both declarations have 'alignas' attributes. We require them to match.
2353     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2354     // fall short. (If two declarations both have alignas, they must both match
2355     // every definition, and so must match each other if there is a definition.)
2356 
2357     // If either declaration only contains 'alignas(0)' specifiers, then it
2358     // specifies the natural alignment for the type.
2359     if (OldAlign == 0 || NewAlign == 0) {
2360       QualType Ty;
2361       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2362         Ty = VD->getType();
2363       else
2364         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2365 
2366       if (OldAlign == 0)
2367         OldAlign = S.Context.getTypeAlign(Ty);
2368       if (NewAlign == 0)
2369         NewAlign = S.Context.getTypeAlign(Ty);
2370     }
2371 
2372     if (OldAlign != NewAlign) {
2373       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2374         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2375         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2376       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2377     }
2378   }
2379 
2380   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2381     // C++11 [dcl.align]p6:
2382     //   if any declaration of an entity has an alignment-specifier,
2383     //   every defining declaration of that entity shall specify an
2384     //   equivalent alignment.
2385     // C11 6.7.5/7:
2386     //   If the definition of an object does not have an alignment
2387     //   specifier, any other declaration of that object shall also
2388     //   have no alignment specifier.
2389     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2390       << OldAlignasAttr;
2391     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2392       << OldAlignasAttr;
2393   }
2394 
2395   bool AnyAdded = false;
2396 
2397   // Ensure we have an attribute representing the strictest alignment.
2398   if (OldAlign > NewAlign) {
2399     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2400     Clone->setInherited(true);
2401     New->addAttr(Clone);
2402     AnyAdded = true;
2403   }
2404 
2405   // Ensure we have an alignas attribute if the old declaration had one.
2406   if (OldAlignasAttr && !NewAlignasAttr &&
2407       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2408     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2409     Clone->setInherited(true);
2410     New->addAttr(Clone);
2411     AnyAdded = true;
2412   }
2413 
2414   return AnyAdded;
2415 }
2416 
2417 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2418                                const InheritableAttr *Attr,
2419                                Sema::AvailabilityMergeKind AMK) {
2420   // This function copies an attribute Attr from a previous declaration to the
2421   // new declaration D if the new declaration doesn't itself have that attribute
2422   // yet or if that attribute allows duplicates.
2423   // If you're adding a new attribute that requires logic different from
2424   // "use explicit attribute on decl if present, else use attribute from
2425   // previous decl", for example if the attribute needs to be consistent
2426   // between redeclarations, you need to call a custom merge function here.
2427   InheritableAttr *NewAttr = nullptr;
2428   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2429   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2430     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2431                                       AA->isImplicit(), AA->getIntroduced(),
2432                                       AA->getDeprecated(),
2433                                       AA->getObsoleted(), AA->getUnavailable(),
2434                                       AA->getMessage(), AA->getStrict(),
2435                                       AA->getReplacement(), AMK,
2436                                       AttrSpellingListIndex);
2437   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2438     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2439                                     AttrSpellingListIndex);
2440   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2441     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2442                                         AttrSpellingListIndex);
2443   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2444     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2445                                    AttrSpellingListIndex);
2446   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2447     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2448                                    AttrSpellingListIndex);
2449   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2450     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2451                                 FA->getFormatIdx(), FA->getFirstArg(),
2452                                 AttrSpellingListIndex);
2453   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2454     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2455                                  AttrSpellingListIndex);
2456   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2457     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2458                                  AttrSpellingListIndex);
2459   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2460     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2461                                        AttrSpellingListIndex,
2462                                        IA->getSemanticSpelling());
2463   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2464     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2465                                       &S.Context.Idents.get(AA->getSpelling()),
2466                                       AttrSpellingListIndex);
2467   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2468            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2469             isa<CUDAGlobalAttr>(Attr))) {
2470     // CUDA target attributes are part of function signature for
2471     // overloading purposes and must not be merged.
2472     return false;
2473   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2474     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2475   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2476     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2477   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2478     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2479   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2480     NewAttr = S.mergeCommonAttr(D, *CommonA);
2481   else if (isa<AlignedAttr>(Attr))
2482     // AlignedAttrs are handled separately, because we need to handle all
2483     // such attributes on a declaration at the same time.
2484     NewAttr = nullptr;
2485   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2486            (AMK == Sema::AMK_Override ||
2487             AMK == Sema::AMK_ProtocolImplementation))
2488     NewAttr = nullptr;
2489   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2490     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2491                               UA->getGuid());
2492   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2493     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2494 
2495   if (NewAttr) {
2496     NewAttr->setInherited(true);
2497     D->addAttr(NewAttr);
2498     if (isa<MSInheritanceAttr>(NewAttr))
2499       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2500     return true;
2501   }
2502 
2503   return false;
2504 }
2505 
2506 static const NamedDecl *getDefinition(const Decl *D) {
2507   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2508     return TD->getDefinition();
2509   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2510     const VarDecl *Def = VD->getDefinition();
2511     if (Def)
2512       return Def;
2513     return VD->getActingDefinition();
2514   }
2515   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2516     return FD->getDefinition();
2517   return nullptr;
2518 }
2519 
2520 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2521   for (const auto *Attribute : D->attrs())
2522     if (Attribute->getKind() == Kind)
2523       return true;
2524   return false;
2525 }
2526 
2527 /// checkNewAttributesAfterDef - If we already have a definition, check that
2528 /// there are no new attributes in this declaration.
2529 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2530   if (!New->hasAttrs())
2531     return;
2532 
2533   const NamedDecl *Def = getDefinition(Old);
2534   if (!Def || Def == New)
2535     return;
2536 
2537   AttrVec &NewAttributes = New->getAttrs();
2538   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2539     const Attr *NewAttribute = NewAttributes[I];
2540 
2541     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2542       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2543         Sema::SkipBodyInfo SkipBody;
2544         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2545 
2546         // If we're skipping this definition, drop the "alias" attribute.
2547         if (SkipBody.ShouldSkip) {
2548           NewAttributes.erase(NewAttributes.begin() + I);
2549           --E;
2550           continue;
2551         }
2552       } else {
2553         VarDecl *VD = cast<VarDecl>(New);
2554         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2555                                 VarDecl::TentativeDefinition
2556                             ? diag::err_alias_after_tentative
2557                             : diag::err_redefinition;
2558         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2559         if (Diag == diag::err_redefinition)
2560           S.notePreviousDefinition(Def, VD->getLocation());
2561         else
2562           S.Diag(Def->getLocation(), diag::note_previous_definition);
2563         VD->setInvalidDecl();
2564       }
2565       ++I;
2566       continue;
2567     }
2568 
2569     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2570       // Tentative definitions are only interesting for the alias check above.
2571       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2572         ++I;
2573         continue;
2574       }
2575     }
2576 
2577     if (hasAttribute(Def, NewAttribute->getKind())) {
2578       ++I;
2579       continue; // regular attr merging will take care of validating this.
2580     }
2581 
2582     if (isa<C11NoReturnAttr>(NewAttribute)) {
2583       // C's _Noreturn is allowed to be added to a function after it is defined.
2584       ++I;
2585       continue;
2586     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2587       if (AA->isAlignas()) {
2588         // C++11 [dcl.align]p6:
2589         //   if any declaration of an entity has an alignment-specifier,
2590         //   every defining declaration of that entity shall specify an
2591         //   equivalent alignment.
2592         // C11 6.7.5/7:
2593         //   If the definition of an object does not have an alignment
2594         //   specifier, any other declaration of that object shall also
2595         //   have no alignment specifier.
2596         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2597           << AA;
2598         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2599           << AA;
2600         NewAttributes.erase(NewAttributes.begin() + I);
2601         --E;
2602         continue;
2603       }
2604     }
2605 
2606     S.Diag(NewAttribute->getLocation(),
2607            diag::warn_attribute_precede_definition);
2608     S.Diag(Def->getLocation(), diag::note_previous_definition);
2609     NewAttributes.erase(NewAttributes.begin() + I);
2610     --E;
2611   }
2612 }
2613 
2614 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2615 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2616                                AvailabilityMergeKind AMK) {
2617   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2618     UsedAttr *NewAttr = OldAttr->clone(Context);
2619     NewAttr->setInherited(true);
2620     New->addAttr(NewAttr);
2621   }
2622 
2623   if (!Old->hasAttrs() && !New->hasAttrs())
2624     return;
2625 
2626   // Attributes declared post-definition are currently ignored.
2627   checkNewAttributesAfterDef(*this, New, Old);
2628 
2629   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2630     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2631       if (OldA->getLabel() != NewA->getLabel()) {
2632         // This redeclaration changes __asm__ label.
2633         Diag(New->getLocation(), diag::err_different_asm_label);
2634         Diag(OldA->getLocation(), diag::note_previous_declaration);
2635       }
2636     } else if (Old->isUsed()) {
2637       // This redeclaration adds an __asm__ label to a declaration that has
2638       // already been ODR-used.
2639       Diag(New->getLocation(), diag::err_late_asm_label_name)
2640         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2641     }
2642   }
2643 
2644   // Re-declaration cannot add abi_tag's.
2645   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2646     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2647       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2648         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2649                       NewTag) == OldAbiTagAttr->tags_end()) {
2650           Diag(NewAbiTagAttr->getLocation(),
2651                diag::err_new_abi_tag_on_redeclaration)
2652               << NewTag;
2653           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2654         }
2655       }
2656     } else {
2657       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2658       Diag(Old->getLocation(), diag::note_previous_declaration);
2659     }
2660   }
2661 
2662   // This redeclaration adds a section attribute.
2663   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2664     if (auto *VD = dyn_cast<VarDecl>(New)) {
2665       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2666         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2667         Diag(Old->getLocation(), diag::note_previous_declaration);
2668       }
2669     }
2670   }
2671 
2672   // Redeclaration adds code-seg attribute.
2673   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2674   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2675       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2676     Diag(New->getLocation(), diag::warn_mismatched_section)
2677          << 0 /*codeseg*/;
2678     Diag(Old->getLocation(), diag::note_previous_declaration);
2679   }
2680 
2681   if (!Old->hasAttrs())
2682     return;
2683 
2684   bool foundAny = New->hasAttrs();
2685 
2686   // Ensure that any moving of objects within the allocated map is done before
2687   // we process them.
2688   if (!foundAny) New->setAttrs(AttrVec());
2689 
2690   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2691     // Ignore deprecated/unavailable/availability attributes if requested.
2692     AvailabilityMergeKind LocalAMK = AMK_None;
2693     if (isa<DeprecatedAttr>(I) ||
2694         isa<UnavailableAttr>(I) ||
2695         isa<AvailabilityAttr>(I)) {
2696       switch (AMK) {
2697       case AMK_None:
2698         continue;
2699 
2700       case AMK_Redeclaration:
2701       case AMK_Override:
2702       case AMK_ProtocolImplementation:
2703         LocalAMK = AMK;
2704         break;
2705       }
2706     }
2707 
2708     // Already handled.
2709     if (isa<UsedAttr>(I))
2710       continue;
2711 
2712     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2713       foundAny = true;
2714   }
2715 
2716   if (mergeAlignedAttrs(*this, New, Old))
2717     foundAny = true;
2718 
2719   if (!foundAny) New->dropAttrs();
2720 }
2721 
2722 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2723 /// to the new one.
2724 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2725                                      const ParmVarDecl *oldDecl,
2726                                      Sema &S) {
2727   // C++11 [dcl.attr.depend]p2:
2728   //   The first declaration of a function shall specify the
2729   //   carries_dependency attribute for its declarator-id if any declaration
2730   //   of the function specifies the carries_dependency attribute.
2731   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2732   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2733     S.Diag(CDA->getLocation(),
2734            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2735     // Find the first declaration of the parameter.
2736     // FIXME: Should we build redeclaration chains for function parameters?
2737     const FunctionDecl *FirstFD =
2738       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2739     const ParmVarDecl *FirstVD =
2740       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2741     S.Diag(FirstVD->getLocation(),
2742            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2743   }
2744 
2745   if (!oldDecl->hasAttrs())
2746     return;
2747 
2748   bool foundAny = newDecl->hasAttrs();
2749 
2750   // Ensure that any moving of objects within the allocated map is
2751   // done before we process them.
2752   if (!foundAny) newDecl->setAttrs(AttrVec());
2753 
2754   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2755     if (!DeclHasAttr(newDecl, I)) {
2756       InheritableAttr *newAttr =
2757         cast<InheritableParamAttr>(I->clone(S.Context));
2758       newAttr->setInherited(true);
2759       newDecl->addAttr(newAttr);
2760       foundAny = true;
2761     }
2762   }
2763 
2764   if (!foundAny) newDecl->dropAttrs();
2765 }
2766 
2767 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2768                                 const ParmVarDecl *OldParam,
2769                                 Sema &S) {
2770   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2771     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2772       if (*Oldnullability != *Newnullability) {
2773         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2774           << DiagNullabilityKind(
2775                *Newnullability,
2776                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2777                 != 0))
2778           << DiagNullabilityKind(
2779                *Oldnullability,
2780                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2781                 != 0));
2782         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2783       }
2784     } else {
2785       QualType NewT = NewParam->getType();
2786       NewT = S.Context.getAttributedType(
2787                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2788                          NewT, NewT);
2789       NewParam->setType(NewT);
2790     }
2791   }
2792 }
2793 
2794 namespace {
2795 
2796 /// Used in MergeFunctionDecl to keep track of function parameters in
2797 /// C.
2798 struct GNUCompatibleParamWarning {
2799   ParmVarDecl *OldParm;
2800   ParmVarDecl *NewParm;
2801   QualType PromotedType;
2802 };
2803 
2804 } // end anonymous namespace
2805 
2806 /// getSpecialMember - get the special member enum for a method.
2807 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2808   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2809     if (Ctor->isDefaultConstructor())
2810       return Sema::CXXDefaultConstructor;
2811 
2812     if (Ctor->isCopyConstructor())
2813       return Sema::CXXCopyConstructor;
2814 
2815     if (Ctor->isMoveConstructor())
2816       return Sema::CXXMoveConstructor;
2817   } else if (isa<CXXDestructorDecl>(MD)) {
2818     return Sema::CXXDestructor;
2819   } else if (MD->isCopyAssignmentOperator()) {
2820     return Sema::CXXCopyAssignment;
2821   } else if (MD->isMoveAssignmentOperator()) {
2822     return Sema::CXXMoveAssignment;
2823   }
2824 
2825   return Sema::CXXInvalid;
2826 }
2827 
2828 // Determine whether the previous declaration was a definition, implicit
2829 // declaration, or a declaration.
2830 template <typename T>
2831 static std::pair<diag::kind, SourceLocation>
2832 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2833   diag::kind PrevDiag;
2834   SourceLocation OldLocation = Old->getLocation();
2835   if (Old->isThisDeclarationADefinition())
2836     PrevDiag = diag::note_previous_definition;
2837   else if (Old->isImplicit()) {
2838     PrevDiag = diag::note_previous_implicit_declaration;
2839     if (OldLocation.isInvalid())
2840       OldLocation = New->getLocation();
2841   } else
2842     PrevDiag = diag::note_previous_declaration;
2843   return std::make_pair(PrevDiag, OldLocation);
2844 }
2845 
2846 /// canRedefineFunction - checks if a function can be redefined. Currently,
2847 /// only extern inline functions can be redefined, and even then only in
2848 /// GNU89 mode.
2849 static bool canRedefineFunction(const FunctionDecl *FD,
2850                                 const LangOptions& LangOpts) {
2851   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2852           !LangOpts.CPlusPlus &&
2853           FD->isInlineSpecified() &&
2854           FD->getStorageClass() == SC_Extern);
2855 }
2856 
2857 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2858   const AttributedType *AT = T->getAs<AttributedType>();
2859   while (AT && !AT->isCallingConv())
2860     AT = AT->getModifiedType()->getAs<AttributedType>();
2861   return AT;
2862 }
2863 
2864 template <typename T>
2865 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2866   const DeclContext *DC = Old->getDeclContext();
2867   if (DC->isRecord())
2868     return false;
2869 
2870   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2871   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2872     return true;
2873   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2874     return true;
2875   return false;
2876 }
2877 
2878 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2879 static bool isExternC(VarTemplateDecl *) { return false; }
2880 
2881 /// Check whether a redeclaration of an entity introduced by a
2882 /// using-declaration is valid, given that we know it's not an overload
2883 /// (nor a hidden tag declaration).
2884 template<typename ExpectedDecl>
2885 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2886                                    ExpectedDecl *New) {
2887   // C++11 [basic.scope.declarative]p4:
2888   //   Given a set of declarations in a single declarative region, each of
2889   //   which specifies the same unqualified name,
2890   //   -- they shall all refer to the same entity, or all refer to functions
2891   //      and function templates; or
2892   //   -- exactly one declaration shall declare a class name or enumeration
2893   //      name that is not a typedef name and the other declarations shall all
2894   //      refer to the same variable or enumerator, or all refer to functions
2895   //      and function templates; in this case the class name or enumeration
2896   //      name is hidden (3.3.10).
2897 
2898   // C++11 [namespace.udecl]p14:
2899   //   If a function declaration in namespace scope or block scope has the
2900   //   same name and the same parameter-type-list as a function introduced
2901   //   by a using-declaration, and the declarations do not declare the same
2902   //   function, the program is ill-formed.
2903 
2904   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2905   if (Old &&
2906       !Old->getDeclContext()->getRedeclContext()->Equals(
2907           New->getDeclContext()->getRedeclContext()) &&
2908       !(isExternC(Old) && isExternC(New)))
2909     Old = nullptr;
2910 
2911   if (!Old) {
2912     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2913     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2914     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2915     return true;
2916   }
2917   return false;
2918 }
2919 
2920 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2921                                             const FunctionDecl *B) {
2922   assert(A->getNumParams() == B->getNumParams());
2923 
2924   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2925     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2926     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2927     if (AttrA == AttrB)
2928       return true;
2929     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2930   };
2931 
2932   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2933 }
2934 
2935 /// If necessary, adjust the semantic declaration context for a qualified
2936 /// declaration to name the correct inline namespace within the qualifier.
2937 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2938                                                DeclaratorDecl *OldD) {
2939   // The only case where we need to update the DeclContext is when
2940   // redeclaration lookup for a qualified name finds a declaration
2941   // in an inline namespace within the context named by the qualifier:
2942   //
2943   //   inline namespace N { int f(); }
2944   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2945   //
2946   // For unqualified declarations, the semantic context *can* change
2947   // along the redeclaration chain (for local extern declarations,
2948   // extern "C" declarations, and friend declarations in particular).
2949   if (!NewD->getQualifier())
2950     return;
2951 
2952   // NewD is probably already in the right context.
2953   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2954   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2955   if (NamedDC->Equals(SemaDC))
2956     return;
2957 
2958   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2959           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2960          "unexpected context for redeclaration");
2961 
2962   auto *LexDC = NewD->getLexicalDeclContext();
2963   auto FixSemaDC = [=](NamedDecl *D) {
2964     if (!D)
2965       return;
2966     D->setDeclContext(SemaDC);
2967     D->setLexicalDeclContext(LexDC);
2968   };
2969 
2970   FixSemaDC(NewD);
2971   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2972     FixSemaDC(FD->getDescribedFunctionTemplate());
2973   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2974     FixSemaDC(VD->getDescribedVarTemplate());
2975 }
2976 
2977 /// MergeFunctionDecl - We just parsed a function 'New' from
2978 /// declarator D which has the same name and scope as a previous
2979 /// declaration 'Old'.  Figure out how to resolve this situation,
2980 /// merging decls or emitting diagnostics as appropriate.
2981 ///
2982 /// In C++, New and Old must be declarations that are not
2983 /// overloaded. Use IsOverload to determine whether New and Old are
2984 /// overloaded, and to select the Old declaration that New should be
2985 /// merged with.
2986 ///
2987 /// Returns true if there was an error, false otherwise.
2988 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2989                              Scope *S, bool MergeTypeWithOld) {
2990   // Verify the old decl was also a function.
2991   FunctionDecl *Old = OldD->getAsFunction();
2992   if (!Old) {
2993     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2994       if (New->getFriendObjectKind()) {
2995         Diag(New->getLocation(), diag::err_using_decl_friend);
2996         Diag(Shadow->getTargetDecl()->getLocation(),
2997              diag::note_using_decl_target);
2998         Diag(Shadow->getUsingDecl()->getLocation(),
2999              diag::note_using_decl) << 0;
3000         return true;
3001       }
3002 
3003       // Check whether the two declarations might declare the same function.
3004       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3005         return true;
3006       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3007     } else {
3008       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3009         << New->getDeclName();
3010       notePreviousDefinition(OldD, New->getLocation());
3011       return true;
3012     }
3013   }
3014 
3015   // If the old declaration is invalid, just give up here.
3016   if (Old->isInvalidDecl())
3017     return true;
3018 
3019   // Disallow redeclaration of some builtins.
3020   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3021     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3022     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3023         << Old << Old->getType();
3024     return true;
3025   }
3026 
3027   diag::kind PrevDiag;
3028   SourceLocation OldLocation;
3029   std::tie(PrevDiag, OldLocation) =
3030       getNoteDiagForInvalidRedeclaration(Old, New);
3031 
3032   // Don't complain about this if we're in GNU89 mode and the old function
3033   // is an extern inline function.
3034   // Don't complain about specializations. They are not supposed to have
3035   // storage classes.
3036   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3037       New->getStorageClass() == SC_Static &&
3038       Old->hasExternalFormalLinkage() &&
3039       !New->getTemplateSpecializationInfo() &&
3040       !canRedefineFunction(Old, getLangOpts())) {
3041     if (getLangOpts().MicrosoftExt) {
3042       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3043       Diag(OldLocation, PrevDiag);
3044     } else {
3045       Diag(New->getLocation(), diag::err_static_non_static) << New;
3046       Diag(OldLocation, PrevDiag);
3047       return true;
3048     }
3049   }
3050 
3051   if (New->hasAttr<InternalLinkageAttr>() &&
3052       !Old->hasAttr<InternalLinkageAttr>()) {
3053     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3054         << New->getDeclName();
3055     notePreviousDefinition(Old, New->getLocation());
3056     New->dropAttr<InternalLinkageAttr>();
3057   }
3058 
3059   if (CheckRedeclarationModuleOwnership(New, Old))
3060     return true;
3061 
3062   if (!getLangOpts().CPlusPlus) {
3063     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3064     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3065       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3066         << New << OldOvl;
3067 
3068       // Try our best to find a decl that actually has the overloadable
3069       // attribute for the note. In most cases (e.g. programs with only one
3070       // broken declaration/definition), this won't matter.
3071       //
3072       // FIXME: We could do this if we juggled some extra state in
3073       // OverloadableAttr, rather than just removing it.
3074       const Decl *DiagOld = Old;
3075       if (OldOvl) {
3076         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3077           const auto *A = D->getAttr<OverloadableAttr>();
3078           return A && !A->isImplicit();
3079         });
3080         // If we've implicitly added *all* of the overloadable attrs to this
3081         // chain, emitting a "previous redecl" note is pointless.
3082         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3083       }
3084 
3085       if (DiagOld)
3086         Diag(DiagOld->getLocation(),
3087              diag::note_attribute_overloadable_prev_overload)
3088           << OldOvl;
3089 
3090       if (OldOvl)
3091         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3092       else
3093         New->dropAttr<OverloadableAttr>();
3094     }
3095   }
3096 
3097   // If a function is first declared with a calling convention, but is later
3098   // declared or defined without one, all following decls assume the calling
3099   // convention of the first.
3100   //
3101   // It's OK if a function is first declared without a calling convention,
3102   // but is later declared or defined with the default calling convention.
3103   //
3104   // To test if either decl has an explicit calling convention, we look for
3105   // AttributedType sugar nodes on the type as written.  If they are missing or
3106   // were canonicalized away, we assume the calling convention was implicit.
3107   //
3108   // Note also that we DO NOT return at this point, because we still have
3109   // other tests to run.
3110   QualType OldQType = Context.getCanonicalType(Old->getType());
3111   QualType NewQType = Context.getCanonicalType(New->getType());
3112   const FunctionType *OldType = cast<FunctionType>(OldQType);
3113   const FunctionType *NewType = cast<FunctionType>(NewQType);
3114   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3115   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3116   bool RequiresAdjustment = false;
3117 
3118   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3119     FunctionDecl *First = Old->getFirstDecl();
3120     const FunctionType *FT =
3121         First->getType().getCanonicalType()->castAs<FunctionType>();
3122     FunctionType::ExtInfo FI = FT->getExtInfo();
3123     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3124     if (!NewCCExplicit) {
3125       // Inherit the CC from the previous declaration if it was specified
3126       // there but not here.
3127       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3128       RequiresAdjustment = true;
3129     } else {
3130       // Calling conventions aren't compatible, so complain.
3131       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3132       Diag(New->getLocation(), diag::err_cconv_change)
3133         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3134         << !FirstCCExplicit
3135         << (!FirstCCExplicit ? "" :
3136             FunctionType::getNameForCallConv(FI.getCC()));
3137 
3138       // Put the note on the first decl, since it is the one that matters.
3139       Diag(First->getLocation(), diag::note_previous_declaration);
3140       return true;
3141     }
3142   }
3143 
3144   // FIXME: diagnose the other way around?
3145   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3146     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3147     RequiresAdjustment = true;
3148   }
3149 
3150   // Merge regparm attribute.
3151   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3152       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3153     if (NewTypeInfo.getHasRegParm()) {
3154       Diag(New->getLocation(), diag::err_regparm_mismatch)
3155         << NewType->getRegParmType()
3156         << OldType->getRegParmType();
3157       Diag(OldLocation, diag::note_previous_declaration);
3158       return true;
3159     }
3160 
3161     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3162     RequiresAdjustment = true;
3163   }
3164 
3165   // Merge ns_returns_retained attribute.
3166   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3167     if (NewTypeInfo.getProducesResult()) {
3168       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3169           << "'ns_returns_retained'";
3170       Diag(OldLocation, diag::note_previous_declaration);
3171       return true;
3172     }
3173 
3174     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3175     RequiresAdjustment = true;
3176   }
3177 
3178   if (OldTypeInfo.getNoCallerSavedRegs() !=
3179       NewTypeInfo.getNoCallerSavedRegs()) {
3180     if (NewTypeInfo.getNoCallerSavedRegs()) {
3181       AnyX86NoCallerSavedRegistersAttr *Attr =
3182         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3183       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3184       Diag(OldLocation, diag::note_previous_declaration);
3185       return true;
3186     }
3187 
3188     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3189     RequiresAdjustment = true;
3190   }
3191 
3192   if (RequiresAdjustment) {
3193     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3194     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3195     New->setType(QualType(AdjustedType, 0));
3196     NewQType = Context.getCanonicalType(New->getType());
3197     NewType = cast<FunctionType>(NewQType);
3198   }
3199 
3200   // If this redeclaration makes the function inline, we may need to add it to
3201   // UndefinedButUsed.
3202   if (!Old->isInlined() && New->isInlined() &&
3203       !New->hasAttr<GNUInlineAttr>() &&
3204       !getLangOpts().GNUInline &&
3205       Old->isUsed(false) &&
3206       !Old->isDefined() && !New->isThisDeclarationADefinition())
3207     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3208                                            SourceLocation()));
3209 
3210   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3211   // about it.
3212   if (New->hasAttr<GNUInlineAttr>() &&
3213       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3214     UndefinedButUsed.erase(Old->getCanonicalDecl());
3215   }
3216 
3217   // If pass_object_size params don't match up perfectly, this isn't a valid
3218   // redeclaration.
3219   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3220       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3221     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3222         << New->getDeclName();
3223     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3224     return true;
3225   }
3226 
3227   if (getLangOpts().CPlusPlus) {
3228     // C++1z [over.load]p2
3229     //   Certain function declarations cannot be overloaded:
3230     //     -- Function declarations that differ only in the return type,
3231     //        the exception specification, or both cannot be overloaded.
3232 
3233     // Check the exception specifications match. This may recompute the type of
3234     // both Old and New if it resolved exception specifications, so grab the
3235     // types again after this. Because this updates the type, we do this before
3236     // any of the other checks below, which may update the "de facto" NewQType
3237     // but do not necessarily update the type of New.
3238     if (CheckEquivalentExceptionSpec(Old, New))
3239       return true;
3240     OldQType = Context.getCanonicalType(Old->getType());
3241     NewQType = Context.getCanonicalType(New->getType());
3242 
3243     // Go back to the type source info to compare the declared return types,
3244     // per C++1y [dcl.type.auto]p13:
3245     //   Redeclarations or specializations of a function or function template
3246     //   with a declared return type that uses a placeholder type shall also
3247     //   use that placeholder, not a deduced type.
3248     QualType OldDeclaredReturnType =
3249         (Old->getTypeSourceInfo()
3250              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3251              : OldType)->getReturnType();
3252     QualType NewDeclaredReturnType =
3253         (New->getTypeSourceInfo()
3254              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3255              : NewType)->getReturnType();
3256     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3257         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3258           New->isLocalExternDecl())) {
3259       QualType ResQT;
3260       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3261           OldDeclaredReturnType->isObjCObjectPointerType())
3262         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3263       if (ResQT.isNull()) {
3264         if (New->isCXXClassMember() && New->isOutOfLine())
3265           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3266               << New << New->getReturnTypeSourceRange();
3267         else
3268           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3269               << New->getReturnTypeSourceRange();
3270         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3271                                     << Old->getReturnTypeSourceRange();
3272         return true;
3273       }
3274       else
3275         NewQType = ResQT;
3276     }
3277 
3278     QualType OldReturnType = OldType->getReturnType();
3279     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3280     if (OldReturnType != NewReturnType) {
3281       // If this function has a deduced return type and has already been
3282       // defined, copy the deduced value from the old declaration.
3283       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3284       if (OldAT && OldAT->isDeduced()) {
3285         New->setType(
3286             SubstAutoType(New->getType(),
3287                           OldAT->isDependentType() ? Context.DependentTy
3288                                                    : OldAT->getDeducedType()));
3289         NewQType = Context.getCanonicalType(
3290             SubstAutoType(NewQType,
3291                           OldAT->isDependentType() ? Context.DependentTy
3292                                                    : OldAT->getDeducedType()));
3293       }
3294     }
3295 
3296     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3297     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3298     if (OldMethod && NewMethod) {
3299       // Preserve triviality.
3300       NewMethod->setTrivial(OldMethod->isTrivial());
3301 
3302       // MSVC allows explicit template specialization at class scope:
3303       // 2 CXXMethodDecls referring to the same function will be injected.
3304       // We don't want a redeclaration error.
3305       bool IsClassScopeExplicitSpecialization =
3306                               OldMethod->isFunctionTemplateSpecialization() &&
3307                               NewMethod->isFunctionTemplateSpecialization();
3308       bool isFriend = NewMethod->getFriendObjectKind();
3309 
3310       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3311           !IsClassScopeExplicitSpecialization) {
3312         //    -- Member function declarations with the same name and the
3313         //       same parameter types cannot be overloaded if any of them
3314         //       is a static member function declaration.
3315         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3316           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3317           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3318           return true;
3319         }
3320 
3321         // C++ [class.mem]p1:
3322         //   [...] A member shall not be declared twice in the
3323         //   member-specification, except that a nested class or member
3324         //   class template can be declared and then later defined.
3325         if (!inTemplateInstantiation()) {
3326           unsigned NewDiag;
3327           if (isa<CXXConstructorDecl>(OldMethod))
3328             NewDiag = diag::err_constructor_redeclared;
3329           else if (isa<CXXDestructorDecl>(NewMethod))
3330             NewDiag = diag::err_destructor_redeclared;
3331           else if (isa<CXXConversionDecl>(NewMethod))
3332             NewDiag = diag::err_conv_function_redeclared;
3333           else
3334             NewDiag = diag::err_member_redeclared;
3335 
3336           Diag(New->getLocation(), NewDiag);
3337         } else {
3338           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3339             << New << New->getType();
3340         }
3341         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3342         return true;
3343 
3344       // Complain if this is an explicit declaration of a special
3345       // member that was initially declared implicitly.
3346       //
3347       // As an exception, it's okay to befriend such methods in order
3348       // to permit the implicit constructor/destructor/operator calls.
3349       } else if (OldMethod->isImplicit()) {
3350         if (isFriend) {
3351           NewMethod->setImplicit();
3352         } else {
3353           Diag(NewMethod->getLocation(),
3354                diag::err_definition_of_implicitly_declared_member)
3355             << New << getSpecialMember(OldMethod);
3356           return true;
3357         }
3358       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3359         Diag(NewMethod->getLocation(),
3360              diag::err_definition_of_explicitly_defaulted_member)
3361           << getSpecialMember(OldMethod);
3362         return true;
3363       }
3364     }
3365 
3366     // C++11 [dcl.attr.noreturn]p1:
3367     //   The first declaration of a function shall specify the noreturn
3368     //   attribute if any declaration of that function specifies the noreturn
3369     //   attribute.
3370     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3371     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3372       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3373       Diag(Old->getFirstDecl()->getLocation(),
3374            diag::note_noreturn_missing_first_decl);
3375     }
3376 
3377     // C++11 [dcl.attr.depend]p2:
3378     //   The first declaration of a function shall specify the
3379     //   carries_dependency attribute for its declarator-id if any declaration
3380     //   of the function specifies the carries_dependency attribute.
3381     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3382     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3383       Diag(CDA->getLocation(),
3384            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3385       Diag(Old->getFirstDecl()->getLocation(),
3386            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3387     }
3388 
3389     // (C++98 8.3.5p3):
3390     //   All declarations for a function shall agree exactly in both the
3391     //   return type and the parameter-type-list.
3392     // We also want to respect all the extended bits except noreturn.
3393 
3394     // noreturn should now match unless the old type info didn't have it.
3395     QualType OldQTypeForComparison = OldQType;
3396     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3397       auto *OldType = OldQType->castAs<FunctionProtoType>();
3398       const FunctionType *OldTypeForComparison
3399         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3400       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3401       assert(OldQTypeForComparison.isCanonical());
3402     }
3403 
3404     if (haveIncompatibleLanguageLinkages(Old, New)) {
3405       // As a special case, retain the language linkage from previous
3406       // declarations of a friend function as an extension.
3407       //
3408       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3409       // and is useful because there's otherwise no way to specify language
3410       // linkage within class scope.
3411       //
3412       // Check cautiously as the friend object kind isn't yet complete.
3413       if (New->getFriendObjectKind() != Decl::FOK_None) {
3414         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3415         Diag(OldLocation, PrevDiag);
3416       } else {
3417         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3418         Diag(OldLocation, PrevDiag);
3419         return true;
3420       }
3421     }
3422 
3423     if (OldQTypeForComparison == NewQType)
3424       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3425 
3426     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3427         New->isLocalExternDecl()) {
3428       // It's OK if we couldn't merge types for a local function declaraton
3429       // if either the old or new type is dependent. We'll merge the types
3430       // when we instantiate the function.
3431       return false;
3432     }
3433 
3434     // Fall through for conflicting redeclarations and redefinitions.
3435   }
3436 
3437   // C: Function types need to be compatible, not identical. This handles
3438   // duplicate function decls like "void f(int); void f(enum X);" properly.
3439   if (!getLangOpts().CPlusPlus &&
3440       Context.typesAreCompatible(OldQType, NewQType)) {
3441     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3442     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3443     const FunctionProtoType *OldProto = nullptr;
3444     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3445         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3446       // The old declaration provided a function prototype, but the
3447       // new declaration does not. Merge in the prototype.
3448       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3449       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3450       NewQType =
3451           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3452                                   OldProto->getExtProtoInfo());
3453       New->setType(NewQType);
3454       New->setHasInheritedPrototype();
3455 
3456       // Synthesize parameters with the same types.
3457       SmallVector<ParmVarDecl*, 16> Params;
3458       for (const auto &ParamType : OldProto->param_types()) {
3459         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3460                                                  SourceLocation(), nullptr,
3461                                                  ParamType, /*TInfo=*/nullptr,
3462                                                  SC_None, nullptr);
3463         Param->setScopeInfo(0, Params.size());
3464         Param->setImplicit();
3465         Params.push_back(Param);
3466       }
3467 
3468       New->setParams(Params);
3469     }
3470 
3471     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3472   }
3473 
3474   // GNU C permits a K&R definition to follow a prototype declaration
3475   // if the declared types of the parameters in the K&R definition
3476   // match the types in the prototype declaration, even when the
3477   // promoted types of the parameters from the K&R definition differ
3478   // from the types in the prototype. GCC then keeps the types from
3479   // the prototype.
3480   //
3481   // If a variadic prototype is followed by a non-variadic K&R definition,
3482   // the K&R definition becomes variadic.  This is sort of an edge case, but
3483   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3484   // C99 6.9.1p8.
3485   if (!getLangOpts().CPlusPlus &&
3486       Old->hasPrototype() && !New->hasPrototype() &&
3487       New->getType()->getAs<FunctionProtoType>() &&
3488       Old->getNumParams() == New->getNumParams()) {
3489     SmallVector<QualType, 16> ArgTypes;
3490     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3491     const FunctionProtoType *OldProto
3492       = Old->getType()->getAs<FunctionProtoType>();
3493     const FunctionProtoType *NewProto
3494       = New->getType()->getAs<FunctionProtoType>();
3495 
3496     // Determine whether this is the GNU C extension.
3497     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3498                                                NewProto->getReturnType());
3499     bool LooseCompatible = !MergedReturn.isNull();
3500     for (unsigned Idx = 0, End = Old->getNumParams();
3501          LooseCompatible && Idx != End; ++Idx) {
3502       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3503       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3504       if (Context.typesAreCompatible(OldParm->getType(),
3505                                      NewProto->getParamType(Idx))) {
3506         ArgTypes.push_back(NewParm->getType());
3507       } else if (Context.typesAreCompatible(OldParm->getType(),
3508                                             NewParm->getType(),
3509                                             /*CompareUnqualified=*/true)) {
3510         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3511                                            NewProto->getParamType(Idx) };
3512         Warnings.push_back(Warn);
3513         ArgTypes.push_back(NewParm->getType());
3514       } else
3515         LooseCompatible = false;
3516     }
3517 
3518     if (LooseCompatible) {
3519       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3520         Diag(Warnings[Warn].NewParm->getLocation(),
3521              diag::ext_param_promoted_not_compatible_with_prototype)
3522           << Warnings[Warn].PromotedType
3523           << Warnings[Warn].OldParm->getType();
3524         if (Warnings[Warn].OldParm->getLocation().isValid())
3525           Diag(Warnings[Warn].OldParm->getLocation(),
3526                diag::note_previous_declaration);
3527       }
3528 
3529       if (MergeTypeWithOld)
3530         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3531                                              OldProto->getExtProtoInfo()));
3532       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3533     }
3534 
3535     // Fall through to diagnose conflicting types.
3536   }
3537 
3538   // A function that has already been declared has been redeclared or
3539   // defined with a different type; show an appropriate diagnostic.
3540 
3541   // If the previous declaration was an implicitly-generated builtin
3542   // declaration, then at the very least we should use a specialized note.
3543   unsigned BuiltinID;
3544   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3545     // If it's actually a library-defined builtin function like 'malloc'
3546     // or 'printf', just warn about the incompatible redeclaration.
3547     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3548       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3549       Diag(OldLocation, diag::note_previous_builtin_declaration)
3550         << Old << Old->getType();
3551 
3552       // If this is a global redeclaration, just forget hereafter
3553       // about the "builtin-ness" of the function.
3554       //
3555       // Doing this for local extern declarations is problematic.  If
3556       // the builtin declaration remains visible, a second invalid
3557       // local declaration will produce a hard error; if it doesn't
3558       // remain visible, a single bogus local redeclaration (which is
3559       // actually only a warning) could break all the downstream code.
3560       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3561         New->getIdentifier()->revertBuiltin();
3562 
3563       return false;
3564     }
3565 
3566     PrevDiag = diag::note_previous_builtin_declaration;
3567   }
3568 
3569   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3570   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3571   return true;
3572 }
3573 
3574 /// Completes the merge of two function declarations that are
3575 /// known to be compatible.
3576 ///
3577 /// This routine handles the merging of attributes and other
3578 /// properties of function declarations from the old declaration to
3579 /// the new declaration, once we know that New is in fact a
3580 /// redeclaration of Old.
3581 ///
3582 /// \returns false
3583 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3584                                         Scope *S, bool MergeTypeWithOld) {
3585   // Merge the attributes
3586   mergeDeclAttributes(New, Old);
3587 
3588   // Merge "pure" flag.
3589   if (Old->isPure())
3590     New->setPure();
3591 
3592   // Merge "used" flag.
3593   if (Old->getMostRecentDecl()->isUsed(false))
3594     New->setIsUsed();
3595 
3596   // Merge attributes from the parameters.  These can mismatch with K&R
3597   // declarations.
3598   if (New->getNumParams() == Old->getNumParams())
3599       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3600         ParmVarDecl *NewParam = New->getParamDecl(i);
3601         ParmVarDecl *OldParam = Old->getParamDecl(i);
3602         mergeParamDeclAttributes(NewParam, OldParam, *this);
3603         mergeParamDeclTypes(NewParam, OldParam, *this);
3604       }
3605 
3606   if (getLangOpts().CPlusPlus)
3607     return MergeCXXFunctionDecl(New, Old, S);
3608 
3609   // Merge the function types so the we get the composite types for the return
3610   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3611   // was visible.
3612   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3613   if (!Merged.isNull() && MergeTypeWithOld)
3614     New->setType(Merged);
3615 
3616   return false;
3617 }
3618 
3619 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3620                                 ObjCMethodDecl *oldMethod) {
3621   // Merge the attributes, including deprecated/unavailable
3622   AvailabilityMergeKind MergeKind =
3623     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3624       ? AMK_ProtocolImplementation
3625       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3626                                                        : AMK_Override;
3627 
3628   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3629 
3630   // Merge attributes from the parameters.
3631   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3632                                        oe = oldMethod->param_end();
3633   for (ObjCMethodDecl::param_iterator
3634          ni = newMethod->param_begin(), ne = newMethod->param_end();
3635        ni != ne && oi != oe; ++ni, ++oi)
3636     mergeParamDeclAttributes(*ni, *oi, *this);
3637 
3638   CheckObjCMethodOverride(newMethod, oldMethod);
3639 }
3640 
3641 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3642   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3643 
3644   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3645          ? diag::err_redefinition_different_type
3646          : diag::err_redeclaration_different_type)
3647     << New->getDeclName() << New->getType() << Old->getType();
3648 
3649   diag::kind PrevDiag;
3650   SourceLocation OldLocation;
3651   std::tie(PrevDiag, OldLocation)
3652     = getNoteDiagForInvalidRedeclaration(Old, New);
3653   S.Diag(OldLocation, PrevDiag);
3654   New->setInvalidDecl();
3655 }
3656 
3657 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3658 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3659 /// emitting diagnostics as appropriate.
3660 ///
3661 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3662 /// to here in AddInitializerToDecl. We can't check them before the initializer
3663 /// is attached.
3664 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3665                              bool MergeTypeWithOld) {
3666   if (New->isInvalidDecl() || Old->isInvalidDecl())
3667     return;
3668 
3669   QualType MergedT;
3670   if (getLangOpts().CPlusPlus) {
3671     if (New->getType()->isUndeducedType()) {
3672       // We don't know what the new type is until the initializer is attached.
3673       return;
3674     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3675       // These could still be something that needs exception specs checked.
3676       return MergeVarDeclExceptionSpecs(New, Old);
3677     }
3678     // C++ [basic.link]p10:
3679     //   [...] the types specified by all declarations referring to a given
3680     //   object or function shall be identical, except that declarations for an
3681     //   array object can specify array types that differ by the presence or
3682     //   absence of a major array bound (8.3.4).
3683     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3684       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3685       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3686 
3687       // We are merging a variable declaration New into Old. If it has an array
3688       // bound, and that bound differs from Old's bound, we should diagnose the
3689       // mismatch.
3690       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3691         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3692              PrevVD = PrevVD->getPreviousDecl()) {
3693           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3694           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3695             continue;
3696 
3697           if (!Context.hasSameType(NewArray, PrevVDTy))
3698             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3699         }
3700       }
3701 
3702       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3703         if (Context.hasSameType(OldArray->getElementType(),
3704                                 NewArray->getElementType()))
3705           MergedT = New->getType();
3706       }
3707       // FIXME: Check visibility. New is hidden but has a complete type. If New
3708       // has no array bound, it should not inherit one from Old, if Old is not
3709       // visible.
3710       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3711         if (Context.hasSameType(OldArray->getElementType(),
3712                                 NewArray->getElementType()))
3713           MergedT = Old->getType();
3714       }
3715     }
3716     else if (New->getType()->isObjCObjectPointerType() &&
3717                Old->getType()->isObjCObjectPointerType()) {
3718       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3719                                               Old->getType());
3720     }
3721   } else {
3722     // C 6.2.7p2:
3723     //   All declarations that refer to the same object or function shall have
3724     //   compatible type.
3725     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3726   }
3727   if (MergedT.isNull()) {
3728     // It's OK if we couldn't merge types if either type is dependent, for a
3729     // block-scope variable. In other cases (static data members of class
3730     // templates, variable templates, ...), we require the types to be
3731     // equivalent.
3732     // FIXME: The C++ standard doesn't say anything about this.
3733     if ((New->getType()->isDependentType() ||
3734          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3735       // If the old type was dependent, we can't merge with it, so the new type
3736       // becomes dependent for now. We'll reproduce the original type when we
3737       // instantiate the TypeSourceInfo for the variable.
3738       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3739         New->setType(Context.DependentTy);
3740       return;
3741     }
3742     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3743   }
3744 
3745   // Don't actually update the type on the new declaration if the old
3746   // declaration was an extern declaration in a different scope.
3747   if (MergeTypeWithOld)
3748     New->setType(MergedT);
3749 }
3750 
3751 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3752                                   LookupResult &Previous) {
3753   // C11 6.2.7p4:
3754   //   For an identifier with internal or external linkage declared
3755   //   in a scope in which a prior declaration of that identifier is
3756   //   visible, if the prior declaration specifies internal or
3757   //   external linkage, the type of the identifier at the later
3758   //   declaration becomes the composite type.
3759   //
3760   // If the variable isn't visible, we do not merge with its type.
3761   if (Previous.isShadowed())
3762     return false;
3763 
3764   if (S.getLangOpts().CPlusPlus) {
3765     // C++11 [dcl.array]p3:
3766     //   If there is a preceding declaration of the entity in the same
3767     //   scope in which the bound was specified, an omitted array bound
3768     //   is taken to be the same as in that earlier declaration.
3769     return NewVD->isPreviousDeclInSameBlockScope() ||
3770            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3771             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3772   } else {
3773     // If the old declaration was function-local, don't merge with its
3774     // type unless we're in the same function.
3775     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3776            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3777   }
3778 }
3779 
3780 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3781 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3782 /// situation, merging decls or emitting diagnostics as appropriate.
3783 ///
3784 /// Tentative definition rules (C99 6.9.2p2) are checked by
3785 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3786 /// definitions here, since the initializer hasn't been attached.
3787 ///
3788 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3789   // If the new decl is already invalid, don't do any other checking.
3790   if (New->isInvalidDecl())
3791     return;
3792 
3793   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3794     return;
3795 
3796   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3797 
3798   // Verify the old decl was also a variable or variable template.
3799   VarDecl *Old = nullptr;
3800   VarTemplateDecl *OldTemplate = nullptr;
3801   if (Previous.isSingleResult()) {
3802     if (NewTemplate) {
3803       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3804       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3805 
3806       if (auto *Shadow =
3807               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3808         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3809           return New->setInvalidDecl();
3810     } else {
3811       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3812 
3813       if (auto *Shadow =
3814               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3815         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3816           return New->setInvalidDecl();
3817     }
3818   }
3819   if (!Old) {
3820     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3821         << New->getDeclName();
3822     notePreviousDefinition(Previous.getRepresentativeDecl(),
3823                            New->getLocation());
3824     return New->setInvalidDecl();
3825   }
3826 
3827   // Ensure the template parameters are compatible.
3828   if (NewTemplate &&
3829       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3830                                       OldTemplate->getTemplateParameters(),
3831                                       /*Complain=*/true, TPL_TemplateMatch))
3832     return New->setInvalidDecl();
3833 
3834   // C++ [class.mem]p1:
3835   //   A member shall not be declared twice in the member-specification [...]
3836   //
3837   // Here, we need only consider static data members.
3838   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3839     Diag(New->getLocation(), diag::err_duplicate_member)
3840       << New->getIdentifier();
3841     Diag(Old->getLocation(), diag::note_previous_declaration);
3842     New->setInvalidDecl();
3843   }
3844 
3845   mergeDeclAttributes(New, Old);
3846   // Warn if an already-declared variable is made a weak_import in a subsequent
3847   // declaration
3848   if (New->hasAttr<WeakImportAttr>() &&
3849       Old->getStorageClass() == SC_None &&
3850       !Old->hasAttr<WeakImportAttr>()) {
3851     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3852     notePreviousDefinition(Old, New->getLocation());
3853     // Remove weak_import attribute on new declaration.
3854     New->dropAttr<WeakImportAttr>();
3855   }
3856 
3857   if (New->hasAttr<InternalLinkageAttr>() &&
3858       !Old->hasAttr<InternalLinkageAttr>()) {
3859     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3860         << New->getDeclName();
3861     notePreviousDefinition(Old, New->getLocation());
3862     New->dropAttr<InternalLinkageAttr>();
3863   }
3864 
3865   // Merge the types.
3866   VarDecl *MostRecent = Old->getMostRecentDecl();
3867   if (MostRecent != Old) {
3868     MergeVarDeclTypes(New, MostRecent,
3869                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3870     if (New->isInvalidDecl())
3871       return;
3872   }
3873 
3874   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3875   if (New->isInvalidDecl())
3876     return;
3877 
3878   diag::kind PrevDiag;
3879   SourceLocation OldLocation;
3880   std::tie(PrevDiag, OldLocation) =
3881       getNoteDiagForInvalidRedeclaration(Old, New);
3882 
3883   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3884   if (New->getStorageClass() == SC_Static &&
3885       !New->isStaticDataMember() &&
3886       Old->hasExternalFormalLinkage()) {
3887     if (getLangOpts().MicrosoftExt) {
3888       Diag(New->getLocation(), diag::ext_static_non_static)
3889           << New->getDeclName();
3890       Diag(OldLocation, PrevDiag);
3891     } else {
3892       Diag(New->getLocation(), diag::err_static_non_static)
3893           << New->getDeclName();
3894       Diag(OldLocation, PrevDiag);
3895       return New->setInvalidDecl();
3896     }
3897   }
3898   // C99 6.2.2p4:
3899   //   For an identifier declared with the storage-class specifier
3900   //   extern in a scope in which a prior declaration of that
3901   //   identifier is visible,23) if the prior declaration specifies
3902   //   internal or external linkage, the linkage of the identifier at
3903   //   the later declaration is the same as the linkage specified at
3904   //   the prior declaration. If no prior declaration is visible, or
3905   //   if the prior declaration specifies no linkage, then the
3906   //   identifier has external linkage.
3907   if (New->hasExternalStorage() && Old->hasLinkage())
3908     /* Okay */;
3909   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3910            !New->isStaticDataMember() &&
3911            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3912     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3913     Diag(OldLocation, PrevDiag);
3914     return New->setInvalidDecl();
3915   }
3916 
3917   // Check if extern is followed by non-extern and vice-versa.
3918   if (New->hasExternalStorage() &&
3919       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3920     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3921     Diag(OldLocation, PrevDiag);
3922     return New->setInvalidDecl();
3923   }
3924   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3925       !New->hasExternalStorage()) {
3926     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3927     Diag(OldLocation, PrevDiag);
3928     return New->setInvalidDecl();
3929   }
3930 
3931   if (CheckRedeclarationModuleOwnership(New, Old))
3932     return;
3933 
3934   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3935 
3936   // FIXME: The test for external storage here seems wrong? We still
3937   // need to check for mismatches.
3938   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3939       // Don't complain about out-of-line definitions of static members.
3940       !(Old->getLexicalDeclContext()->isRecord() &&
3941         !New->getLexicalDeclContext()->isRecord())) {
3942     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3943     Diag(OldLocation, PrevDiag);
3944     return New->setInvalidDecl();
3945   }
3946 
3947   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3948     if (VarDecl *Def = Old->getDefinition()) {
3949       // C++1z [dcl.fcn.spec]p4:
3950       //   If the definition of a variable appears in a translation unit before
3951       //   its first declaration as inline, the program is ill-formed.
3952       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3953       Diag(Def->getLocation(), diag::note_previous_definition);
3954     }
3955   }
3956 
3957   // If this redeclaration makes the variable inline, we may need to add it to
3958   // UndefinedButUsed.
3959   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3960       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3961     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3962                                            SourceLocation()));
3963 
3964   if (New->getTLSKind() != Old->getTLSKind()) {
3965     if (!Old->getTLSKind()) {
3966       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3967       Diag(OldLocation, PrevDiag);
3968     } else if (!New->getTLSKind()) {
3969       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3970       Diag(OldLocation, PrevDiag);
3971     } else {
3972       // Do not allow redeclaration to change the variable between requiring
3973       // static and dynamic initialization.
3974       // FIXME: GCC allows this, but uses the TLS keyword on the first
3975       // declaration to determine the kind. Do we need to be compatible here?
3976       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3977         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3978       Diag(OldLocation, PrevDiag);
3979     }
3980   }
3981 
3982   // C++ doesn't have tentative definitions, so go right ahead and check here.
3983   if (getLangOpts().CPlusPlus &&
3984       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3985     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3986         Old->getCanonicalDecl()->isConstexpr()) {
3987       // This definition won't be a definition any more once it's been merged.
3988       Diag(New->getLocation(),
3989            diag::warn_deprecated_redundant_constexpr_static_def);
3990     } else if (VarDecl *Def = Old->getDefinition()) {
3991       if (checkVarDeclRedefinition(Def, New))
3992         return;
3993     }
3994   }
3995 
3996   if (haveIncompatibleLanguageLinkages(Old, New)) {
3997     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3998     Diag(OldLocation, PrevDiag);
3999     New->setInvalidDecl();
4000     return;
4001   }
4002 
4003   // Merge "used" flag.
4004   if (Old->getMostRecentDecl()->isUsed(false))
4005     New->setIsUsed();
4006 
4007   // Keep a chain of previous declarations.
4008   New->setPreviousDecl(Old);
4009   if (NewTemplate)
4010     NewTemplate->setPreviousDecl(OldTemplate);
4011   adjustDeclContextForDeclaratorDecl(New, Old);
4012 
4013   // Inherit access appropriately.
4014   New->setAccess(Old->getAccess());
4015   if (NewTemplate)
4016     NewTemplate->setAccess(New->getAccess());
4017 
4018   if (Old->isInline())
4019     New->setImplicitlyInline();
4020 }
4021 
4022 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4023   SourceManager &SrcMgr = getSourceManager();
4024   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4025   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4026   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4027   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4028   auto &HSI = PP.getHeaderSearchInfo();
4029   StringRef HdrFilename =
4030       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4031 
4032   auto noteFromModuleOrInclude = [&](Module *Mod,
4033                                      SourceLocation IncLoc) -> bool {
4034     // Redefinition errors with modules are common with non modular mapped
4035     // headers, example: a non-modular header H in module A that also gets
4036     // included directly in a TU. Pointing twice to the same header/definition
4037     // is confusing, try to get better diagnostics when modules is on.
4038     if (IncLoc.isValid()) {
4039       if (Mod) {
4040         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4041             << HdrFilename.str() << Mod->getFullModuleName();
4042         if (!Mod->DefinitionLoc.isInvalid())
4043           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4044               << Mod->getFullModuleName();
4045       } else {
4046         Diag(IncLoc, diag::note_redefinition_include_same_file)
4047             << HdrFilename.str();
4048       }
4049       return true;
4050     }
4051 
4052     return false;
4053   };
4054 
4055   // Is it the same file and same offset? Provide more information on why
4056   // this leads to a redefinition error.
4057   bool EmittedDiag = false;
4058   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4059     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4060     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4061     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4062     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4063 
4064     // If the header has no guards, emit a note suggesting one.
4065     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4066       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4067 
4068     if (EmittedDiag)
4069       return;
4070   }
4071 
4072   // Redefinition coming from different files or couldn't do better above.
4073   if (Old->getLocation().isValid())
4074     Diag(Old->getLocation(), diag::note_previous_definition);
4075 }
4076 
4077 /// We've just determined that \p Old and \p New both appear to be definitions
4078 /// of the same variable. Either diagnose or fix the problem.
4079 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4080   if (!hasVisibleDefinition(Old) &&
4081       (New->getFormalLinkage() == InternalLinkage ||
4082        New->isInline() ||
4083        New->getDescribedVarTemplate() ||
4084        New->getNumTemplateParameterLists() ||
4085        New->getDeclContext()->isDependentContext())) {
4086     // The previous definition is hidden, and multiple definitions are
4087     // permitted (in separate TUs). Demote this to a declaration.
4088     New->demoteThisDefinitionToDeclaration();
4089 
4090     // Make the canonical definition visible.
4091     if (auto *OldTD = Old->getDescribedVarTemplate())
4092       makeMergedDefinitionVisible(OldTD);
4093     makeMergedDefinitionVisible(Old);
4094     return false;
4095   } else {
4096     Diag(New->getLocation(), diag::err_redefinition) << New;
4097     notePreviousDefinition(Old, New->getLocation());
4098     New->setInvalidDecl();
4099     return true;
4100   }
4101 }
4102 
4103 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4104 /// no declarator (e.g. "struct foo;") is parsed.
4105 Decl *
4106 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4107                                  RecordDecl *&AnonRecord) {
4108   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4109                                     AnonRecord);
4110 }
4111 
4112 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4113 // disambiguate entities defined in different scopes.
4114 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4115 // compatibility.
4116 // We will pick our mangling number depending on which version of MSVC is being
4117 // targeted.
4118 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4119   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4120              ? S->getMSCurManglingNumber()
4121              : S->getMSLastManglingNumber();
4122 }
4123 
4124 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4125   if (!Context.getLangOpts().CPlusPlus)
4126     return;
4127 
4128   if (isa<CXXRecordDecl>(Tag->getParent())) {
4129     // If this tag is the direct child of a class, number it if
4130     // it is anonymous.
4131     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4132       return;
4133     MangleNumberingContext &MCtx =
4134         Context.getManglingNumberContext(Tag->getParent());
4135     Context.setManglingNumber(
4136         Tag, MCtx.getManglingNumber(
4137                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4138     return;
4139   }
4140 
4141   // If this tag isn't a direct child of a class, number it if it is local.
4142   Decl *ManglingContextDecl;
4143   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4144           Tag->getDeclContext(), ManglingContextDecl)) {
4145     Context.setManglingNumber(
4146         Tag, MCtx->getManglingNumber(
4147                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4148   }
4149 }
4150 
4151 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4152                                         TypedefNameDecl *NewTD) {
4153   if (TagFromDeclSpec->isInvalidDecl())
4154     return;
4155 
4156   // Do nothing if the tag already has a name for linkage purposes.
4157   if (TagFromDeclSpec->hasNameForLinkage())
4158     return;
4159 
4160   // A well-formed anonymous tag must always be a TUK_Definition.
4161   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4162 
4163   // The type must match the tag exactly;  no qualifiers allowed.
4164   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4165                            Context.getTagDeclType(TagFromDeclSpec))) {
4166     if (getLangOpts().CPlusPlus)
4167       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4168     return;
4169   }
4170 
4171   // If we've already computed linkage for the anonymous tag, then
4172   // adding a typedef name for the anonymous decl can change that
4173   // linkage, which might be a serious problem.  Diagnose this as
4174   // unsupported and ignore the typedef name.  TODO: we should
4175   // pursue this as a language defect and establish a formal rule
4176   // for how to handle it.
4177   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4178     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4179 
4180     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4181     tagLoc = getLocForEndOfToken(tagLoc);
4182 
4183     llvm::SmallString<40> textToInsert;
4184     textToInsert += ' ';
4185     textToInsert += NewTD->getIdentifier()->getName();
4186     Diag(tagLoc, diag::note_typedef_changes_linkage)
4187         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4188     return;
4189   }
4190 
4191   // Otherwise, set this is the anon-decl typedef for the tag.
4192   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4193 }
4194 
4195 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4196   switch (T) {
4197   case DeclSpec::TST_class:
4198     return 0;
4199   case DeclSpec::TST_struct:
4200     return 1;
4201   case DeclSpec::TST_interface:
4202     return 2;
4203   case DeclSpec::TST_union:
4204     return 3;
4205   case DeclSpec::TST_enum:
4206     return 4;
4207   default:
4208     llvm_unreachable("unexpected type specifier");
4209   }
4210 }
4211 
4212 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4213 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4214 /// parameters to cope with template friend declarations.
4215 Decl *
4216 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4217                                  MultiTemplateParamsArg TemplateParams,
4218                                  bool IsExplicitInstantiation,
4219                                  RecordDecl *&AnonRecord) {
4220   Decl *TagD = nullptr;
4221   TagDecl *Tag = nullptr;
4222   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4223       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4224       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4225       DS.getTypeSpecType() == DeclSpec::TST_union ||
4226       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4227     TagD = DS.getRepAsDecl();
4228 
4229     if (!TagD) // We probably had an error
4230       return nullptr;
4231 
4232     // Note that the above type specs guarantee that the
4233     // type rep is a Decl, whereas in many of the others
4234     // it's a Type.
4235     if (isa<TagDecl>(TagD))
4236       Tag = cast<TagDecl>(TagD);
4237     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4238       Tag = CTD->getTemplatedDecl();
4239   }
4240 
4241   if (Tag) {
4242     handleTagNumbering(Tag, S);
4243     Tag->setFreeStanding();
4244     if (Tag->isInvalidDecl())
4245       return Tag;
4246   }
4247 
4248   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4249     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4250     // or incomplete types shall not be restrict-qualified."
4251     if (TypeQuals & DeclSpec::TQ_restrict)
4252       Diag(DS.getRestrictSpecLoc(),
4253            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4254            << DS.getSourceRange();
4255   }
4256 
4257   if (DS.isInlineSpecified())
4258     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4259         << getLangOpts().CPlusPlus17;
4260 
4261   if (DS.isConstexprSpecified()) {
4262     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4263     // and definitions of functions and variables.
4264     if (Tag)
4265       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4266           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4267     else
4268       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4269     // Don't emit warnings after this error.
4270     return TagD;
4271   }
4272 
4273   DiagnoseFunctionSpecifiers(DS);
4274 
4275   if (DS.isFriendSpecified()) {
4276     // If we're dealing with a decl but not a TagDecl, assume that
4277     // whatever routines created it handled the friendship aspect.
4278     if (TagD && !Tag)
4279       return nullptr;
4280     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4281   }
4282 
4283   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4284   bool IsExplicitSpecialization =
4285     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4286   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4287       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4288       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4289     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4290     // nested-name-specifier unless it is an explicit instantiation
4291     // or an explicit specialization.
4292     //
4293     // FIXME: We allow class template partial specializations here too, per the
4294     // obvious intent of DR1819.
4295     //
4296     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4297     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4298         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4299     return nullptr;
4300   }
4301 
4302   // Track whether this decl-specifier declares anything.
4303   bool DeclaresAnything = true;
4304 
4305   // Handle anonymous struct definitions.
4306   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4307     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4308         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4309       if (getLangOpts().CPlusPlus ||
4310           Record->getDeclContext()->isRecord()) {
4311         // If CurContext is a DeclContext that can contain statements,
4312         // RecursiveASTVisitor won't visit the decls that
4313         // BuildAnonymousStructOrUnion() will put into CurContext.
4314         // Also store them here so that they can be part of the
4315         // DeclStmt that gets created in this case.
4316         // FIXME: Also return the IndirectFieldDecls created by
4317         // BuildAnonymousStructOr union, for the same reason?
4318         if (CurContext->isFunctionOrMethod())
4319           AnonRecord = Record;
4320         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4321                                            Context.getPrintingPolicy());
4322       }
4323 
4324       DeclaresAnything = false;
4325     }
4326   }
4327 
4328   // C11 6.7.2.1p2:
4329   //   A struct-declaration that does not declare an anonymous structure or
4330   //   anonymous union shall contain a struct-declarator-list.
4331   //
4332   // This rule also existed in C89 and C99; the grammar for struct-declaration
4333   // did not permit a struct-declaration without a struct-declarator-list.
4334   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4335       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4336     // Check for Microsoft C extension: anonymous struct/union member.
4337     // Handle 2 kinds of anonymous struct/union:
4338     //   struct STRUCT;
4339     //   union UNION;
4340     // and
4341     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4342     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4343     if ((Tag && Tag->getDeclName()) ||
4344         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4345       RecordDecl *Record = nullptr;
4346       if (Tag)
4347         Record = dyn_cast<RecordDecl>(Tag);
4348       else if (const RecordType *RT =
4349                    DS.getRepAsType().get()->getAsStructureType())
4350         Record = RT->getDecl();
4351       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4352         Record = UT->getDecl();
4353 
4354       if (Record && getLangOpts().MicrosoftExt) {
4355         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4356             << Record->isUnion() << DS.getSourceRange();
4357         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4358       }
4359 
4360       DeclaresAnything = false;
4361     }
4362   }
4363 
4364   // Skip all the checks below if we have a type error.
4365   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4366       (TagD && TagD->isInvalidDecl()))
4367     return TagD;
4368 
4369   if (getLangOpts().CPlusPlus &&
4370       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4371     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4372       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4373           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4374         DeclaresAnything = false;
4375 
4376   if (!DS.isMissingDeclaratorOk()) {
4377     // Customize diagnostic for a typedef missing a name.
4378     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4379       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4380           << DS.getSourceRange();
4381     else
4382       DeclaresAnything = false;
4383   }
4384 
4385   if (DS.isModulePrivateSpecified() &&
4386       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4387     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4388       << Tag->getTagKind()
4389       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4390 
4391   ActOnDocumentableDecl(TagD);
4392 
4393   // C 6.7/2:
4394   //   A declaration [...] shall declare at least a declarator [...], a tag,
4395   //   or the members of an enumeration.
4396   // C++ [dcl.dcl]p3:
4397   //   [If there are no declarators], and except for the declaration of an
4398   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4399   //   names into the program, or shall redeclare a name introduced by a
4400   //   previous declaration.
4401   if (!DeclaresAnything) {
4402     // In C, we allow this as a (popular) extension / bug. Don't bother
4403     // producing further diagnostics for redundant qualifiers after this.
4404     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4405     return TagD;
4406   }
4407 
4408   // C++ [dcl.stc]p1:
4409   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4410   //   init-declarator-list of the declaration shall not be empty.
4411   // C++ [dcl.fct.spec]p1:
4412   //   If a cv-qualifier appears in a decl-specifier-seq, the
4413   //   init-declarator-list of the declaration shall not be empty.
4414   //
4415   // Spurious qualifiers here appear to be valid in C.
4416   unsigned DiagID = diag::warn_standalone_specifier;
4417   if (getLangOpts().CPlusPlus)
4418     DiagID = diag::ext_standalone_specifier;
4419 
4420   // Note that a linkage-specification sets a storage class, but
4421   // 'extern "C" struct foo;' is actually valid and not theoretically
4422   // useless.
4423   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4424     if (SCS == DeclSpec::SCS_mutable)
4425       // Since mutable is not a viable storage class specifier in C, there is
4426       // no reason to treat it as an extension. Instead, diagnose as an error.
4427       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4428     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4429       Diag(DS.getStorageClassSpecLoc(), DiagID)
4430         << DeclSpec::getSpecifierName(SCS);
4431   }
4432 
4433   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4434     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4435       << DeclSpec::getSpecifierName(TSCS);
4436   if (DS.getTypeQualifiers()) {
4437     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4438       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4439     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4440       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4441     // Restrict is covered above.
4442     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4443       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4444     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4445       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4446   }
4447 
4448   // Warn about ignored type attributes, for example:
4449   // __attribute__((aligned)) struct A;
4450   // Attributes should be placed after tag to apply to type declaration.
4451   if (!DS.getAttributes().empty()) {
4452     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4453     if (TypeSpecType == DeclSpec::TST_class ||
4454         TypeSpecType == DeclSpec::TST_struct ||
4455         TypeSpecType == DeclSpec::TST_interface ||
4456         TypeSpecType == DeclSpec::TST_union ||
4457         TypeSpecType == DeclSpec::TST_enum) {
4458       for (const ParsedAttr &AL : DS.getAttributes())
4459         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4460             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4461     }
4462   }
4463 
4464   return TagD;
4465 }
4466 
4467 /// We are trying to inject an anonymous member into the given scope;
4468 /// check if there's an existing declaration that can't be overloaded.
4469 ///
4470 /// \return true if this is a forbidden redeclaration
4471 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4472                                          Scope *S,
4473                                          DeclContext *Owner,
4474                                          DeclarationName Name,
4475                                          SourceLocation NameLoc,
4476                                          bool IsUnion) {
4477   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4478                  Sema::ForVisibleRedeclaration);
4479   if (!SemaRef.LookupName(R, S)) return false;
4480 
4481   // Pick a representative declaration.
4482   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4483   assert(PrevDecl && "Expected a non-null Decl");
4484 
4485   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4486     return false;
4487 
4488   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4489     << IsUnion << Name;
4490   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4491 
4492   return true;
4493 }
4494 
4495 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4496 /// anonymous struct or union AnonRecord into the owning context Owner
4497 /// and scope S. This routine will be invoked just after we realize
4498 /// that an unnamed union or struct is actually an anonymous union or
4499 /// struct, e.g.,
4500 ///
4501 /// @code
4502 /// union {
4503 ///   int i;
4504 ///   float f;
4505 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4506 ///    // f into the surrounding scope.x
4507 /// @endcode
4508 ///
4509 /// This routine is recursive, injecting the names of nested anonymous
4510 /// structs/unions into the owning context and scope as well.
4511 static bool
4512 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4513                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4514                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4515   bool Invalid = false;
4516 
4517   // Look every FieldDecl and IndirectFieldDecl with a name.
4518   for (auto *D : AnonRecord->decls()) {
4519     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4520         cast<NamedDecl>(D)->getDeclName()) {
4521       ValueDecl *VD = cast<ValueDecl>(D);
4522       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4523                                        VD->getLocation(),
4524                                        AnonRecord->isUnion())) {
4525         // C++ [class.union]p2:
4526         //   The names of the members of an anonymous union shall be
4527         //   distinct from the names of any other entity in the
4528         //   scope in which the anonymous union is declared.
4529         Invalid = true;
4530       } else {
4531         // C++ [class.union]p2:
4532         //   For the purpose of name lookup, after the anonymous union
4533         //   definition, the members of the anonymous union are
4534         //   considered to have been defined in the scope in which the
4535         //   anonymous union is declared.
4536         unsigned OldChainingSize = Chaining.size();
4537         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4538           Chaining.append(IF->chain_begin(), IF->chain_end());
4539         else
4540           Chaining.push_back(VD);
4541 
4542         assert(Chaining.size() >= 2);
4543         NamedDecl **NamedChain =
4544           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4545         for (unsigned i = 0; i < Chaining.size(); i++)
4546           NamedChain[i] = Chaining[i];
4547 
4548         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4549             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4550             VD->getType(), {NamedChain, Chaining.size()});
4551 
4552         for (const auto *Attr : VD->attrs())
4553           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4554 
4555         IndirectField->setAccess(AS);
4556         IndirectField->setImplicit();
4557         SemaRef.PushOnScopeChains(IndirectField, S);
4558 
4559         // That includes picking up the appropriate access specifier.
4560         if (AS != AS_none) IndirectField->setAccess(AS);
4561 
4562         Chaining.resize(OldChainingSize);
4563       }
4564     }
4565   }
4566 
4567   return Invalid;
4568 }
4569 
4570 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4571 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4572 /// illegal input values are mapped to SC_None.
4573 static StorageClass
4574 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4575   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4576   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4577          "Parser allowed 'typedef' as storage class VarDecl.");
4578   switch (StorageClassSpec) {
4579   case DeclSpec::SCS_unspecified:    return SC_None;
4580   case DeclSpec::SCS_extern:
4581     if (DS.isExternInLinkageSpec())
4582       return SC_None;
4583     return SC_Extern;
4584   case DeclSpec::SCS_static:         return SC_Static;
4585   case DeclSpec::SCS_auto:           return SC_Auto;
4586   case DeclSpec::SCS_register:       return SC_Register;
4587   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4588     // Illegal SCSs map to None: error reporting is up to the caller.
4589   case DeclSpec::SCS_mutable:        // Fall through.
4590   case DeclSpec::SCS_typedef:        return SC_None;
4591   }
4592   llvm_unreachable("unknown storage class specifier");
4593 }
4594 
4595 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4596   assert(Record->hasInClassInitializer());
4597 
4598   for (const auto *I : Record->decls()) {
4599     const auto *FD = dyn_cast<FieldDecl>(I);
4600     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4601       FD = IFD->getAnonField();
4602     if (FD && FD->hasInClassInitializer())
4603       return FD->getLocation();
4604   }
4605 
4606   llvm_unreachable("couldn't find in-class initializer");
4607 }
4608 
4609 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4610                                       SourceLocation DefaultInitLoc) {
4611   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4612     return;
4613 
4614   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4615   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4616 }
4617 
4618 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4619                                       CXXRecordDecl *AnonUnion) {
4620   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4621     return;
4622 
4623   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4624 }
4625 
4626 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4627 /// anonymous structure or union. Anonymous unions are a C++ feature
4628 /// (C++ [class.union]) and a C11 feature; anonymous structures
4629 /// are a C11 feature and GNU C++ extension.
4630 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4631                                         AccessSpecifier AS,
4632                                         RecordDecl *Record,
4633                                         const PrintingPolicy &Policy) {
4634   DeclContext *Owner = Record->getDeclContext();
4635 
4636   // Diagnose whether this anonymous struct/union is an extension.
4637   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4638     Diag(Record->getLocation(), diag::ext_anonymous_union);
4639   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4640     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4641   else if (!Record->isUnion() && !getLangOpts().C11)
4642     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4643 
4644   // C and C++ require different kinds of checks for anonymous
4645   // structs/unions.
4646   bool Invalid = false;
4647   if (getLangOpts().CPlusPlus) {
4648     const char *PrevSpec = nullptr;
4649     unsigned DiagID;
4650     if (Record->isUnion()) {
4651       // C++ [class.union]p6:
4652       // C++17 [class.union.anon]p2:
4653       //   Anonymous unions declared in a named namespace or in the
4654       //   global namespace shall be declared static.
4655       DeclContext *OwnerScope = Owner->getRedeclContext();
4656       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4657           (OwnerScope->isTranslationUnit() ||
4658            (OwnerScope->isNamespace() &&
4659             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4660         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4661           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4662 
4663         // Recover by adding 'static'.
4664         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4665                                PrevSpec, DiagID, Policy);
4666       }
4667       // C++ [class.union]p6:
4668       //   A storage class is not allowed in a declaration of an
4669       //   anonymous union in a class scope.
4670       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4671                isa<RecordDecl>(Owner)) {
4672         Diag(DS.getStorageClassSpecLoc(),
4673              diag::err_anonymous_union_with_storage_spec)
4674           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4675 
4676         // Recover by removing the storage specifier.
4677         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4678                                SourceLocation(),
4679                                PrevSpec, DiagID, Context.getPrintingPolicy());
4680       }
4681     }
4682 
4683     // Ignore const/volatile/restrict qualifiers.
4684     if (DS.getTypeQualifiers()) {
4685       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4686         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4687           << Record->isUnion() << "const"
4688           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4689       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4690         Diag(DS.getVolatileSpecLoc(),
4691              diag::ext_anonymous_struct_union_qualified)
4692           << Record->isUnion() << "volatile"
4693           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4694       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4695         Diag(DS.getRestrictSpecLoc(),
4696              diag::ext_anonymous_struct_union_qualified)
4697           << Record->isUnion() << "restrict"
4698           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4699       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4700         Diag(DS.getAtomicSpecLoc(),
4701              diag::ext_anonymous_struct_union_qualified)
4702           << Record->isUnion() << "_Atomic"
4703           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4704       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4705         Diag(DS.getUnalignedSpecLoc(),
4706              diag::ext_anonymous_struct_union_qualified)
4707           << Record->isUnion() << "__unaligned"
4708           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4709 
4710       DS.ClearTypeQualifiers();
4711     }
4712 
4713     // C++ [class.union]p2:
4714     //   The member-specification of an anonymous union shall only
4715     //   define non-static data members. [Note: nested types and
4716     //   functions cannot be declared within an anonymous union. ]
4717     for (auto *Mem : Record->decls()) {
4718       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4719         // C++ [class.union]p3:
4720         //   An anonymous union shall not have private or protected
4721         //   members (clause 11).
4722         assert(FD->getAccess() != AS_none);
4723         if (FD->getAccess() != AS_public) {
4724           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4725             << Record->isUnion() << (FD->getAccess() == AS_protected);
4726           Invalid = true;
4727         }
4728 
4729         // C++ [class.union]p1
4730         //   An object of a class with a non-trivial constructor, a non-trivial
4731         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4732         //   assignment operator cannot be a member of a union, nor can an
4733         //   array of such objects.
4734         if (CheckNontrivialField(FD))
4735           Invalid = true;
4736       } else if (Mem->isImplicit()) {
4737         // Any implicit members are fine.
4738       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4739         // This is a type that showed up in an
4740         // elaborated-type-specifier inside the anonymous struct or
4741         // union, but which actually declares a type outside of the
4742         // anonymous struct or union. It's okay.
4743       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4744         if (!MemRecord->isAnonymousStructOrUnion() &&
4745             MemRecord->getDeclName()) {
4746           // Visual C++ allows type definition in anonymous struct or union.
4747           if (getLangOpts().MicrosoftExt)
4748             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4749               << Record->isUnion();
4750           else {
4751             // This is a nested type declaration.
4752             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4753               << Record->isUnion();
4754             Invalid = true;
4755           }
4756         } else {
4757           // This is an anonymous type definition within another anonymous type.
4758           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4759           // not part of standard C++.
4760           Diag(MemRecord->getLocation(),
4761                diag::ext_anonymous_record_with_anonymous_type)
4762             << Record->isUnion();
4763         }
4764       } else if (isa<AccessSpecDecl>(Mem)) {
4765         // Any access specifier is fine.
4766       } else if (isa<StaticAssertDecl>(Mem)) {
4767         // In C++1z, static_assert declarations are also fine.
4768       } else {
4769         // We have something that isn't a non-static data
4770         // member. Complain about it.
4771         unsigned DK = diag::err_anonymous_record_bad_member;
4772         if (isa<TypeDecl>(Mem))
4773           DK = diag::err_anonymous_record_with_type;
4774         else if (isa<FunctionDecl>(Mem))
4775           DK = diag::err_anonymous_record_with_function;
4776         else if (isa<VarDecl>(Mem))
4777           DK = diag::err_anonymous_record_with_static;
4778 
4779         // Visual C++ allows type definition in anonymous struct or union.
4780         if (getLangOpts().MicrosoftExt &&
4781             DK == diag::err_anonymous_record_with_type)
4782           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4783             << Record->isUnion();
4784         else {
4785           Diag(Mem->getLocation(), DK) << Record->isUnion();
4786           Invalid = true;
4787         }
4788       }
4789     }
4790 
4791     // C++11 [class.union]p8 (DR1460):
4792     //   At most one variant member of a union may have a
4793     //   brace-or-equal-initializer.
4794     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4795         Owner->isRecord())
4796       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4797                                 cast<CXXRecordDecl>(Record));
4798   }
4799 
4800   if (!Record->isUnion() && !Owner->isRecord()) {
4801     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4802       << getLangOpts().CPlusPlus;
4803     Invalid = true;
4804   }
4805 
4806   // Mock up a declarator.
4807   Declarator Dc(DS, DeclaratorContext::MemberContext);
4808   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4809   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4810 
4811   // Create a declaration for this anonymous struct/union.
4812   NamedDecl *Anon = nullptr;
4813   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4814     Anon = FieldDecl::Create(
4815         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4816         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4817         /*BitWidth=*/nullptr, /*Mutable=*/false,
4818         /*InitStyle=*/ICIS_NoInit);
4819     Anon->setAccess(AS);
4820     if (getLangOpts().CPlusPlus)
4821       FieldCollector->Add(cast<FieldDecl>(Anon));
4822   } else {
4823     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4824     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4825     if (SCSpec == DeclSpec::SCS_mutable) {
4826       // mutable can only appear on non-static class members, so it's always
4827       // an error here
4828       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4829       Invalid = true;
4830       SC = SC_None;
4831     }
4832 
4833     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4834                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4835                            Context.getTypeDeclType(Record), TInfo, SC);
4836 
4837     // Default-initialize the implicit variable. This initialization will be
4838     // trivial in almost all cases, except if a union member has an in-class
4839     // initializer:
4840     //   union { int n = 0; };
4841     ActOnUninitializedDecl(Anon);
4842   }
4843   Anon->setImplicit();
4844 
4845   // Mark this as an anonymous struct/union type.
4846   Record->setAnonymousStructOrUnion(true);
4847 
4848   // Add the anonymous struct/union object to the current
4849   // context. We'll be referencing this object when we refer to one of
4850   // its members.
4851   Owner->addDecl(Anon);
4852 
4853   // Inject the members of the anonymous struct/union into the owning
4854   // context and into the identifier resolver chain for name lookup
4855   // purposes.
4856   SmallVector<NamedDecl*, 2> Chain;
4857   Chain.push_back(Anon);
4858 
4859   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4860     Invalid = true;
4861 
4862   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4863     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4864       Decl *ManglingContextDecl;
4865       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4866               NewVD->getDeclContext(), ManglingContextDecl)) {
4867         Context.setManglingNumber(
4868             NewVD, MCtx->getManglingNumber(
4869                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4870         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4871       }
4872     }
4873   }
4874 
4875   if (Invalid)
4876     Anon->setInvalidDecl();
4877 
4878   return Anon;
4879 }
4880 
4881 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4882 /// Microsoft C anonymous structure.
4883 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4884 /// Example:
4885 ///
4886 /// struct A { int a; };
4887 /// struct B { struct A; int b; };
4888 ///
4889 /// void foo() {
4890 ///   B var;
4891 ///   var.a = 3;
4892 /// }
4893 ///
4894 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4895                                            RecordDecl *Record) {
4896   assert(Record && "expected a record!");
4897 
4898   // Mock up a declarator.
4899   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4900   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4901   assert(TInfo && "couldn't build declarator info for anonymous struct");
4902 
4903   auto *ParentDecl = cast<RecordDecl>(CurContext);
4904   QualType RecTy = Context.getTypeDeclType(Record);
4905 
4906   // Create a declaration for this anonymous struct.
4907   NamedDecl *Anon =
4908       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4909                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4910                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4911                         /*InitStyle=*/ICIS_NoInit);
4912   Anon->setImplicit();
4913 
4914   // Add the anonymous struct object to the current context.
4915   CurContext->addDecl(Anon);
4916 
4917   // Inject the members of the anonymous struct into the current
4918   // context and into the identifier resolver chain for name lookup
4919   // purposes.
4920   SmallVector<NamedDecl*, 2> Chain;
4921   Chain.push_back(Anon);
4922 
4923   RecordDecl *RecordDef = Record->getDefinition();
4924   if (RequireCompleteType(Anon->getLocation(), RecTy,
4925                           diag::err_field_incomplete) ||
4926       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4927                                           AS_none, Chain)) {
4928     Anon->setInvalidDecl();
4929     ParentDecl->setInvalidDecl();
4930   }
4931 
4932   return Anon;
4933 }
4934 
4935 /// GetNameForDeclarator - Determine the full declaration name for the
4936 /// given Declarator.
4937 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4938   return GetNameFromUnqualifiedId(D.getName());
4939 }
4940 
4941 /// Retrieves the declaration name from a parsed unqualified-id.
4942 DeclarationNameInfo
4943 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4944   DeclarationNameInfo NameInfo;
4945   NameInfo.setLoc(Name.StartLocation);
4946 
4947   switch (Name.getKind()) {
4948 
4949   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4950   case UnqualifiedIdKind::IK_Identifier:
4951     NameInfo.setName(Name.Identifier);
4952     return NameInfo;
4953 
4954   case UnqualifiedIdKind::IK_DeductionGuideName: {
4955     // C++ [temp.deduct.guide]p3:
4956     //   The simple-template-id shall name a class template specialization.
4957     //   The template-name shall be the same identifier as the template-name
4958     //   of the simple-template-id.
4959     // These together intend to imply that the template-name shall name a
4960     // class template.
4961     // FIXME: template<typename T> struct X {};
4962     //        template<typename T> using Y = X<T>;
4963     //        Y(int) -> Y<int>;
4964     //   satisfies these rules but does not name a class template.
4965     TemplateName TN = Name.TemplateName.get().get();
4966     auto *Template = TN.getAsTemplateDecl();
4967     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4968       Diag(Name.StartLocation,
4969            diag::err_deduction_guide_name_not_class_template)
4970         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4971       if (Template)
4972         Diag(Template->getLocation(), diag::note_template_decl_here);
4973       return DeclarationNameInfo();
4974     }
4975 
4976     NameInfo.setName(
4977         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4978     return NameInfo;
4979   }
4980 
4981   case UnqualifiedIdKind::IK_OperatorFunctionId:
4982     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4983                                            Name.OperatorFunctionId.Operator));
4984     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4985       = Name.OperatorFunctionId.SymbolLocations[0];
4986     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4987       = Name.EndLocation.getRawEncoding();
4988     return NameInfo;
4989 
4990   case UnqualifiedIdKind::IK_LiteralOperatorId:
4991     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4992                                                            Name.Identifier));
4993     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4994     return NameInfo;
4995 
4996   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4997     TypeSourceInfo *TInfo;
4998     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4999     if (Ty.isNull())
5000       return DeclarationNameInfo();
5001     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5002                                                Context.getCanonicalType(Ty)));
5003     NameInfo.setNamedTypeInfo(TInfo);
5004     return NameInfo;
5005   }
5006 
5007   case UnqualifiedIdKind::IK_ConstructorName: {
5008     TypeSourceInfo *TInfo;
5009     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5010     if (Ty.isNull())
5011       return DeclarationNameInfo();
5012     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5013                                               Context.getCanonicalType(Ty)));
5014     NameInfo.setNamedTypeInfo(TInfo);
5015     return NameInfo;
5016   }
5017 
5018   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5019     // In well-formed code, we can only have a constructor
5020     // template-id that refers to the current context, so go there
5021     // to find the actual type being constructed.
5022     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5023     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5024       return DeclarationNameInfo();
5025 
5026     // Determine the type of the class being constructed.
5027     QualType CurClassType = Context.getTypeDeclType(CurClass);
5028 
5029     // FIXME: Check two things: that the template-id names the same type as
5030     // CurClassType, and that the template-id does not occur when the name
5031     // was qualified.
5032 
5033     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5034                                     Context.getCanonicalType(CurClassType)));
5035     // FIXME: should we retrieve TypeSourceInfo?
5036     NameInfo.setNamedTypeInfo(nullptr);
5037     return NameInfo;
5038   }
5039 
5040   case UnqualifiedIdKind::IK_DestructorName: {
5041     TypeSourceInfo *TInfo;
5042     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5043     if (Ty.isNull())
5044       return DeclarationNameInfo();
5045     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5046                                               Context.getCanonicalType(Ty)));
5047     NameInfo.setNamedTypeInfo(TInfo);
5048     return NameInfo;
5049   }
5050 
5051   case UnqualifiedIdKind::IK_TemplateId: {
5052     TemplateName TName = Name.TemplateId->Template.get();
5053     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5054     return Context.getNameForTemplate(TName, TNameLoc);
5055   }
5056 
5057   } // switch (Name.getKind())
5058 
5059   llvm_unreachable("Unknown name kind");
5060 }
5061 
5062 static QualType getCoreType(QualType Ty) {
5063   do {
5064     if (Ty->isPointerType() || Ty->isReferenceType())
5065       Ty = Ty->getPointeeType();
5066     else if (Ty->isArrayType())
5067       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5068     else
5069       return Ty.withoutLocalFastQualifiers();
5070   } while (true);
5071 }
5072 
5073 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5074 /// and Definition have "nearly" matching parameters. This heuristic is
5075 /// used to improve diagnostics in the case where an out-of-line function
5076 /// definition doesn't match any declaration within the class or namespace.
5077 /// Also sets Params to the list of indices to the parameters that differ
5078 /// between the declaration and the definition. If hasSimilarParameters
5079 /// returns true and Params is empty, then all of the parameters match.
5080 static bool hasSimilarParameters(ASTContext &Context,
5081                                      FunctionDecl *Declaration,
5082                                      FunctionDecl *Definition,
5083                                      SmallVectorImpl<unsigned> &Params) {
5084   Params.clear();
5085   if (Declaration->param_size() != Definition->param_size())
5086     return false;
5087   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5088     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5089     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5090 
5091     // The parameter types are identical
5092     if (Context.hasSameType(DefParamTy, DeclParamTy))
5093       continue;
5094 
5095     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5096     QualType DefParamBaseTy = getCoreType(DefParamTy);
5097     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5098     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5099 
5100     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5101         (DeclTyName && DeclTyName == DefTyName))
5102       Params.push_back(Idx);
5103     else  // The two parameters aren't even close
5104       return false;
5105   }
5106 
5107   return true;
5108 }
5109 
5110 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5111 /// declarator needs to be rebuilt in the current instantiation.
5112 /// Any bits of declarator which appear before the name are valid for
5113 /// consideration here.  That's specifically the type in the decl spec
5114 /// and the base type in any member-pointer chunks.
5115 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5116                                                     DeclarationName Name) {
5117   // The types we specifically need to rebuild are:
5118   //   - typenames, typeofs, and decltypes
5119   //   - types which will become injected class names
5120   // Of course, we also need to rebuild any type referencing such a
5121   // type.  It's safest to just say "dependent", but we call out a
5122   // few cases here.
5123 
5124   DeclSpec &DS = D.getMutableDeclSpec();
5125   switch (DS.getTypeSpecType()) {
5126   case DeclSpec::TST_typename:
5127   case DeclSpec::TST_typeofType:
5128   case DeclSpec::TST_underlyingType:
5129   case DeclSpec::TST_atomic: {
5130     // Grab the type from the parser.
5131     TypeSourceInfo *TSI = nullptr;
5132     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5133     if (T.isNull() || !T->isDependentType()) break;
5134 
5135     // Make sure there's a type source info.  This isn't really much
5136     // of a waste; most dependent types should have type source info
5137     // attached already.
5138     if (!TSI)
5139       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5140 
5141     // Rebuild the type in the current instantiation.
5142     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5143     if (!TSI) return true;
5144 
5145     // Store the new type back in the decl spec.
5146     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5147     DS.UpdateTypeRep(LocType);
5148     break;
5149   }
5150 
5151   case DeclSpec::TST_decltype:
5152   case DeclSpec::TST_typeofExpr: {
5153     Expr *E = DS.getRepAsExpr();
5154     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5155     if (Result.isInvalid()) return true;
5156     DS.UpdateExprRep(Result.get());
5157     break;
5158   }
5159 
5160   default:
5161     // Nothing to do for these decl specs.
5162     break;
5163   }
5164 
5165   // It doesn't matter what order we do this in.
5166   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5167     DeclaratorChunk &Chunk = D.getTypeObject(I);
5168 
5169     // The only type information in the declarator which can come
5170     // before the declaration name is the base type of a member
5171     // pointer.
5172     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5173       continue;
5174 
5175     // Rebuild the scope specifier in-place.
5176     CXXScopeSpec &SS = Chunk.Mem.Scope();
5177     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5178       return true;
5179   }
5180 
5181   return false;
5182 }
5183 
5184 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5185   D.setFunctionDefinitionKind(FDK_Declaration);
5186   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5187 
5188   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5189       Dcl && Dcl->getDeclContext()->isFileContext())
5190     Dcl->setTopLevelDeclInObjCContainer();
5191 
5192   if (getLangOpts().OpenCL)
5193     setCurrentOpenCLExtensionForDecl(Dcl);
5194 
5195   return Dcl;
5196 }
5197 
5198 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5199 ///   If T is the name of a class, then each of the following shall have a
5200 ///   name different from T:
5201 ///     - every static data member of class T;
5202 ///     - every member function of class T
5203 ///     - every member of class T that is itself a type;
5204 /// \returns true if the declaration name violates these rules.
5205 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5206                                    DeclarationNameInfo NameInfo) {
5207   DeclarationName Name = NameInfo.getName();
5208 
5209   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5210   while (Record && Record->isAnonymousStructOrUnion())
5211     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5212   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5213     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5214     return true;
5215   }
5216 
5217   return false;
5218 }
5219 
5220 /// Diagnose a declaration whose declarator-id has the given
5221 /// nested-name-specifier.
5222 ///
5223 /// \param SS The nested-name-specifier of the declarator-id.
5224 ///
5225 /// \param DC The declaration context to which the nested-name-specifier
5226 /// resolves.
5227 ///
5228 /// \param Name The name of the entity being declared.
5229 ///
5230 /// \param Loc The location of the name of the entity being declared.
5231 ///
5232 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5233 /// we're declaring an explicit / partial specialization / instantiation.
5234 ///
5235 /// \returns true if we cannot safely recover from this error, false otherwise.
5236 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5237                                         DeclarationName Name,
5238                                         SourceLocation Loc, bool IsTemplateId) {
5239   DeclContext *Cur = CurContext;
5240   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5241     Cur = Cur->getParent();
5242 
5243   // If the user provided a superfluous scope specifier that refers back to the
5244   // class in which the entity is already declared, diagnose and ignore it.
5245   //
5246   // class X {
5247   //   void X::f();
5248   // };
5249   //
5250   // Note, it was once ill-formed to give redundant qualification in all
5251   // contexts, but that rule was removed by DR482.
5252   if (Cur->Equals(DC)) {
5253     if (Cur->isRecord()) {
5254       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5255                                       : diag::err_member_extra_qualification)
5256         << Name << FixItHint::CreateRemoval(SS.getRange());
5257       SS.clear();
5258     } else {
5259       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5260     }
5261     return false;
5262   }
5263 
5264   // Check whether the qualifying scope encloses the scope of the original
5265   // declaration. For a template-id, we perform the checks in
5266   // CheckTemplateSpecializationScope.
5267   if (!Cur->Encloses(DC) && !IsTemplateId) {
5268     if (Cur->isRecord())
5269       Diag(Loc, diag::err_member_qualification)
5270         << Name << SS.getRange();
5271     else if (isa<TranslationUnitDecl>(DC))
5272       Diag(Loc, diag::err_invalid_declarator_global_scope)
5273         << Name << SS.getRange();
5274     else if (isa<FunctionDecl>(Cur))
5275       Diag(Loc, diag::err_invalid_declarator_in_function)
5276         << Name << SS.getRange();
5277     else if (isa<BlockDecl>(Cur))
5278       Diag(Loc, diag::err_invalid_declarator_in_block)
5279         << Name << SS.getRange();
5280     else
5281       Diag(Loc, diag::err_invalid_declarator_scope)
5282       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5283 
5284     return true;
5285   }
5286 
5287   if (Cur->isRecord()) {
5288     // Cannot qualify members within a class.
5289     Diag(Loc, diag::err_member_qualification)
5290       << Name << SS.getRange();
5291     SS.clear();
5292 
5293     // C++ constructors and destructors with incorrect scopes can break
5294     // our AST invariants by having the wrong underlying types. If
5295     // that's the case, then drop this declaration entirely.
5296     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5297          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5298         !Context.hasSameType(Name.getCXXNameType(),
5299                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5300       return true;
5301 
5302     return false;
5303   }
5304 
5305   // C++11 [dcl.meaning]p1:
5306   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5307   //   not begin with a decltype-specifer"
5308   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5309   while (SpecLoc.getPrefix())
5310     SpecLoc = SpecLoc.getPrefix();
5311   if (dyn_cast_or_null<DecltypeType>(
5312         SpecLoc.getNestedNameSpecifier()->getAsType()))
5313     Diag(Loc, diag::err_decltype_in_declarator)
5314       << SpecLoc.getTypeLoc().getSourceRange();
5315 
5316   return false;
5317 }
5318 
5319 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5320                                   MultiTemplateParamsArg TemplateParamLists) {
5321   // TODO: consider using NameInfo for diagnostic.
5322   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5323   DeclarationName Name = NameInfo.getName();
5324 
5325   // All of these full declarators require an identifier.  If it doesn't have
5326   // one, the ParsedFreeStandingDeclSpec action should be used.
5327   if (D.isDecompositionDeclarator()) {
5328     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5329   } else if (!Name) {
5330     if (!D.isInvalidType())  // Reject this if we think it is valid.
5331       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5332           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5333     return nullptr;
5334   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5335     return nullptr;
5336 
5337   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5338   // we find one that is.
5339   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5340          (S->getFlags() & Scope::TemplateParamScope) != 0)
5341     S = S->getParent();
5342 
5343   DeclContext *DC = CurContext;
5344   if (D.getCXXScopeSpec().isInvalid())
5345     D.setInvalidType();
5346   else if (D.getCXXScopeSpec().isSet()) {
5347     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5348                                         UPPC_DeclarationQualifier))
5349       return nullptr;
5350 
5351     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5352     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5353     if (!DC || isa<EnumDecl>(DC)) {
5354       // If we could not compute the declaration context, it's because the
5355       // declaration context is dependent but does not refer to a class,
5356       // class template, or class template partial specialization. Complain
5357       // and return early, to avoid the coming semantic disaster.
5358       Diag(D.getIdentifierLoc(),
5359            diag::err_template_qualified_declarator_no_match)
5360         << D.getCXXScopeSpec().getScopeRep()
5361         << D.getCXXScopeSpec().getRange();
5362       return nullptr;
5363     }
5364     bool IsDependentContext = DC->isDependentContext();
5365 
5366     if (!IsDependentContext &&
5367         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5368       return nullptr;
5369 
5370     // If a class is incomplete, do not parse entities inside it.
5371     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5372       Diag(D.getIdentifierLoc(),
5373            diag::err_member_def_undefined_record)
5374         << Name << DC << D.getCXXScopeSpec().getRange();
5375       return nullptr;
5376     }
5377     if (!D.getDeclSpec().isFriendSpecified()) {
5378       if (diagnoseQualifiedDeclaration(
5379               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5380               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5381         if (DC->isRecord())
5382           return nullptr;
5383 
5384         D.setInvalidType();
5385       }
5386     }
5387 
5388     // Check whether we need to rebuild the type of the given
5389     // declaration in the current instantiation.
5390     if (EnteringContext && IsDependentContext &&
5391         TemplateParamLists.size() != 0) {
5392       ContextRAII SavedContext(*this, DC);
5393       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5394         D.setInvalidType();
5395     }
5396   }
5397 
5398   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5399   QualType R = TInfo->getType();
5400 
5401   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5402                                       UPPC_DeclarationType))
5403     D.setInvalidType();
5404 
5405   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5406                         forRedeclarationInCurContext());
5407 
5408   // See if this is a redefinition of a variable in the same scope.
5409   if (!D.getCXXScopeSpec().isSet()) {
5410     bool IsLinkageLookup = false;
5411     bool CreateBuiltins = false;
5412 
5413     // If the declaration we're planning to build will be a function
5414     // or object with linkage, then look for another declaration with
5415     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5416     //
5417     // If the declaration we're planning to build will be declared with
5418     // external linkage in the translation unit, create any builtin with
5419     // the same name.
5420     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5421       /* Do nothing*/;
5422     else if (CurContext->isFunctionOrMethod() &&
5423              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5424               R->isFunctionType())) {
5425       IsLinkageLookup = true;
5426       CreateBuiltins =
5427           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5428     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5429                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5430       CreateBuiltins = true;
5431 
5432     if (IsLinkageLookup) {
5433       Previous.clear(LookupRedeclarationWithLinkage);
5434       Previous.setRedeclarationKind(ForExternalRedeclaration);
5435     }
5436 
5437     LookupName(Previous, S, CreateBuiltins);
5438   } else { // Something like "int foo::x;"
5439     LookupQualifiedName(Previous, DC);
5440 
5441     // C++ [dcl.meaning]p1:
5442     //   When the declarator-id is qualified, the declaration shall refer to a
5443     //  previously declared member of the class or namespace to which the
5444     //  qualifier refers (or, in the case of a namespace, of an element of the
5445     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5446     //  thereof; [...]
5447     //
5448     // Note that we already checked the context above, and that we do not have
5449     // enough information to make sure that Previous contains the declaration
5450     // we want to match. For example, given:
5451     //
5452     //   class X {
5453     //     void f();
5454     //     void f(float);
5455     //   };
5456     //
5457     //   void X::f(int) { } // ill-formed
5458     //
5459     // In this case, Previous will point to the overload set
5460     // containing the two f's declared in X, but neither of them
5461     // matches.
5462 
5463     // C++ [dcl.meaning]p1:
5464     //   [...] the member shall not merely have been introduced by a
5465     //   using-declaration in the scope of the class or namespace nominated by
5466     //   the nested-name-specifier of the declarator-id.
5467     RemoveUsingDecls(Previous);
5468   }
5469 
5470   if (Previous.isSingleResult() &&
5471       Previous.getFoundDecl()->isTemplateParameter()) {
5472     // Maybe we will complain about the shadowed template parameter.
5473     if (!D.isInvalidType())
5474       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5475                                       Previous.getFoundDecl());
5476 
5477     // Just pretend that we didn't see the previous declaration.
5478     Previous.clear();
5479   }
5480 
5481   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5482     // Forget that the previous declaration is the injected-class-name.
5483     Previous.clear();
5484 
5485   // In C++, the previous declaration we find might be a tag type
5486   // (class or enum). In this case, the new declaration will hide the
5487   // tag type. Note that this applies to functions, function templates, and
5488   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5489   if (Previous.isSingleTagDecl() &&
5490       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5491       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5492     Previous.clear();
5493 
5494   // Check that there are no default arguments other than in the parameters
5495   // of a function declaration (C++ only).
5496   if (getLangOpts().CPlusPlus)
5497     CheckExtraCXXDefaultArguments(D);
5498 
5499   NamedDecl *New;
5500 
5501   bool AddToScope = true;
5502   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5503     if (TemplateParamLists.size()) {
5504       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5505       return nullptr;
5506     }
5507 
5508     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5509   } else if (R->isFunctionType()) {
5510     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5511                                   TemplateParamLists,
5512                                   AddToScope);
5513   } else {
5514     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5515                                   AddToScope);
5516   }
5517 
5518   if (!New)
5519     return nullptr;
5520 
5521   // If this has an identifier and is not a function template specialization,
5522   // add it to the scope stack.
5523   if (New->getDeclName() && AddToScope) {
5524     // Only make a locally-scoped extern declaration visible if it is the first
5525     // declaration of this entity. Qualified lookup for such an entity should
5526     // only find this declaration if there is no visible declaration of it.
5527     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5528     PushOnScopeChains(New, S, AddToContext);
5529     if (!AddToContext)
5530       CurContext->addHiddenDecl(New);
5531   }
5532 
5533   if (isInOpenMPDeclareTargetContext())
5534     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5535 
5536   return New;
5537 }
5538 
5539 /// Helper method to turn variable array types into constant array
5540 /// types in certain situations which would otherwise be errors (for
5541 /// GCC compatibility).
5542 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5543                                                     ASTContext &Context,
5544                                                     bool &SizeIsNegative,
5545                                                     llvm::APSInt &Oversized) {
5546   // This method tries to turn a variable array into a constant
5547   // array even when the size isn't an ICE.  This is necessary
5548   // for compatibility with code that depends on gcc's buggy
5549   // constant expression folding, like struct {char x[(int)(char*)2];}
5550   SizeIsNegative = false;
5551   Oversized = 0;
5552 
5553   if (T->isDependentType())
5554     return QualType();
5555 
5556   QualifierCollector Qs;
5557   const Type *Ty = Qs.strip(T);
5558 
5559   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5560     QualType Pointee = PTy->getPointeeType();
5561     QualType FixedType =
5562         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5563                                             Oversized);
5564     if (FixedType.isNull()) return FixedType;
5565     FixedType = Context.getPointerType(FixedType);
5566     return Qs.apply(Context, FixedType);
5567   }
5568   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5569     QualType Inner = PTy->getInnerType();
5570     QualType FixedType =
5571         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5572                                             Oversized);
5573     if (FixedType.isNull()) return FixedType;
5574     FixedType = Context.getParenType(FixedType);
5575     return Qs.apply(Context, FixedType);
5576   }
5577 
5578   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5579   if (!VLATy)
5580     return QualType();
5581   // FIXME: We should probably handle this case
5582   if (VLATy->getElementType()->isVariablyModifiedType())
5583     return QualType();
5584 
5585   llvm::APSInt Res;
5586   if (!VLATy->getSizeExpr() ||
5587       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5588     return QualType();
5589 
5590   // Check whether the array size is negative.
5591   if (Res.isSigned() && Res.isNegative()) {
5592     SizeIsNegative = true;
5593     return QualType();
5594   }
5595 
5596   // Check whether the array is too large to be addressed.
5597   unsigned ActiveSizeBits
5598     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5599                                               Res);
5600   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5601     Oversized = Res;
5602     return QualType();
5603   }
5604 
5605   return Context.getConstantArrayType(VLATy->getElementType(),
5606                                       Res, ArrayType::Normal, 0);
5607 }
5608 
5609 static void
5610 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5611   SrcTL = SrcTL.getUnqualifiedLoc();
5612   DstTL = DstTL.getUnqualifiedLoc();
5613   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5614     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5615     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5616                                       DstPTL.getPointeeLoc());
5617     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5618     return;
5619   }
5620   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5621     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5622     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5623                                       DstPTL.getInnerLoc());
5624     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5625     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5626     return;
5627   }
5628   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5629   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5630   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5631   TypeLoc DstElemTL = DstATL.getElementLoc();
5632   DstElemTL.initializeFullCopy(SrcElemTL);
5633   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5634   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5635   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5636 }
5637 
5638 /// Helper method to turn variable array types into constant array
5639 /// types in certain situations which would otherwise be errors (for
5640 /// GCC compatibility).
5641 static TypeSourceInfo*
5642 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5643                                               ASTContext &Context,
5644                                               bool &SizeIsNegative,
5645                                               llvm::APSInt &Oversized) {
5646   QualType FixedTy
5647     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5648                                           SizeIsNegative, Oversized);
5649   if (FixedTy.isNull())
5650     return nullptr;
5651   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5652   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5653                                     FixedTInfo->getTypeLoc());
5654   return FixedTInfo;
5655 }
5656 
5657 /// Register the given locally-scoped extern "C" declaration so
5658 /// that it can be found later for redeclarations. We include any extern "C"
5659 /// declaration that is not visible in the translation unit here, not just
5660 /// function-scope declarations.
5661 void
5662 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5663   if (!getLangOpts().CPlusPlus &&
5664       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5665     // Don't need to track declarations in the TU in C.
5666     return;
5667 
5668   // Note that we have a locally-scoped external with this name.
5669   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5670 }
5671 
5672 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5673   // FIXME: We can have multiple results via __attribute__((overloadable)).
5674   auto Result = Context.getExternCContextDecl()->lookup(Name);
5675   return Result.empty() ? nullptr : *Result.begin();
5676 }
5677 
5678 /// Diagnose function specifiers on a declaration of an identifier that
5679 /// does not identify a function.
5680 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5681   // FIXME: We should probably indicate the identifier in question to avoid
5682   // confusion for constructs like "virtual int a(), b;"
5683   if (DS.isVirtualSpecified())
5684     Diag(DS.getVirtualSpecLoc(),
5685          diag::err_virtual_non_function);
5686 
5687   if (DS.isExplicitSpecified())
5688     Diag(DS.getExplicitSpecLoc(),
5689          diag::err_explicit_non_function);
5690 
5691   if (DS.isNoreturnSpecified())
5692     Diag(DS.getNoreturnSpecLoc(),
5693          diag::err_noreturn_non_function);
5694 }
5695 
5696 NamedDecl*
5697 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5698                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5699   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5700   if (D.getCXXScopeSpec().isSet()) {
5701     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5702       << D.getCXXScopeSpec().getRange();
5703     D.setInvalidType();
5704     // Pretend we didn't see the scope specifier.
5705     DC = CurContext;
5706     Previous.clear();
5707   }
5708 
5709   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5710 
5711   if (D.getDeclSpec().isInlineSpecified())
5712     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5713         << getLangOpts().CPlusPlus17;
5714   if (D.getDeclSpec().isConstexprSpecified())
5715     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5716       << 1;
5717 
5718   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5719     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5720       Diag(D.getName().StartLocation,
5721            diag::err_deduction_guide_invalid_specifier)
5722           << "typedef";
5723     else
5724       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5725           << D.getName().getSourceRange();
5726     return nullptr;
5727   }
5728 
5729   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5730   if (!NewTD) return nullptr;
5731 
5732   // Handle attributes prior to checking for duplicates in MergeVarDecl
5733   ProcessDeclAttributes(S, NewTD, D);
5734 
5735   CheckTypedefForVariablyModifiedType(S, NewTD);
5736 
5737   bool Redeclaration = D.isRedeclaration();
5738   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5739   D.setRedeclaration(Redeclaration);
5740   return ND;
5741 }
5742 
5743 void
5744 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5745   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5746   // then it shall have block scope.
5747   // Note that variably modified types must be fixed before merging the decl so
5748   // that redeclarations will match.
5749   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5750   QualType T = TInfo->getType();
5751   if (T->isVariablyModifiedType()) {
5752     setFunctionHasBranchProtectedScope();
5753 
5754     if (S->getFnParent() == nullptr) {
5755       bool SizeIsNegative;
5756       llvm::APSInt Oversized;
5757       TypeSourceInfo *FixedTInfo =
5758         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5759                                                       SizeIsNegative,
5760                                                       Oversized);
5761       if (FixedTInfo) {
5762         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5763         NewTD->setTypeSourceInfo(FixedTInfo);
5764       } else {
5765         if (SizeIsNegative)
5766           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5767         else if (T->isVariableArrayType())
5768           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5769         else if (Oversized.getBoolValue())
5770           Diag(NewTD->getLocation(), diag::err_array_too_large)
5771             << Oversized.toString(10);
5772         else
5773           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5774         NewTD->setInvalidDecl();
5775       }
5776     }
5777   }
5778 }
5779 
5780 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5781 /// declares a typedef-name, either using the 'typedef' type specifier or via
5782 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5783 NamedDecl*
5784 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5785                            LookupResult &Previous, bool &Redeclaration) {
5786 
5787   // Find the shadowed declaration before filtering for scope.
5788   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5789 
5790   // Merge the decl with the existing one if appropriate. If the decl is
5791   // in an outer scope, it isn't the same thing.
5792   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5793                        /*AllowInlineNamespace*/false);
5794   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5795   if (!Previous.empty()) {
5796     Redeclaration = true;
5797     MergeTypedefNameDecl(S, NewTD, Previous);
5798   }
5799 
5800   if (ShadowedDecl && !Redeclaration)
5801     CheckShadow(NewTD, ShadowedDecl, Previous);
5802 
5803   // If this is the C FILE type, notify the AST context.
5804   if (IdentifierInfo *II = NewTD->getIdentifier())
5805     if (!NewTD->isInvalidDecl() &&
5806         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5807       if (II->isStr("FILE"))
5808         Context.setFILEDecl(NewTD);
5809       else if (II->isStr("jmp_buf"))
5810         Context.setjmp_bufDecl(NewTD);
5811       else if (II->isStr("sigjmp_buf"))
5812         Context.setsigjmp_bufDecl(NewTD);
5813       else if (II->isStr("ucontext_t"))
5814         Context.setucontext_tDecl(NewTD);
5815     }
5816 
5817   return NewTD;
5818 }
5819 
5820 /// Determines whether the given declaration is an out-of-scope
5821 /// previous declaration.
5822 ///
5823 /// This routine should be invoked when name lookup has found a
5824 /// previous declaration (PrevDecl) that is not in the scope where a
5825 /// new declaration by the same name is being introduced. If the new
5826 /// declaration occurs in a local scope, previous declarations with
5827 /// linkage may still be considered previous declarations (C99
5828 /// 6.2.2p4-5, C++ [basic.link]p6).
5829 ///
5830 /// \param PrevDecl the previous declaration found by name
5831 /// lookup
5832 ///
5833 /// \param DC the context in which the new declaration is being
5834 /// declared.
5835 ///
5836 /// \returns true if PrevDecl is an out-of-scope previous declaration
5837 /// for a new delcaration with the same name.
5838 static bool
5839 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5840                                 ASTContext &Context) {
5841   if (!PrevDecl)
5842     return false;
5843 
5844   if (!PrevDecl->hasLinkage())
5845     return false;
5846 
5847   if (Context.getLangOpts().CPlusPlus) {
5848     // C++ [basic.link]p6:
5849     //   If there is a visible declaration of an entity with linkage
5850     //   having the same name and type, ignoring entities declared
5851     //   outside the innermost enclosing namespace scope, the block
5852     //   scope declaration declares that same entity and receives the
5853     //   linkage of the previous declaration.
5854     DeclContext *OuterContext = DC->getRedeclContext();
5855     if (!OuterContext->isFunctionOrMethod())
5856       // This rule only applies to block-scope declarations.
5857       return false;
5858 
5859     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5860     if (PrevOuterContext->isRecord())
5861       // We found a member function: ignore it.
5862       return false;
5863 
5864     // Find the innermost enclosing namespace for the new and
5865     // previous declarations.
5866     OuterContext = OuterContext->getEnclosingNamespaceContext();
5867     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5868 
5869     // The previous declaration is in a different namespace, so it
5870     // isn't the same function.
5871     if (!OuterContext->Equals(PrevOuterContext))
5872       return false;
5873   }
5874 
5875   return true;
5876 }
5877 
5878 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5879   CXXScopeSpec &SS = D.getCXXScopeSpec();
5880   if (!SS.isSet()) return;
5881   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5882 }
5883 
5884 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5885   QualType type = decl->getType();
5886   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5887   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5888     // Various kinds of declaration aren't allowed to be __autoreleasing.
5889     unsigned kind = -1U;
5890     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5891       if (var->hasAttr<BlocksAttr>())
5892         kind = 0; // __block
5893       else if (!var->hasLocalStorage())
5894         kind = 1; // global
5895     } else if (isa<ObjCIvarDecl>(decl)) {
5896       kind = 3; // ivar
5897     } else if (isa<FieldDecl>(decl)) {
5898       kind = 2; // field
5899     }
5900 
5901     if (kind != -1U) {
5902       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5903         << kind;
5904     }
5905   } else if (lifetime == Qualifiers::OCL_None) {
5906     // Try to infer lifetime.
5907     if (!type->isObjCLifetimeType())
5908       return false;
5909 
5910     lifetime = type->getObjCARCImplicitLifetime();
5911     type = Context.getLifetimeQualifiedType(type, lifetime);
5912     decl->setType(type);
5913   }
5914 
5915   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5916     // Thread-local variables cannot have lifetime.
5917     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5918         var->getTLSKind()) {
5919       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5920         << var->getType();
5921       return true;
5922     }
5923   }
5924 
5925   return false;
5926 }
5927 
5928 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5929   // Ensure that an auto decl is deduced otherwise the checks below might cache
5930   // the wrong linkage.
5931   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5932 
5933   // 'weak' only applies to declarations with external linkage.
5934   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5935     if (!ND.isExternallyVisible()) {
5936       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5937       ND.dropAttr<WeakAttr>();
5938     }
5939   }
5940   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5941     if (ND.isExternallyVisible()) {
5942       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5943       ND.dropAttr<WeakRefAttr>();
5944       ND.dropAttr<AliasAttr>();
5945     }
5946   }
5947 
5948   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5949     if (VD->hasInit()) {
5950       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5951         assert(VD->isThisDeclarationADefinition() &&
5952                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5953         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5954         VD->dropAttr<AliasAttr>();
5955       }
5956     }
5957   }
5958 
5959   // 'selectany' only applies to externally visible variable declarations.
5960   // It does not apply to functions.
5961   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5962     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5963       S.Diag(Attr->getLocation(),
5964              diag::err_attribute_selectany_non_extern_data);
5965       ND.dropAttr<SelectAnyAttr>();
5966     }
5967   }
5968 
5969   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5970     // dll attributes require external linkage. Static locals may have external
5971     // linkage but still cannot be explicitly imported or exported.
5972     auto *VD = dyn_cast<VarDecl>(&ND);
5973     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5974       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5975         << &ND << Attr;
5976       ND.setInvalidDecl();
5977     }
5978   }
5979 
5980   // Virtual functions cannot be marked as 'notail'.
5981   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5982     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5983       if (MD->isVirtual()) {
5984         S.Diag(ND.getLocation(),
5985                diag::err_invalid_attribute_on_virtual_function)
5986             << Attr;
5987         ND.dropAttr<NotTailCalledAttr>();
5988       }
5989 
5990   // Check the attributes on the function type, if any.
5991   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
5992     // Don't declare this variable in the second operand of the for-statement;
5993     // GCC miscompiles that by ending its lifetime before evaluating the
5994     // third operand. See gcc.gnu.org/PR86769.
5995     AttributedTypeLoc ATL;
5996     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
5997          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
5998          TL = ATL.getModifiedLoc()) {
5999       // The [[lifetimebound]] attribute can be applied to the implicit object
6000       // parameter of a non-static member function (other than a ctor or dtor)
6001       // by applying it to the function type.
6002       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6003         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6004         if (!MD || MD->isStatic()) {
6005           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6006               << !MD << A->getRange();
6007         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6008           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6009               << isa<CXXDestructorDecl>(MD) << A->getRange();
6010         }
6011       }
6012     }
6013   }
6014 }
6015 
6016 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6017                                            NamedDecl *NewDecl,
6018                                            bool IsSpecialization,
6019                                            bool IsDefinition) {
6020   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6021     return;
6022 
6023   bool IsTemplate = false;
6024   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6025     OldDecl = OldTD->getTemplatedDecl();
6026     IsTemplate = true;
6027     if (!IsSpecialization)
6028       IsDefinition = false;
6029   }
6030   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6031     NewDecl = NewTD->getTemplatedDecl();
6032     IsTemplate = true;
6033   }
6034 
6035   if (!OldDecl || !NewDecl)
6036     return;
6037 
6038   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6039   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6040   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6041   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6042 
6043   // dllimport and dllexport are inheritable attributes so we have to exclude
6044   // inherited attribute instances.
6045   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6046                     (NewExportAttr && !NewExportAttr->isInherited());
6047 
6048   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6049   // the only exception being explicit specializations.
6050   // Implicitly generated declarations are also excluded for now because there
6051   // is no other way to switch these to use dllimport or dllexport.
6052   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6053 
6054   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6055     // Allow with a warning for free functions and global variables.
6056     bool JustWarn = false;
6057     if (!OldDecl->isCXXClassMember()) {
6058       auto *VD = dyn_cast<VarDecl>(OldDecl);
6059       if (VD && !VD->getDescribedVarTemplate())
6060         JustWarn = true;
6061       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6062       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6063         JustWarn = true;
6064     }
6065 
6066     // We cannot change a declaration that's been used because IR has already
6067     // been emitted. Dllimported functions will still work though (modulo
6068     // address equality) as they can use the thunk.
6069     if (OldDecl->isUsed())
6070       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6071         JustWarn = false;
6072 
6073     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6074                                : diag::err_attribute_dll_redeclaration;
6075     S.Diag(NewDecl->getLocation(), DiagID)
6076         << NewDecl
6077         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6078     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6079     if (!JustWarn) {
6080       NewDecl->setInvalidDecl();
6081       return;
6082     }
6083   }
6084 
6085   // A redeclaration is not allowed to drop a dllimport attribute, the only
6086   // exceptions being inline function definitions (except for function
6087   // templates), local extern declarations, qualified friend declarations or
6088   // special MSVC extension: in the last case, the declaration is treated as if
6089   // it were marked dllexport.
6090   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6091   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6092   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6093     // Ignore static data because out-of-line definitions are diagnosed
6094     // separately.
6095     IsStaticDataMember = VD->isStaticDataMember();
6096     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6097                    VarDecl::DeclarationOnly;
6098   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6099     IsInline = FD->isInlined();
6100     IsQualifiedFriend = FD->getQualifier() &&
6101                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6102   }
6103 
6104   if (OldImportAttr && !HasNewAttr &&
6105       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6106       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6107     if (IsMicrosoft && IsDefinition) {
6108       S.Diag(NewDecl->getLocation(),
6109              diag::warn_redeclaration_without_import_attribute)
6110           << NewDecl;
6111       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6112       NewDecl->dropAttr<DLLImportAttr>();
6113       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6114           NewImportAttr->getRange(), S.Context,
6115           NewImportAttr->getSpellingListIndex()));
6116     } else {
6117       S.Diag(NewDecl->getLocation(),
6118              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6119           << NewDecl << OldImportAttr;
6120       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6121       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6122       OldDecl->dropAttr<DLLImportAttr>();
6123       NewDecl->dropAttr<DLLImportAttr>();
6124     }
6125   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6126     // In MinGW, seeing a function declared inline drops the dllimport
6127     // attribute.
6128     OldDecl->dropAttr<DLLImportAttr>();
6129     NewDecl->dropAttr<DLLImportAttr>();
6130     S.Diag(NewDecl->getLocation(),
6131            diag::warn_dllimport_dropped_from_inline_function)
6132         << NewDecl << OldImportAttr;
6133   }
6134 
6135   // A specialization of a class template member function is processed here
6136   // since it's a redeclaration. If the parent class is dllexport, the
6137   // specialization inherits that attribute. This doesn't happen automatically
6138   // since the parent class isn't instantiated until later.
6139   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6140     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6141         !NewImportAttr && !NewExportAttr) {
6142       if (const DLLExportAttr *ParentExportAttr =
6143               MD->getParent()->getAttr<DLLExportAttr>()) {
6144         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6145         NewAttr->setInherited(true);
6146         NewDecl->addAttr(NewAttr);
6147       }
6148     }
6149   }
6150 }
6151 
6152 /// Given that we are within the definition of the given function,
6153 /// will that definition behave like C99's 'inline', where the
6154 /// definition is discarded except for optimization purposes?
6155 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6156   // Try to avoid calling GetGVALinkageForFunction.
6157 
6158   // All cases of this require the 'inline' keyword.
6159   if (!FD->isInlined()) return false;
6160 
6161   // This is only possible in C++ with the gnu_inline attribute.
6162   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6163     return false;
6164 
6165   // Okay, go ahead and call the relatively-more-expensive function.
6166   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6167 }
6168 
6169 /// Determine whether a variable is extern "C" prior to attaching
6170 /// an initializer. We can't just call isExternC() here, because that
6171 /// will also compute and cache whether the declaration is externally
6172 /// visible, which might change when we attach the initializer.
6173 ///
6174 /// This can only be used if the declaration is known to not be a
6175 /// redeclaration of an internal linkage declaration.
6176 ///
6177 /// For instance:
6178 ///
6179 ///   auto x = []{};
6180 ///
6181 /// Attaching the initializer here makes this declaration not externally
6182 /// visible, because its type has internal linkage.
6183 ///
6184 /// FIXME: This is a hack.
6185 template<typename T>
6186 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6187   if (S.getLangOpts().CPlusPlus) {
6188     // In C++, the overloadable attribute negates the effects of extern "C".
6189     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6190       return false;
6191 
6192     // So do CUDA's host/device attributes.
6193     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6194                                  D->template hasAttr<CUDAHostAttr>()))
6195       return false;
6196   }
6197   return D->isExternC();
6198 }
6199 
6200 static bool shouldConsiderLinkage(const VarDecl *VD) {
6201   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6202   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6203     return VD->hasExternalStorage();
6204   if (DC->isFileContext())
6205     return true;
6206   if (DC->isRecord())
6207     return false;
6208   llvm_unreachable("Unexpected context");
6209 }
6210 
6211 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6212   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6213   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6214       isa<OMPDeclareReductionDecl>(DC))
6215     return true;
6216   if (DC->isRecord())
6217     return false;
6218   llvm_unreachable("Unexpected context");
6219 }
6220 
6221 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6222                           ParsedAttr::Kind Kind) {
6223   // Check decl attributes on the DeclSpec.
6224   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6225     return true;
6226 
6227   // Walk the declarator structure, checking decl attributes that were in a type
6228   // position to the decl itself.
6229   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6230     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6231       return true;
6232   }
6233 
6234   // Finally, check attributes on the decl itself.
6235   return PD.getAttributes().hasAttribute(Kind);
6236 }
6237 
6238 /// Adjust the \c DeclContext for a function or variable that might be a
6239 /// function-local external declaration.
6240 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6241   if (!DC->isFunctionOrMethod())
6242     return false;
6243 
6244   // If this is a local extern function or variable declared within a function
6245   // template, don't add it into the enclosing namespace scope until it is
6246   // instantiated; it might have a dependent type right now.
6247   if (DC->isDependentContext())
6248     return true;
6249 
6250   // C++11 [basic.link]p7:
6251   //   When a block scope declaration of an entity with linkage is not found to
6252   //   refer to some other declaration, then that entity is a member of the
6253   //   innermost enclosing namespace.
6254   //
6255   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6256   // semantically-enclosing namespace, not a lexically-enclosing one.
6257   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6258     DC = DC->getParent();
6259   return true;
6260 }
6261 
6262 /// Returns true if given declaration has external C language linkage.
6263 static bool isDeclExternC(const Decl *D) {
6264   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6265     return FD->isExternC();
6266   if (const auto *VD = dyn_cast<VarDecl>(D))
6267     return VD->isExternC();
6268 
6269   llvm_unreachable("Unknown type of decl!");
6270 }
6271 
6272 NamedDecl *Sema::ActOnVariableDeclarator(
6273     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6274     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6275     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6276   QualType R = TInfo->getType();
6277   DeclarationName Name = GetNameForDeclarator(D).getName();
6278 
6279   IdentifierInfo *II = Name.getAsIdentifierInfo();
6280 
6281   if (D.isDecompositionDeclarator()) {
6282     // Take the name of the first declarator as our name for diagnostic
6283     // purposes.
6284     auto &Decomp = D.getDecompositionDeclarator();
6285     if (!Decomp.bindings().empty()) {
6286       II = Decomp.bindings()[0].Name;
6287       Name = II;
6288     }
6289   } else if (!II) {
6290     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6291     return nullptr;
6292   }
6293 
6294   if (getLangOpts().OpenCL) {
6295     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6296     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6297     // argument.
6298     if (R->isImageType() || R->isPipeType()) {
6299       Diag(D.getIdentifierLoc(),
6300            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6301           << R;
6302       D.setInvalidType();
6303       return nullptr;
6304     }
6305 
6306     // OpenCL v1.2 s6.9.r:
6307     // The event type cannot be used to declare a program scope variable.
6308     // OpenCL v2.0 s6.9.q:
6309     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6310     if (NULL == S->getParent()) {
6311       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6312         Diag(D.getIdentifierLoc(),
6313              diag::err_invalid_type_for_program_scope_var) << R;
6314         D.setInvalidType();
6315         return nullptr;
6316       }
6317     }
6318 
6319     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6320     QualType NR = R;
6321     while (NR->isPointerType()) {
6322       if (NR->isFunctionPointerType()) {
6323         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6324         D.setInvalidType();
6325         break;
6326       }
6327       NR = NR->getPointeeType();
6328     }
6329 
6330     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6331       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6332       // half array type (unless the cl_khr_fp16 extension is enabled).
6333       if (Context.getBaseElementType(R)->isHalfType()) {
6334         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6335         D.setInvalidType();
6336       }
6337     }
6338 
6339     if (R->isSamplerT()) {
6340       // OpenCL v1.2 s6.9.b p4:
6341       // The sampler type cannot be used with the __local and __global address
6342       // space qualifiers.
6343       if (R.getAddressSpace() == LangAS::opencl_local ||
6344           R.getAddressSpace() == LangAS::opencl_global) {
6345         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6346       }
6347 
6348       // OpenCL v1.2 s6.12.14.1:
6349       // A global sampler must be declared with either the constant address
6350       // space qualifier or with the const qualifier.
6351       if (DC->isTranslationUnit() &&
6352           !(R.getAddressSpace() == LangAS::opencl_constant ||
6353           R.isConstQualified())) {
6354         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6355         D.setInvalidType();
6356       }
6357     }
6358 
6359     // OpenCL v1.2 s6.9.r:
6360     // The event type cannot be used with the __local, __constant and __global
6361     // address space qualifiers.
6362     if (R->isEventT()) {
6363       if (R.getAddressSpace() != LangAS::opencl_private) {
6364         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6365         D.setInvalidType();
6366       }
6367     }
6368 
6369     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6370     // supported.  OpenCL C does not support thread_local either, and
6371     // also reject all other thread storage class specifiers.
6372     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6373     if (TSC != TSCS_unspecified) {
6374       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6375       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6376            diag::err_opencl_unknown_type_specifier)
6377           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6378           << DeclSpec::getSpecifierName(TSC) << 1;
6379       D.setInvalidType();
6380       return nullptr;
6381     }
6382   }
6383 
6384   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6385   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6386 
6387   // dllimport globals without explicit storage class are treated as extern. We
6388   // have to change the storage class this early to get the right DeclContext.
6389   if (SC == SC_None && !DC->isRecord() &&
6390       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6391       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6392     SC = SC_Extern;
6393 
6394   DeclContext *OriginalDC = DC;
6395   bool IsLocalExternDecl = SC == SC_Extern &&
6396                            adjustContextForLocalExternDecl(DC);
6397 
6398   if (SCSpec == DeclSpec::SCS_mutable) {
6399     // mutable can only appear on non-static class members, so it's always
6400     // an error here
6401     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6402     D.setInvalidType();
6403     SC = SC_None;
6404   }
6405 
6406   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6407       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6408                               D.getDeclSpec().getStorageClassSpecLoc())) {
6409     // In C++11, the 'register' storage class specifier is deprecated.
6410     // Suppress the warning in system macros, it's used in macros in some
6411     // popular C system headers, such as in glibc's htonl() macro.
6412     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6413          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6414                                    : diag::warn_deprecated_register)
6415       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6416   }
6417 
6418   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6419 
6420   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6421     // C99 6.9p2: The storage-class specifiers auto and register shall not
6422     // appear in the declaration specifiers in an external declaration.
6423     // Global Register+Asm is a GNU extension we support.
6424     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6425       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6426       D.setInvalidType();
6427     }
6428   }
6429 
6430   bool IsMemberSpecialization = false;
6431   bool IsVariableTemplateSpecialization = false;
6432   bool IsPartialSpecialization = false;
6433   bool IsVariableTemplate = false;
6434   VarDecl *NewVD = nullptr;
6435   VarTemplateDecl *NewTemplate = nullptr;
6436   TemplateParameterList *TemplateParams = nullptr;
6437   if (!getLangOpts().CPlusPlus) {
6438     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6439                             II, R, TInfo, SC);
6440 
6441     if (R->getContainedDeducedType())
6442       ParsingInitForAutoVars.insert(NewVD);
6443 
6444     if (D.isInvalidType())
6445       NewVD->setInvalidDecl();
6446   } else {
6447     bool Invalid = false;
6448 
6449     if (DC->isRecord() && !CurContext->isRecord()) {
6450       // This is an out-of-line definition of a static data member.
6451       switch (SC) {
6452       case SC_None:
6453         break;
6454       case SC_Static:
6455         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6456              diag::err_static_out_of_line)
6457           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6458         break;
6459       case SC_Auto:
6460       case SC_Register:
6461       case SC_Extern:
6462         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6463         // to names of variables declared in a block or to function parameters.
6464         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6465         // of class members
6466 
6467         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6468              diag::err_storage_class_for_static_member)
6469           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6470         break;
6471       case SC_PrivateExtern:
6472         llvm_unreachable("C storage class in c++!");
6473       }
6474     }
6475 
6476     if (SC == SC_Static && CurContext->isRecord()) {
6477       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6478         if (RD->isLocalClass())
6479           Diag(D.getIdentifierLoc(),
6480                diag::err_static_data_member_not_allowed_in_local_class)
6481             << Name << RD->getDeclName();
6482 
6483         // C++98 [class.union]p1: If a union contains a static data member,
6484         // the program is ill-formed. C++11 drops this restriction.
6485         if (RD->isUnion())
6486           Diag(D.getIdentifierLoc(),
6487                getLangOpts().CPlusPlus11
6488                  ? diag::warn_cxx98_compat_static_data_member_in_union
6489                  : diag::ext_static_data_member_in_union) << Name;
6490         // We conservatively disallow static data members in anonymous structs.
6491         else if (!RD->getDeclName())
6492           Diag(D.getIdentifierLoc(),
6493                diag::err_static_data_member_not_allowed_in_anon_struct)
6494             << Name << RD->isUnion();
6495       }
6496     }
6497 
6498     // Match up the template parameter lists with the scope specifier, then
6499     // determine whether we have a template or a template specialization.
6500     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6501         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6502         D.getCXXScopeSpec(),
6503         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6504             ? D.getName().TemplateId
6505             : nullptr,
6506         TemplateParamLists,
6507         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6508 
6509     if (TemplateParams) {
6510       if (!TemplateParams->size() &&
6511           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6512         // There is an extraneous 'template<>' for this variable. Complain
6513         // about it, but allow the declaration of the variable.
6514         Diag(TemplateParams->getTemplateLoc(),
6515              diag::err_template_variable_noparams)
6516           << II
6517           << SourceRange(TemplateParams->getTemplateLoc(),
6518                          TemplateParams->getRAngleLoc());
6519         TemplateParams = nullptr;
6520       } else {
6521         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6522           // This is an explicit specialization or a partial specialization.
6523           // FIXME: Check that we can declare a specialization here.
6524           IsVariableTemplateSpecialization = true;
6525           IsPartialSpecialization = TemplateParams->size() > 0;
6526         } else { // if (TemplateParams->size() > 0)
6527           // This is a template declaration.
6528           IsVariableTemplate = true;
6529 
6530           // Check that we can declare a template here.
6531           if (CheckTemplateDeclScope(S, TemplateParams))
6532             return nullptr;
6533 
6534           // Only C++1y supports variable templates (N3651).
6535           Diag(D.getIdentifierLoc(),
6536                getLangOpts().CPlusPlus14
6537                    ? diag::warn_cxx11_compat_variable_template
6538                    : diag::ext_variable_template);
6539         }
6540       }
6541     } else {
6542       assert((Invalid ||
6543               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6544              "should have a 'template<>' for this decl");
6545     }
6546 
6547     if (IsVariableTemplateSpecialization) {
6548       SourceLocation TemplateKWLoc =
6549           TemplateParamLists.size() > 0
6550               ? TemplateParamLists[0]->getTemplateLoc()
6551               : SourceLocation();
6552       DeclResult Res = ActOnVarTemplateSpecialization(
6553           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6554           IsPartialSpecialization);
6555       if (Res.isInvalid())
6556         return nullptr;
6557       NewVD = cast<VarDecl>(Res.get());
6558       AddToScope = false;
6559     } else if (D.isDecompositionDeclarator()) {
6560       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6561                                         D.getIdentifierLoc(), R, TInfo, SC,
6562                                         Bindings);
6563     } else
6564       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6565                               D.getIdentifierLoc(), II, R, TInfo, SC);
6566 
6567     // If this is supposed to be a variable template, create it as such.
6568     if (IsVariableTemplate) {
6569       NewTemplate =
6570           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6571                                   TemplateParams, NewVD);
6572       NewVD->setDescribedVarTemplate(NewTemplate);
6573     }
6574 
6575     // If this decl has an auto type in need of deduction, make a note of the
6576     // Decl so we can diagnose uses of it in its own initializer.
6577     if (R->getContainedDeducedType())
6578       ParsingInitForAutoVars.insert(NewVD);
6579 
6580     if (D.isInvalidType() || Invalid) {
6581       NewVD->setInvalidDecl();
6582       if (NewTemplate)
6583         NewTemplate->setInvalidDecl();
6584     }
6585 
6586     SetNestedNameSpecifier(NewVD, D);
6587 
6588     // If we have any template parameter lists that don't directly belong to
6589     // the variable (matching the scope specifier), store them.
6590     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6591     if (TemplateParamLists.size() > VDTemplateParamLists)
6592       NewVD->setTemplateParameterListsInfo(
6593           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6594 
6595     if (D.getDeclSpec().isConstexprSpecified()) {
6596       NewVD->setConstexpr(true);
6597       // C++1z [dcl.spec.constexpr]p1:
6598       //   A static data member declared with the constexpr specifier is
6599       //   implicitly an inline variable.
6600       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6601         NewVD->setImplicitlyInline();
6602     }
6603   }
6604 
6605   if (D.getDeclSpec().isInlineSpecified()) {
6606     if (!getLangOpts().CPlusPlus) {
6607       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6608           << 0;
6609     } else if (CurContext->isFunctionOrMethod()) {
6610       // 'inline' is not allowed on block scope variable declaration.
6611       Diag(D.getDeclSpec().getInlineSpecLoc(),
6612            diag::err_inline_declaration_block_scope) << Name
6613         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6614     } else {
6615       Diag(D.getDeclSpec().getInlineSpecLoc(),
6616            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6617                                      : diag::ext_inline_variable);
6618       NewVD->setInlineSpecified();
6619     }
6620   }
6621 
6622   // Set the lexical context. If the declarator has a C++ scope specifier, the
6623   // lexical context will be different from the semantic context.
6624   NewVD->setLexicalDeclContext(CurContext);
6625   if (NewTemplate)
6626     NewTemplate->setLexicalDeclContext(CurContext);
6627 
6628   if (IsLocalExternDecl) {
6629     if (D.isDecompositionDeclarator())
6630       for (auto *B : Bindings)
6631         B->setLocalExternDecl();
6632     else
6633       NewVD->setLocalExternDecl();
6634   }
6635 
6636   bool EmitTLSUnsupportedError = false;
6637   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6638     // C++11 [dcl.stc]p4:
6639     //   When thread_local is applied to a variable of block scope the
6640     //   storage-class-specifier static is implied if it does not appear
6641     //   explicitly.
6642     // Core issue: 'static' is not implied if the variable is declared
6643     //   'extern'.
6644     if (NewVD->hasLocalStorage() &&
6645         (SCSpec != DeclSpec::SCS_unspecified ||
6646          TSCS != DeclSpec::TSCS_thread_local ||
6647          !DC->isFunctionOrMethod()))
6648       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6649            diag::err_thread_non_global)
6650         << DeclSpec::getSpecifierName(TSCS);
6651     else if (!Context.getTargetInfo().isTLSSupported()) {
6652       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6653         // Postpone error emission until we've collected attributes required to
6654         // figure out whether it's a host or device variable and whether the
6655         // error should be ignored.
6656         EmitTLSUnsupportedError = true;
6657         // We still need to mark the variable as TLS so it shows up in AST with
6658         // proper storage class for other tools to use even if we're not going
6659         // to emit any code for it.
6660         NewVD->setTSCSpec(TSCS);
6661       } else
6662         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6663              diag::err_thread_unsupported);
6664     } else
6665       NewVD->setTSCSpec(TSCS);
6666   }
6667 
6668   // C99 6.7.4p3
6669   //   An inline definition of a function with external linkage shall
6670   //   not contain a definition of a modifiable object with static or
6671   //   thread storage duration...
6672   // We only apply this when the function is required to be defined
6673   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6674   // that a local variable with thread storage duration still has to
6675   // be marked 'static'.  Also note that it's possible to get these
6676   // semantics in C++ using __attribute__((gnu_inline)).
6677   if (SC == SC_Static && S->getFnParent() != nullptr &&
6678       !NewVD->getType().isConstQualified()) {
6679     FunctionDecl *CurFD = getCurFunctionDecl();
6680     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6681       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6682            diag::warn_static_local_in_extern_inline);
6683       MaybeSuggestAddingStaticToDecl(CurFD);
6684     }
6685   }
6686 
6687   if (D.getDeclSpec().isModulePrivateSpecified()) {
6688     if (IsVariableTemplateSpecialization)
6689       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6690           << (IsPartialSpecialization ? 1 : 0)
6691           << FixItHint::CreateRemoval(
6692                  D.getDeclSpec().getModulePrivateSpecLoc());
6693     else if (IsMemberSpecialization)
6694       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6695         << 2
6696         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6697     else if (NewVD->hasLocalStorage())
6698       Diag(NewVD->getLocation(), diag::err_module_private_local)
6699         << 0 << NewVD->getDeclName()
6700         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6701         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6702     else {
6703       NewVD->setModulePrivate();
6704       if (NewTemplate)
6705         NewTemplate->setModulePrivate();
6706       for (auto *B : Bindings)
6707         B->setModulePrivate();
6708     }
6709   }
6710 
6711   // Handle attributes prior to checking for duplicates in MergeVarDecl
6712   ProcessDeclAttributes(S, NewVD, D);
6713 
6714   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6715     if (EmitTLSUnsupportedError &&
6716         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6717          (getLangOpts().OpenMPIsDevice &&
6718           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6719       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6720            diag::err_thread_unsupported);
6721     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6722     // storage [duration]."
6723     if (SC == SC_None && S->getFnParent() != nullptr &&
6724         (NewVD->hasAttr<CUDASharedAttr>() ||
6725          NewVD->hasAttr<CUDAConstantAttr>())) {
6726       NewVD->setStorageClass(SC_Static);
6727     }
6728   }
6729 
6730   // Ensure that dllimport globals without explicit storage class are treated as
6731   // extern. The storage class is set above using parsed attributes. Now we can
6732   // check the VarDecl itself.
6733   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6734          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6735          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6736 
6737   // In auto-retain/release, infer strong retension for variables of
6738   // retainable type.
6739   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6740     NewVD->setInvalidDecl();
6741 
6742   // Handle GNU asm-label extension (encoded as an attribute).
6743   if (Expr *E = (Expr*)D.getAsmLabel()) {
6744     // The parser guarantees this is a string.
6745     StringLiteral *SE = cast<StringLiteral>(E);
6746     StringRef Label = SE->getString();
6747     if (S->getFnParent() != nullptr) {
6748       switch (SC) {
6749       case SC_None:
6750       case SC_Auto:
6751         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6752         break;
6753       case SC_Register:
6754         // Local Named register
6755         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6756             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6757           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6758         break;
6759       case SC_Static:
6760       case SC_Extern:
6761       case SC_PrivateExtern:
6762         break;
6763       }
6764     } else if (SC == SC_Register) {
6765       // Global Named register
6766       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6767         const auto &TI = Context.getTargetInfo();
6768         bool HasSizeMismatch;
6769 
6770         if (!TI.isValidGCCRegisterName(Label))
6771           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6772         else if (!TI.validateGlobalRegisterVariable(Label,
6773                                                     Context.getTypeSize(R),
6774                                                     HasSizeMismatch))
6775           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6776         else if (HasSizeMismatch)
6777           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6778       }
6779 
6780       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6781         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6782         NewVD->setInvalidDecl(true);
6783       }
6784     }
6785 
6786     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6787                                                 Context, Label, 0));
6788   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6789     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6790       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6791     if (I != ExtnameUndeclaredIdentifiers.end()) {
6792       if (isDeclExternC(NewVD)) {
6793         NewVD->addAttr(I->second);
6794         ExtnameUndeclaredIdentifiers.erase(I);
6795       } else
6796         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6797             << /*Variable*/1 << NewVD;
6798     }
6799   }
6800 
6801   // Find the shadowed declaration before filtering for scope.
6802   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6803                                 ? getShadowedDeclaration(NewVD, Previous)
6804                                 : nullptr;
6805 
6806   // Don't consider existing declarations that are in a different
6807   // scope and are out-of-semantic-context declarations (if the new
6808   // declaration has linkage).
6809   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6810                        D.getCXXScopeSpec().isNotEmpty() ||
6811                        IsMemberSpecialization ||
6812                        IsVariableTemplateSpecialization);
6813 
6814   // Check whether the previous declaration is in the same block scope. This
6815   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6816   if (getLangOpts().CPlusPlus &&
6817       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6818     NewVD->setPreviousDeclInSameBlockScope(
6819         Previous.isSingleResult() && !Previous.isShadowed() &&
6820         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6821 
6822   if (!getLangOpts().CPlusPlus) {
6823     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6824   } else {
6825     // If this is an explicit specialization of a static data member, check it.
6826     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6827         CheckMemberSpecialization(NewVD, Previous))
6828       NewVD->setInvalidDecl();
6829 
6830     // Merge the decl with the existing one if appropriate.
6831     if (!Previous.empty()) {
6832       if (Previous.isSingleResult() &&
6833           isa<FieldDecl>(Previous.getFoundDecl()) &&
6834           D.getCXXScopeSpec().isSet()) {
6835         // The user tried to define a non-static data member
6836         // out-of-line (C++ [dcl.meaning]p1).
6837         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6838           << D.getCXXScopeSpec().getRange();
6839         Previous.clear();
6840         NewVD->setInvalidDecl();
6841       }
6842     } else if (D.getCXXScopeSpec().isSet()) {
6843       // No previous declaration in the qualifying scope.
6844       Diag(D.getIdentifierLoc(), diag::err_no_member)
6845         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6846         << D.getCXXScopeSpec().getRange();
6847       NewVD->setInvalidDecl();
6848     }
6849 
6850     if (!IsVariableTemplateSpecialization)
6851       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6852 
6853     if (NewTemplate) {
6854       VarTemplateDecl *PrevVarTemplate =
6855           NewVD->getPreviousDecl()
6856               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6857               : nullptr;
6858 
6859       // Check the template parameter list of this declaration, possibly
6860       // merging in the template parameter list from the previous variable
6861       // template declaration.
6862       if (CheckTemplateParameterList(
6863               TemplateParams,
6864               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6865                               : nullptr,
6866               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6867                DC->isDependentContext())
6868                   ? TPC_ClassTemplateMember
6869                   : TPC_VarTemplate))
6870         NewVD->setInvalidDecl();
6871 
6872       // If we are providing an explicit specialization of a static variable
6873       // template, make a note of that.
6874       if (PrevVarTemplate &&
6875           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6876         PrevVarTemplate->setMemberSpecialization();
6877     }
6878   }
6879 
6880   // Diagnose shadowed variables iff this isn't a redeclaration.
6881   if (ShadowedDecl && !D.isRedeclaration())
6882     CheckShadow(NewVD, ShadowedDecl, Previous);
6883 
6884   ProcessPragmaWeak(S, NewVD);
6885 
6886   // If this is the first declaration of an extern C variable, update
6887   // the map of such variables.
6888   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6889       isIncompleteDeclExternC(*this, NewVD))
6890     RegisterLocallyScopedExternCDecl(NewVD, S);
6891 
6892   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6893     Decl *ManglingContextDecl;
6894     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6895             NewVD->getDeclContext(), ManglingContextDecl)) {
6896       Context.setManglingNumber(
6897           NewVD, MCtx->getManglingNumber(
6898                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6899       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6900     }
6901   }
6902 
6903   // Special handling of variable named 'main'.
6904   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6905       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6906       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6907 
6908     // C++ [basic.start.main]p3
6909     // A program that declares a variable main at global scope is ill-formed.
6910     if (getLangOpts().CPlusPlus)
6911       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6912 
6913     // In C, and external-linkage variable named main results in undefined
6914     // behavior.
6915     else if (NewVD->hasExternalFormalLinkage())
6916       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6917   }
6918 
6919   if (D.isRedeclaration() && !Previous.empty()) {
6920     NamedDecl *Prev = Previous.getRepresentativeDecl();
6921     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6922                                    D.isFunctionDefinition());
6923   }
6924 
6925   if (NewTemplate) {
6926     if (NewVD->isInvalidDecl())
6927       NewTemplate->setInvalidDecl();
6928     ActOnDocumentableDecl(NewTemplate);
6929     return NewTemplate;
6930   }
6931 
6932   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6933     CompleteMemberSpecialization(NewVD, Previous);
6934 
6935   return NewVD;
6936 }
6937 
6938 /// Enum describing the %select options in diag::warn_decl_shadow.
6939 enum ShadowedDeclKind {
6940   SDK_Local,
6941   SDK_Global,
6942   SDK_StaticMember,
6943   SDK_Field,
6944   SDK_Typedef,
6945   SDK_Using
6946 };
6947 
6948 /// Determine what kind of declaration we're shadowing.
6949 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6950                                                 const DeclContext *OldDC) {
6951   if (isa<TypeAliasDecl>(ShadowedDecl))
6952     return SDK_Using;
6953   else if (isa<TypedefDecl>(ShadowedDecl))
6954     return SDK_Typedef;
6955   else if (isa<RecordDecl>(OldDC))
6956     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6957 
6958   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6959 }
6960 
6961 /// Return the location of the capture if the given lambda captures the given
6962 /// variable \p VD, or an invalid source location otherwise.
6963 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6964                                          const VarDecl *VD) {
6965   for (const Capture &Capture : LSI->Captures) {
6966     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6967       return Capture.getLocation();
6968   }
6969   return SourceLocation();
6970 }
6971 
6972 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6973                                      const LookupResult &R) {
6974   // Only diagnose if we're shadowing an unambiguous field or variable.
6975   if (R.getResultKind() != LookupResult::Found)
6976     return false;
6977 
6978   // Return false if warning is ignored.
6979   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6980 }
6981 
6982 /// Return the declaration shadowed by the given variable \p D, or null
6983 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6984 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6985                                         const LookupResult &R) {
6986   if (!shouldWarnIfShadowedDecl(Diags, R))
6987     return nullptr;
6988 
6989   // Don't diagnose declarations at file scope.
6990   if (D->hasGlobalStorage())
6991     return nullptr;
6992 
6993   NamedDecl *ShadowedDecl = R.getFoundDecl();
6994   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6995              ? ShadowedDecl
6996              : nullptr;
6997 }
6998 
6999 /// Return the declaration shadowed by the given typedef \p D, or null
7000 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7001 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7002                                         const LookupResult &R) {
7003   // Don't warn if typedef declaration is part of a class
7004   if (D->getDeclContext()->isRecord())
7005     return nullptr;
7006 
7007   if (!shouldWarnIfShadowedDecl(Diags, R))
7008     return nullptr;
7009 
7010   NamedDecl *ShadowedDecl = R.getFoundDecl();
7011   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7012 }
7013 
7014 /// Diagnose variable or built-in function shadowing.  Implements
7015 /// -Wshadow.
7016 ///
7017 /// This method is called whenever a VarDecl is added to a "useful"
7018 /// scope.
7019 ///
7020 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7021 /// \param R the lookup of the name
7022 ///
7023 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7024                        const LookupResult &R) {
7025   DeclContext *NewDC = D->getDeclContext();
7026 
7027   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7028     // Fields are not shadowed by variables in C++ static methods.
7029     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7030       if (MD->isStatic())
7031         return;
7032 
7033     // Fields shadowed by constructor parameters are a special case. Usually
7034     // the constructor initializes the field with the parameter.
7035     if (isa<CXXConstructorDecl>(NewDC))
7036       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7037         // Remember that this was shadowed so we can either warn about its
7038         // modification or its existence depending on warning settings.
7039         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7040         return;
7041       }
7042   }
7043 
7044   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7045     if (shadowedVar->isExternC()) {
7046       // For shadowing external vars, make sure that we point to the global
7047       // declaration, not a locally scoped extern declaration.
7048       for (auto I : shadowedVar->redecls())
7049         if (I->isFileVarDecl()) {
7050           ShadowedDecl = I;
7051           break;
7052         }
7053     }
7054 
7055   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7056 
7057   unsigned WarningDiag = diag::warn_decl_shadow;
7058   SourceLocation CaptureLoc;
7059   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7060       isa<CXXMethodDecl>(NewDC)) {
7061     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7062       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7063         if (RD->getLambdaCaptureDefault() == LCD_None) {
7064           // Try to avoid warnings for lambdas with an explicit capture list.
7065           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7066           // Warn only when the lambda captures the shadowed decl explicitly.
7067           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7068           if (CaptureLoc.isInvalid())
7069             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7070         } else {
7071           // Remember that this was shadowed so we can avoid the warning if the
7072           // shadowed decl isn't captured and the warning settings allow it.
7073           cast<LambdaScopeInfo>(getCurFunction())
7074               ->ShadowingDecls.push_back(
7075                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7076           return;
7077         }
7078       }
7079 
7080       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7081         // A variable can't shadow a local variable in an enclosing scope, if
7082         // they are separated by a non-capturing declaration context.
7083         for (DeclContext *ParentDC = NewDC;
7084              ParentDC && !ParentDC->Equals(OldDC);
7085              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7086           // Only block literals, captured statements, and lambda expressions
7087           // can capture; other scopes don't.
7088           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7089               !isLambdaCallOperator(ParentDC)) {
7090             return;
7091           }
7092         }
7093       }
7094     }
7095   }
7096 
7097   // Only warn about certain kinds of shadowing for class members.
7098   if (NewDC && NewDC->isRecord()) {
7099     // In particular, don't warn about shadowing non-class members.
7100     if (!OldDC->isRecord())
7101       return;
7102 
7103     // TODO: should we warn about static data members shadowing
7104     // static data members from base classes?
7105 
7106     // TODO: don't diagnose for inaccessible shadowed members.
7107     // This is hard to do perfectly because we might friend the
7108     // shadowing context, but that's just a false negative.
7109   }
7110 
7111 
7112   DeclarationName Name = R.getLookupName();
7113 
7114   // Emit warning and note.
7115   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7116     return;
7117   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7118   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7119   if (!CaptureLoc.isInvalid())
7120     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7121         << Name << /*explicitly*/ 1;
7122   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7123 }
7124 
7125 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7126 /// when these variables are captured by the lambda.
7127 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7128   for (const auto &Shadow : LSI->ShadowingDecls) {
7129     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7130     // Try to avoid the warning when the shadowed decl isn't captured.
7131     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7132     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7133     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7134                                        ? diag::warn_decl_shadow_uncaptured_local
7135                                        : diag::warn_decl_shadow)
7136         << Shadow.VD->getDeclName()
7137         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7138     if (!CaptureLoc.isInvalid())
7139       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7140           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7141     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7142   }
7143 }
7144 
7145 /// Check -Wshadow without the advantage of a previous lookup.
7146 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7147   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7148     return;
7149 
7150   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7151                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7152   LookupName(R, S);
7153   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7154     CheckShadow(D, ShadowedDecl, R);
7155 }
7156 
7157 /// Check if 'E', which is an expression that is about to be modified, refers
7158 /// to a constructor parameter that shadows a field.
7159 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7160   // Quickly ignore expressions that can't be shadowing ctor parameters.
7161   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7162     return;
7163   E = E->IgnoreParenImpCasts();
7164   auto *DRE = dyn_cast<DeclRefExpr>(E);
7165   if (!DRE)
7166     return;
7167   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7168   auto I = ShadowingDecls.find(D);
7169   if (I == ShadowingDecls.end())
7170     return;
7171   const NamedDecl *ShadowedDecl = I->second;
7172   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7173   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7174   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7175   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7176 
7177   // Avoid issuing multiple warnings about the same decl.
7178   ShadowingDecls.erase(I);
7179 }
7180 
7181 /// Check for conflict between this global or extern "C" declaration and
7182 /// previous global or extern "C" declarations. This is only used in C++.
7183 template<typename T>
7184 static bool checkGlobalOrExternCConflict(
7185     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7186   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7187   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7188 
7189   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7190     // The common case: this global doesn't conflict with any extern "C"
7191     // declaration.
7192     return false;
7193   }
7194 
7195   if (Prev) {
7196     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7197       // Both the old and new declarations have C language linkage. This is a
7198       // redeclaration.
7199       Previous.clear();
7200       Previous.addDecl(Prev);
7201       return true;
7202     }
7203 
7204     // This is a global, non-extern "C" declaration, and there is a previous
7205     // non-global extern "C" declaration. Diagnose if this is a variable
7206     // declaration.
7207     if (!isa<VarDecl>(ND))
7208       return false;
7209   } else {
7210     // The declaration is extern "C". Check for any declaration in the
7211     // translation unit which might conflict.
7212     if (IsGlobal) {
7213       // We have already performed the lookup into the translation unit.
7214       IsGlobal = false;
7215       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7216            I != E; ++I) {
7217         if (isa<VarDecl>(*I)) {
7218           Prev = *I;
7219           break;
7220         }
7221       }
7222     } else {
7223       DeclContext::lookup_result R =
7224           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7225       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7226            I != E; ++I) {
7227         if (isa<VarDecl>(*I)) {
7228           Prev = *I;
7229           break;
7230         }
7231         // FIXME: If we have any other entity with this name in global scope,
7232         // the declaration is ill-formed, but that is a defect: it breaks the
7233         // 'stat' hack, for instance. Only variables can have mangled name
7234         // clashes with extern "C" declarations, so only they deserve a
7235         // diagnostic.
7236       }
7237     }
7238 
7239     if (!Prev)
7240       return false;
7241   }
7242 
7243   // Use the first declaration's location to ensure we point at something which
7244   // is lexically inside an extern "C" linkage-spec.
7245   assert(Prev && "should have found a previous declaration to diagnose");
7246   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7247     Prev = FD->getFirstDecl();
7248   else
7249     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7250 
7251   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7252     << IsGlobal << ND;
7253   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7254     << IsGlobal;
7255   return false;
7256 }
7257 
7258 /// Apply special rules for handling extern "C" declarations. Returns \c true
7259 /// if we have found that this is a redeclaration of some prior entity.
7260 ///
7261 /// Per C++ [dcl.link]p6:
7262 ///   Two declarations [for a function or variable] with C language linkage
7263 ///   with the same name that appear in different scopes refer to the same
7264 ///   [entity]. An entity with C language linkage shall not be declared with
7265 ///   the same name as an entity in global scope.
7266 template<typename T>
7267 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7268                                                   LookupResult &Previous) {
7269   if (!S.getLangOpts().CPlusPlus) {
7270     // In C, when declaring a global variable, look for a corresponding 'extern'
7271     // variable declared in function scope. We don't need this in C++, because
7272     // we find local extern decls in the surrounding file-scope DeclContext.
7273     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7274       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7275         Previous.clear();
7276         Previous.addDecl(Prev);
7277         return true;
7278       }
7279     }
7280     return false;
7281   }
7282 
7283   // A declaration in the translation unit can conflict with an extern "C"
7284   // declaration.
7285   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7286     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7287 
7288   // An extern "C" declaration can conflict with a declaration in the
7289   // translation unit or can be a redeclaration of an extern "C" declaration
7290   // in another scope.
7291   if (isIncompleteDeclExternC(S,ND))
7292     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7293 
7294   // Neither global nor extern "C": nothing to do.
7295   return false;
7296 }
7297 
7298 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7299   // If the decl is already known invalid, don't check it.
7300   if (NewVD->isInvalidDecl())
7301     return;
7302 
7303   QualType T = NewVD->getType();
7304 
7305   // Defer checking an 'auto' type until its initializer is attached.
7306   if (T->isUndeducedType())
7307     return;
7308 
7309   if (NewVD->hasAttrs())
7310     CheckAlignasUnderalignment(NewVD);
7311 
7312   if (T->isObjCObjectType()) {
7313     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7314       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7315     T = Context.getObjCObjectPointerType(T);
7316     NewVD->setType(T);
7317   }
7318 
7319   // Emit an error if an address space was applied to decl with local storage.
7320   // This includes arrays of objects with address space qualifiers, but not
7321   // automatic variables that point to other address spaces.
7322   // ISO/IEC TR 18037 S5.1.2
7323   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7324       T.getAddressSpace() != LangAS::Default) {
7325     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7326     NewVD->setInvalidDecl();
7327     return;
7328   }
7329 
7330   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7331   // scope.
7332   if (getLangOpts().OpenCLVersion == 120 &&
7333       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7334       NewVD->isStaticLocal()) {
7335     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7336     NewVD->setInvalidDecl();
7337     return;
7338   }
7339 
7340   if (getLangOpts().OpenCL) {
7341     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7342     if (NewVD->hasAttr<BlocksAttr>()) {
7343       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7344       return;
7345     }
7346 
7347     if (T->isBlockPointerType()) {
7348       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7349       // can't use 'extern' storage class.
7350       if (!T.isConstQualified()) {
7351         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7352             << 0 /*const*/;
7353         NewVD->setInvalidDecl();
7354         return;
7355       }
7356       if (NewVD->hasExternalStorage()) {
7357         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7358         NewVD->setInvalidDecl();
7359         return;
7360       }
7361     }
7362     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7363     // __constant address space.
7364     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7365     // variables inside a function can also be declared in the global
7366     // address space.
7367     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7368         NewVD->hasExternalStorage()) {
7369       if (!T->isSamplerT() &&
7370           !(T.getAddressSpace() == LangAS::opencl_constant ||
7371             (T.getAddressSpace() == LangAS::opencl_global &&
7372              getLangOpts().OpenCLVersion == 200))) {
7373         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7374         if (getLangOpts().OpenCLVersion == 200)
7375           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7376               << Scope << "global or constant";
7377         else
7378           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7379               << Scope << "constant";
7380         NewVD->setInvalidDecl();
7381         return;
7382       }
7383     } else {
7384       if (T.getAddressSpace() == LangAS::opencl_global) {
7385         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7386             << 1 /*is any function*/ << "global";
7387         NewVD->setInvalidDecl();
7388         return;
7389       }
7390       if (T.getAddressSpace() == LangAS::opencl_constant ||
7391           T.getAddressSpace() == LangAS::opencl_local) {
7392         FunctionDecl *FD = getCurFunctionDecl();
7393         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7394         // in functions.
7395         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7396           if (T.getAddressSpace() == LangAS::opencl_constant)
7397             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7398                 << 0 /*non-kernel only*/ << "constant";
7399           else
7400             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7401                 << 0 /*non-kernel only*/ << "local";
7402           NewVD->setInvalidDecl();
7403           return;
7404         }
7405         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7406         // in the outermost scope of a kernel function.
7407         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7408           if (!getCurScope()->isFunctionScope()) {
7409             if (T.getAddressSpace() == LangAS::opencl_constant)
7410               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7411                   << "constant";
7412             else
7413               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7414                   << "local";
7415             NewVD->setInvalidDecl();
7416             return;
7417           }
7418         }
7419       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7420         // Do not allow other address spaces on automatic variable.
7421         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7422         NewVD->setInvalidDecl();
7423         return;
7424       }
7425     }
7426   }
7427 
7428   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7429       && !NewVD->hasAttr<BlocksAttr>()) {
7430     if (getLangOpts().getGC() != LangOptions::NonGC)
7431       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7432     else {
7433       assert(!getLangOpts().ObjCAutoRefCount);
7434       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7435     }
7436   }
7437 
7438   bool isVM = T->isVariablyModifiedType();
7439   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7440       NewVD->hasAttr<BlocksAttr>())
7441     setFunctionHasBranchProtectedScope();
7442 
7443   if ((isVM && NewVD->hasLinkage()) ||
7444       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7445     bool SizeIsNegative;
7446     llvm::APSInt Oversized;
7447     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7448         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7449     QualType FixedT;
7450     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7451       FixedT = FixedTInfo->getType();
7452     else if (FixedTInfo) {
7453       // Type and type-as-written are canonically different. We need to fix up
7454       // both types separately.
7455       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7456                                                    Oversized);
7457     }
7458     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7459       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7460       // FIXME: This won't give the correct result for
7461       // int a[10][n];
7462       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7463 
7464       if (NewVD->isFileVarDecl())
7465         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7466         << SizeRange;
7467       else if (NewVD->isStaticLocal())
7468         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7469         << SizeRange;
7470       else
7471         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7472         << SizeRange;
7473       NewVD->setInvalidDecl();
7474       return;
7475     }
7476 
7477     if (!FixedTInfo) {
7478       if (NewVD->isFileVarDecl())
7479         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7480       else
7481         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7482       NewVD->setInvalidDecl();
7483       return;
7484     }
7485 
7486     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7487     NewVD->setType(FixedT);
7488     NewVD->setTypeSourceInfo(FixedTInfo);
7489   }
7490 
7491   if (T->isVoidType()) {
7492     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7493     //                    of objects and functions.
7494     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7495       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7496         << T;
7497       NewVD->setInvalidDecl();
7498       return;
7499     }
7500   }
7501 
7502   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7503     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7504     NewVD->setInvalidDecl();
7505     return;
7506   }
7507 
7508   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7509     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7510     NewVD->setInvalidDecl();
7511     return;
7512   }
7513 
7514   if (NewVD->isConstexpr() && !T->isDependentType() &&
7515       RequireLiteralType(NewVD->getLocation(), T,
7516                          diag::err_constexpr_var_non_literal)) {
7517     NewVD->setInvalidDecl();
7518     return;
7519   }
7520 }
7521 
7522 /// Perform semantic checking on a newly-created variable
7523 /// declaration.
7524 ///
7525 /// This routine performs all of the type-checking required for a
7526 /// variable declaration once it has been built. It is used both to
7527 /// check variables after they have been parsed and their declarators
7528 /// have been translated into a declaration, and to check variables
7529 /// that have been instantiated from a template.
7530 ///
7531 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7532 ///
7533 /// Returns true if the variable declaration is a redeclaration.
7534 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7535   CheckVariableDeclarationType(NewVD);
7536 
7537   // If the decl is already known invalid, don't check it.
7538   if (NewVD->isInvalidDecl())
7539     return false;
7540 
7541   // If we did not find anything by this name, look for a non-visible
7542   // extern "C" declaration with the same name.
7543   if (Previous.empty() &&
7544       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7545     Previous.setShadowed();
7546 
7547   if (!Previous.empty()) {
7548     MergeVarDecl(NewVD, Previous);
7549     return true;
7550   }
7551   return false;
7552 }
7553 
7554 namespace {
7555 struct FindOverriddenMethod {
7556   Sema *S;
7557   CXXMethodDecl *Method;
7558 
7559   /// Member lookup function that determines whether a given C++
7560   /// method overrides a method in a base class, to be used with
7561   /// CXXRecordDecl::lookupInBases().
7562   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7563     RecordDecl *BaseRecord =
7564         Specifier->getType()->getAs<RecordType>()->getDecl();
7565 
7566     DeclarationName Name = Method->getDeclName();
7567 
7568     // FIXME: Do we care about other names here too?
7569     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7570       // We really want to find the base class destructor here.
7571       QualType T = S->Context.getTypeDeclType(BaseRecord);
7572       CanQualType CT = S->Context.getCanonicalType(T);
7573 
7574       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7575     }
7576 
7577     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7578          Path.Decls = Path.Decls.slice(1)) {
7579       NamedDecl *D = Path.Decls.front();
7580       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7581         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7582           return true;
7583       }
7584     }
7585 
7586     return false;
7587   }
7588 };
7589 
7590 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7591 } // end anonymous namespace
7592 
7593 /// Report an error regarding overriding, along with any relevant
7594 /// overridden methods.
7595 ///
7596 /// \param DiagID the primary error to report.
7597 /// \param MD the overriding method.
7598 /// \param OEK which overrides to include as notes.
7599 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7600                             OverrideErrorKind OEK = OEK_All) {
7601   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7602   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7603     // This check (& the OEK parameter) could be replaced by a predicate, but
7604     // without lambdas that would be overkill. This is still nicer than writing
7605     // out the diag loop 3 times.
7606     if ((OEK == OEK_All) ||
7607         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7608         (OEK == OEK_Deleted && O->isDeleted()))
7609       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7610   }
7611 }
7612 
7613 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7614 /// and if so, check that it's a valid override and remember it.
7615 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7616   // Look for methods in base classes that this method might override.
7617   CXXBasePaths Paths;
7618   FindOverriddenMethod FOM;
7619   FOM.Method = MD;
7620   FOM.S = this;
7621   bool hasDeletedOverridenMethods = false;
7622   bool hasNonDeletedOverridenMethods = false;
7623   bool AddedAny = false;
7624   if (DC->lookupInBases(FOM, Paths)) {
7625     for (auto *I : Paths.found_decls()) {
7626       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7627         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7628         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7629             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7630             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7631             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7632           hasDeletedOverridenMethods |= OldMD->isDeleted();
7633           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7634           AddedAny = true;
7635         }
7636       }
7637     }
7638   }
7639 
7640   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7641     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7642   }
7643   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7644     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7645   }
7646 
7647   return AddedAny;
7648 }
7649 
7650 namespace {
7651   // Struct for holding all of the extra arguments needed by
7652   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7653   struct ActOnFDArgs {
7654     Scope *S;
7655     Declarator &D;
7656     MultiTemplateParamsArg TemplateParamLists;
7657     bool AddToScope;
7658   };
7659 } // end anonymous namespace
7660 
7661 namespace {
7662 
7663 // Callback to only accept typo corrections that have a non-zero edit distance.
7664 // Also only accept corrections that have the same parent decl.
7665 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7666  public:
7667   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7668                             CXXRecordDecl *Parent)
7669       : Context(Context), OriginalFD(TypoFD),
7670         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7671 
7672   bool ValidateCandidate(const TypoCorrection &candidate) override {
7673     if (candidate.getEditDistance() == 0)
7674       return false;
7675 
7676     SmallVector<unsigned, 1> MismatchedParams;
7677     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7678                                           CDeclEnd = candidate.end();
7679          CDecl != CDeclEnd; ++CDecl) {
7680       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7681 
7682       if (FD && !FD->hasBody() &&
7683           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7684         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7685           CXXRecordDecl *Parent = MD->getParent();
7686           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7687             return true;
7688         } else if (!ExpectedParent) {
7689           return true;
7690         }
7691       }
7692     }
7693 
7694     return false;
7695   }
7696 
7697  private:
7698   ASTContext &Context;
7699   FunctionDecl *OriginalFD;
7700   CXXRecordDecl *ExpectedParent;
7701 };
7702 
7703 } // end anonymous namespace
7704 
7705 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7706   TypoCorrectedFunctionDefinitions.insert(F);
7707 }
7708 
7709 /// Generate diagnostics for an invalid function redeclaration.
7710 ///
7711 /// This routine handles generating the diagnostic messages for an invalid
7712 /// function redeclaration, including finding possible similar declarations
7713 /// or performing typo correction if there are no previous declarations with
7714 /// the same name.
7715 ///
7716 /// Returns a NamedDecl iff typo correction was performed and substituting in
7717 /// the new declaration name does not cause new errors.
7718 static NamedDecl *DiagnoseInvalidRedeclaration(
7719     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7720     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7721   DeclarationName Name = NewFD->getDeclName();
7722   DeclContext *NewDC = NewFD->getDeclContext();
7723   SmallVector<unsigned, 1> MismatchedParams;
7724   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7725   TypoCorrection Correction;
7726   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7727   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7728                                    : diag::err_member_decl_does_not_match;
7729   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7730                     IsLocalFriend ? Sema::LookupLocalFriendName
7731                                   : Sema::LookupOrdinaryName,
7732                     Sema::ForVisibleRedeclaration);
7733 
7734   NewFD->setInvalidDecl();
7735   if (IsLocalFriend)
7736     SemaRef.LookupName(Prev, S);
7737   else
7738     SemaRef.LookupQualifiedName(Prev, NewDC);
7739   assert(!Prev.isAmbiguous() &&
7740          "Cannot have an ambiguity in previous-declaration lookup");
7741   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7742   if (!Prev.empty()) {
7743     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7744          Func != FuncEnd; ++Func) {
7745       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7746       if (FD &&
7747           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7748         // Add 1 to the index so that 0 can mean the mismatch didn't
7749         // involve a parameter
7750         unsigned ParamNum =
7751             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7752         NearMatches.push_back(std::make_pair(FD, ParamNum));
7753       }
7754     }
7755   // If the qualified name lookup yielded nothing, try typo correction
7756   } else if ((Correction = SemaRef.CorrectTypo(
7757                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7758                   &ExtraArgs.D.getCXXScopeSpec(),
7759                   llvm::make_unique<DifferentNameValidatorCCC>(
7760                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7761                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7762     // Set up everything for the call to ActOnFunctionDeclarator
7763     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7764                               ExtraArgs.D.getIdentifierLoc());
7765     Previous.clear();
7766     Previous.setLookupName(Correction.getCorrection());
7767     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7768                                     CDeclEnd = Correction.end();
7769          CDecl != CDeclEnd; ++CDecl) {
7770       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7771       if (FD && !FD->hasBody() &&
7772           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7773         Previous.addDecl(FD);
7774       }
7775     }
7776     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7777 
7778     NamedDecl *Result;
7779     // Retry building the function declaration with the new previous
7780     // declarations, and with errors suppressed.
7781     {
7782       // Trap errors.
7783       Sema::SFINAETrap Trap(SemaRef);
7784 
7785       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7786       // pieces need to verify the typo-corrected C++ declaration and hopefully
7787       // eliminate the need for the parameter pack ExtraArgs.
7788       Result = SemaRef.ActOnFunctionDeclarator(
7789           ExtraArgs.S, ExtraArgs.D,
7790           Correction.getCorrectionDecl()->getDeclContext(),
7791           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7792           ExtraArgs.AddToScope);
7793 
7794       if (Trap.hasErrorOccurred())
7795         Result = nullptr;
7796     }
7797 
7798     if (Result) {
7799       // Determine which correction we picked.
7800       Decl *Canonical = Result->getCanonicalDecl();
7801       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7802            I != E; ++I)
7803         if ((*I)->getCanonicalDecl() == Canonical)
7804           Correction.setCorrectionDecl(*I);
7805 
7806       // Let Sema know about the correction.
7807       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7808       SemaRef.diagnoseTypo(
7809           Correction,
7810           SemaRef.PDiag(IsLocalFriend
7811                           ? diag::err_no_matching_local_friend_suggest
7812                           : diag::err_member_decl_does_not_match_suggest)
7813             << Name << NewDC << IsDefinition);
7814       return Result;
7815     }
7816 
7817     // Pretend the typo correction never occurred
7818     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7819                               ExtraArgs.D.getIdentifierLoc());
7820     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7821     Previous.clear();
7822     Previous.setLookupName(Name);
7823   }
7824 
7825   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7826       << Name << NewDC << IsDefinition << NewFD->getLocation();
7827 
7828   bool NewFDisConst = false;
7829   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7830     NewFDisConst = NewMD->isConst();
7831 
7832   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7833        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7834        NearMatch != NearMatchEnd; ++NearMatch) {
7835     FunctionDecl *FD = NearMatch->first;
7836     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7837     bool FDisConst = MD && MD->isConst();
7838     bool IsMember = MD || !IsLocalFriend;
7839 
7840     // FIXME: These notes are poorly worded for the local friend case.
7841     if (unsigned Idx = NearMatch->second) {
7842       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7843       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7844       if (Loc.isInvalid()) Loc = FD->getLocation();
7845       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7846                                  : diag::note_local_decl_close_param_match)
7847         << Idx << FDParam->getType()
7848         << NewFD->getParamDecl(Idx - 1)->getType();
7849     } else if (FDisConst != NewFDisConst) {
7850       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7851           << NewFDisConst << FD->getSourceRange().getEnd();
7852     } else
7853       SemaRef.Diag(FD->getLocation(),
7854                    IsMember ? diag::note_member_def_close_match
7855                             : diag::note_local_decl_close_match);
7856   }
7857   return nullptr;
7858 }
7859 
7860 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7861   switch (D.getDeclSpec().getStorageClassSpec()) {
7862   default: llvm_unreachable("Unknown storage class!");
7863   case DeclSpec::SCS_auto:
7864   case DeclSpec::SCS_register:
7865   case DeclSpec::SCS_mutable:
7866     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7867                  diag::err_typecheck_sclass_func);
7868     D.getMutableDeclSpec().ClearStorageClassSpecs();
7869     D.setInvalidType();
7870     break;
7871   case DeclSpec::SCS_unspecified: break;
7872   case DeclSpec::SCS_extern:
7873     if (D.getDeclSpec().isExternInLinkageSpec())
7874       return SC_None;
7875     return SC_Extern;
7876   case DeclSpec::SCS_static: {
7877     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7878       // C99 6.7.1p5:
7879       //   The declaration of an identifier for a function that has
7880       //   block scope shall have no explicit storage-class specifier
7881       //   other than extern
7882       // See also (C++ [dcl.stc]p4).
7883       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7884                    diag::err_static_block_func);
7885       break;
7886     } else
7887       return SC_Static;
7888   }
7889   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7890   }
7891 
7892   // No explicit storage class has already been returned
7893   return SC_None;
7894 }
7895 
7896 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7897                                            DeclContext *DC, QualType &R,
7898                                            TypeSourceInfo *TInfo,
7899                                            StorageClass SC,
7900                                            bool &IsVirtualOkay) {
7901   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7902   DeclarationName Name = NameInfo.getName();
7903 
7904   FunctionDecl *NewFD = nullptr;
7905   bool isInline = D.getDeclSpec().isInlineSpecified();
7906 
7907   if (!SemaRef.getLangOpts().CPlusPlus) {
7908     // Determine whether the function was written with a
7909     // prototype. This true when:
7910     //   - there is a prototype in the declarator, or
7911     //   - the type R of the function is some kind of typedef or other non-
7912     //     attributed reference to a type name (which eventually refers to a
7913     //     function type).
7914     bool HasPrototype =
7915       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7916       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7917 
7918     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7919                                  R, TInfo, SC, isInline, HasPrototype, false);
7920     if (D.isInvalidType())
7921       NewFD->setInvalidDecl();
7922 
7923     return NewFD;
7924   }
7925 
7926   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7927   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7928 
7929   // Check that the return type is not an abstract class type.
7930   // For record types, this is done by the AbstractClassUsageDiagnoser once
7931   // the class has been completely parsed.
7932   if (!DC->isRecord() &&
7933       SemaRef.RequireNonAbstractType(
7934           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7935           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7936     D.setInvalidType();
7937 
7938   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7939     // This is a C++ constructor declaration.
7940     assert(DC->isRecord() &&
7941            "Constructors can only be declared in a member context");
7942 
7943     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7944     return CXXConstructorDecl::Create(
7945         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7946         TInfo, isExplicit, isInline,
7947         /*isImplicitlyDeclared=*/false, isConstexpr);
7948 
7949   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7950     // This is a C++ destructor declaration.
7951     if (DC->isRecord()) {
7952       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7953       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7954       CXXDestructorDecl *NewDD =
7955           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
7956                                     NameInfo, R, TInfo, isInline,
7957                                     /*isImplicitlyDeclared=*/false);
7958 
7959       // If the class is complete, then we now create the implicit exception
7960       // specification. If the class is incomplete or dependent, we can't do
7961       // it yet.
7962       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7963           Record->getDefinition() && !Record->isBeingDefined() &&
7964           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7965         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7966       }
7967 
7968       IsVirtualOkay = true;
7969       return NewDD;
7970 
7971     } else {
7972       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7973       D.setInvalidType();
7974 
7975       // Create a FunctionDecl to satisfy the function definition parsing
7976       // code path.
7977       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7978                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
7979                                   isInline,
7980                                   /*hasPrototype=*/true, isConstexpr);
7981     }
7982 
7983   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7984     if (!DC->isRecord()) {
7985       SemaRef.Diag(D.getIdentifierLoc(),
7986            diag::err_conv_function_not_member);
7987       return nullptr;
7988     }
7989 
7990     SemaRef.CheckConversionDeclarator(D, R, SC);
7991     IsVirtualOkay = true;
7992     return CXXConversionDecl::Create(
7993         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7994         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
7995 
7996   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7997     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7998 
7999     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8000                                          isExplicit, NameInfo, R, TInfo,
8001                                          D.getEndLoc());
8002   } else if (DC->isRecord()) {
8003     // If the name of the function is the same as the name of the record,
8004     // then this must be an invalid constructor that has a return type.
8005     // (The parser checks for a return type and makes the declarator a
8006     // constructor if it has no return type).
8007     if (Name.getAsIdentifierInfo() &&
8008         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8009       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8010         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8011         << SourceRange(D.getIdentifierLoc());
8012       return nullptr;
8013     }
8014 
8015     // This is a C++ method declaration.
8016     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8017         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8018         TInfo, SC, isInline, isConstexpr, SourceLocation());
8019     IsVirtualOkay = !Ret->isStatic();
8020     return Ret;
8021   } else {
8022     bool isFriend =
8023         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8024     if (!isFriend && SemaRef.CurContext->isRecord())
8025       return nullptr;
8026 
8027     // Determine whether the function was written with a
8028     // prototype. This true when:
8029     //   - we're in C++ (where every function has a prototype),
8030     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8031                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8032                                 isConstexpr);
8033   }
8034 }
8035 
8036 enum OpenCLParamType {
8037   ValidKernelParam,
8038   PtrPtrKernelParam,
8039   PtrKernelParam,
8040   InvalidAddrSpacePtrKernelParam,
8041   InvalidKernelParam,
8042   RecordKernelParam
8043 };
8044 
8045 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8046   // Size dependent types are just typedefs to normal integer types
8047   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8048   // integers other than by their names.
8049   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8050 
8051   // Remove typedefs one by one until we reach a typedef
8052   // for a size dependent type.
8053   QualType DesugaredTy = Ty;
8054   do {
8055     ArrayRef<StringRef> Names(SizeTypeNames);
8056     auto Match =
8057         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8058     if (Names.end() != Match)
8059       return true;
8060 
8061     Ty = DesugaredTy;
8062     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8063   } while (DesugaredTy != Ty);
8064 
8065   return false;
8066 }
8067 
8068 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8069   if (PT->isPointerType()) {
8070     QualType PointeeType = PT->getPointeeType();
8071     if (PointeeType->isPointerType())
8072       return PtrPtrKernelParam;
8073     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8074         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8075         PointeeType.getAddressSpace() == LangAS::Default)
8076       return InvalidAddrSpacePtrKernelParam;
8077     return PtrKernelParam;
8078   }
8079 
8080   // OpenCL v1.2 s6.9.k:
8081   // Arguments to kernel functions in a program cannot be declared with the
8082   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8083   // uintptr_t or a struct and/or union that contain fields declared to be one
8084   // of these built-in scalar types.
8085   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8086     return InvalidKernelParam;
8087 
8088   if (PT->isImageType())
8089     return PtrKernelParam;
8090 
8091   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8092     return InvalidKernelParam;
8093 
8094   // OpenCL extension spec v1.2 s9.5:
8095   // This extension adds support for half scalar and vector types as built-in
8096   // types that can be used for arithmetic operations, conversions etc.
8097   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8098     return InvalidKernelParam;
8099 
8100   if (PT->isRecordType())
8101     return RecordKernelParam;
8102 
8103   // Look into an array argument to check if it has a forbidden type.
8104   if (PT->isArrayType()) {
8105     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8106     // Call ourself to check an underlying type of an array. Since the
8107     // getPointeeOrArrayElementType returns an innermost type which is not an
8108     // array, this recusive call only happens once.
8109     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8110   }
8111 
8112   return ValidKernelParam;
8113 }
8114 
8115 static void checkIsValidOpenCLKernelParameter(
8116   Sema &S,
8117   Declarator &D,
8118   ParmVarDecl *Param,
8119   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8120   QualType PT = Param->getType();
8121 
8122   // Cache the valid types we encounter to avoid rechecking structs that are
8123   // used again
8124   if (ValidTypes.count(PT.getTypePtr()))
8125     return;
8126 
8127   switch (getOpenCLKernelParameterType(S, PT)) {
8128   case PtrPtrKernelParam:
8129     // OpenCL v1.2 s6.9.a:
8130     // A kernel function argument cannot be declared as a
8131     // pointer to a pointer type.
8132     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8133     D.setInvalidType();
8134     return;
8135 
8136   case InvalidAddrSpacePtrKernelParam:
8137     // OpenCL v1.0 s6.5:
8138     // __kernel function arguments declared to be a pointer of a type can point
8139     // to one of the following address spaces only : __global, __local or
8140     // __constant.
8141     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8142     D.setInvalidType();
8143     return;
8144 
8145     // OpenCL v1.2 s6.9.k:
8146     // Arguments to kernel functions in a program cannot be declared with the
8147     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8148     // uintptr_t or a struct and/or union that contain fields declared to be
8149     // one of these built-in scalar types.
8150 
8151   case InvalidKernelParam:
8152     // OpenCL v1.2 s6.8 n:
8153     // A kernel function argument cannot be declared
8154     // of event_t type.
8155     // Do not diagnose half type since it is diagnosed as invalid argument
8156     // type for any function elsewhere.
8157     if (!PT->isHalfType()) {
8158       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8159 
8160       // Explain what typedefs are involved.
8161       const TypedefType *Typedef = nullptr;
8162       while ((Typedef = PT->getAs<TypedefType>())) {
8163         SourceLocation Loc = Typedef->getDecl()->getLocation();
8164         // SourceLocation may be invalid for a built-in type.
8165         if (Loc.isValid())
8166           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8167         PT = Typedef->desugar();
8168       }
8169     }
8170 
8171     D.setInvalidType();
8172     return;
8173 
8174   case PtrKernelParam:
8175   case ValidKernelParam:
8176     ValidTypes.insert(PT.getTypePtr());
8177     return;
8178 
8179   case RecordKernelParam:
8180     break;
8181   }
8182 
8183   // Track nested structs we will inspect
8184   SmallVector<const Decl *, 4> VisitStack;
8185 
8186   // Track where we are in the nested structs. Items will migrate from
8187   // VisitStack to HistoryStack as we do the DFS for bad field.
8188   SmallVector<const FieldDecl *, 4> HistoryStack;
8189   HistoryStack.push_back(nullptr);
8190 
8191   // At this point we already handled everything except of a RecordType or
8192   // an ArrayType of a RecordType.
8193   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8194   const RecordType *RecTy =
8195       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8196   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8197 
8198   VisitStack.push_back(RecTy->getDecl());
8199   assert(VisitStack.back() && "First decl null?");
8200 
8201   do {
8202     const Decl *Next = VisitStack.pop_back_val();
8203     if (!Next) {
8204       assert(!HistoryStack.empty());
8205       // Found a marker, we have gone up a level
8206       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8207         ValidTypes.insert(Hist->getType().getTypePtr());
8208 
8209       continue;
8210     }
8211 
8212     // Adds everything except the original parameter declaration (which is not a
8213     // field itself) to the history stack.
8214     const RecordDecl *RD;
8215     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8216       HistoryStack.push_back(Field);
8217 
8218       QualType FieldTy = Field->getType();
8219       // Other field types (known to be valid or invalid) are handled while we
8220       // walk around RecordDecl::fields().
8221       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8222              "Unexpected type.");
8223       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8224 
8225       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8226     } else {
8227       RD = cast<RecordDecl>(Next);
8228     }
8229 
8230     // Add a null marker so we know when we've gone back up a level
8231     VisitStack.push_back(nullptr);
8232 
8233     for (const auto *FD : RD->fields()) {
8234       QualType QT = FD->getType();
8235 
8236       if (ValidTypes.count(QT.getTypePtr()))
8237         continue;
8238 
8239       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8240       if (ParamType == ValidKernelParam)
8241         continue;
8242 
8243       if (ParamType == RecordKernelParam) {
8244         VisitStack.push_back(FD);
8245         continue;
8246       }
8247 
8248       // OpenCL v1.2 s6.9.p:
8249       // Arguments to kernel functions that are declared to be a struct or union
8250       // do not allow OpenCL objects to be passed as elements of the struct or
8251       // union.
8252       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8253           ParamType == InvalidAddrSpacePtrKernelParam) {
8254         S.Diag(Param->getLocation(),
8255                diag::err_record_with_pointers_kernel_param)
8256           << PT->isUnionType()
8257           << PT;
8258       } else {
8259         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8260       }
8261 
8262       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8263           << OrigRecDecl->getDeclName();
8264 
8265       // We have an error, now let's go back up through history and show where
8266       // the offending field came from
8267       for (ArrayRef<const FieldDecl *>::const_iterator
8268                I = HistoryStack.begin() + 1,
8269                E = HistoryStack.end();
8270            I != E; ++I) {
8271         const FieldDecl *OuterField = *I;
8272         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8273           << OuterField->getType();
8274       }
8275 
8276       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8277         << QT->isPointerType()
8278         << QT;
8279       D.setInvalidType();
8280       return;
8281     }
8282   } while (!VisitStack.empty());
8283 }
8284 
8285 /// Find the DeclContext in which a tag is implicitly declared if we see an
8286 /// elaborated type specifier in the specified context, and lookup finds
8287 /// nothing.
8288 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8289   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8290     DC = DC->getParent();
8291   return DC;
8292 }
8293 
8294 /// Find the Scope in which a tag is implicitly declared if we see an
8295 /// elaborated type specifier in the specified context, and lookup finds
8296 /// nothing.
8297 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8298   while (S->isClassScope() ||
8299          (LangOpts.CPlusPlus &&
8300           S->isFunctionPrototypeScope()) ||
8301          ((S->getFlags() & Scope::DeclScope) == 0) ||
8302          (S->getEntity() && S->getEntity()->isTransparentContext()))
8303     S = S->getParent();
8304   return S;
8305 }
8306 
8307 NamedDecl*
8308 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8309                               TypeSourceInfo *TInfo, LookupResult &Previous,
8310                               MultiTemplateParamsArg TemplateParamLists,
8311                               bool &AddToScope) {
8312   QualType R = TInfo->getType();
8313 
8314   assert(R->isFunctionType());
8315 
8316   // TODO: consider using NameInfo for diagnostic.
8317   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8318   DeclarationName Name = NameInfo.getName();
8319   StorageClass SC = getFunctionStorageClass(*this, D);
8320 
8321   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8322     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8323          diag::err_invalid_thread)
8324       << DeclSpec::getSpecifierName(TSCS);
8325 
8326   if (D.isFirstDeclarationOfMember())
8327     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8328                            D.getIdentifierLoc());
8329 
8330   bool isFriend = false;
8331   FunctionTemplateDecl *FunctionTemplate = nullptr;
8332   bool isMemberSpecialization = false;
8333   bool isFunctionTemplateSpecialization = false;
8334 
8335   bool isDependentClassScopeExplicitSpecialization = false;
8336   bool HasExplicitTemplateArgs = false;
8337   TemplateArgumentListInfo TemplateArgs;
8338 
8339   bool isVirtualOkay = false;
8340 
8341   DeclContext *OriginalDC = DC;
8342   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8343 
8344   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8345                                               isVirtualOkay);
8346   if (!NewFD) return nullptr;
8347 
8348   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8349     NewFD->setTopLevelDeclInObjCContainer();
8350 
8351   // Set the lexical context. If this is a function-scope declaration, or has a
8352   // C++ scope specifier, or is the object of a friend declaration, the lexical
8353   // context will be different from the semantic context.
8354   NewFD->setLexicalDeclContext(CurContext);
8355 
8356   if (IsLocalExternDecl)
8357     NewFD->setLocalExternDecl();
8358 
8359   if (getLangOpts().CPlusPlus) {
8360     bool isInline = D.getDeclSpec().isInlineSpecified();
8361     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8362     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8363     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8364     isFriend = D.getDeclSpec().isFriendSpecified();
8365     if (isFriend && !isInline && D.isFunctionDefinition()) {
8366       // C++ [class.friend]p5
8367       //   A function can be defined in a friend declaration of a
8368       //   class . . . . Such a function is implicitly inline.
8369       NewFD->setImplicitlyInline();
8370     }
8371 
8372     // If this is a method defined in an __interface, and is not a constructor
8373     // or an overloaded operator, then set the pure flag (isVirtual will already
8374     // return true).
8375     if (const CXXRecordDecl *Parent =
8376           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8377       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8378         NewFD->setPure(true);
8379 
8380       // C++ [class.union]p2
8381       //   A union can have member functions, but not virtual functions.
8382       if (isVirtual && Parent->isUnion())
8383         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8384     }
8385 
8386     SetNestedNameSpecifier(NewFD, D);
8387     isMemberSpecialization = false;
8388     isFunctionTemplateSpecialization = false;
8389     if (D.isInvalidType())
8390       NewFD->setInvalidDecl();
8391 
8392     // Match up the template parameter lists with the scope specifier, then
8393     // determine whether we have a template or a template specialization.
8394     bool Invalid = false;
8395     if (TemplateParameterList *TemplateParams =
8396             MatchTemplateParametersToScopeSpecifier(
8397                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8398                 D.getCXXScopeSpec(),
8399                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8400                     ? D.getName().TemplateId
8401                     : nullptr,
8402                 TemplateParamLists, isFriend, isMemberSpecialization,
8403                 Invalid)) {
8404       if (TemplateParams->size() > 0) {
8405         // This is a function template
8406 
8407         // Check that we can declare a template here.
8408         if (CheckTemplateDeclScope(S, TemplateParams))
8409           NewFD->setInvalidDecl();
8410 
8411         // A destructor cannot be a template.
8412         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8413           Diag(NewFD->getLocation(), diag::err_destructor_template);
8414           NewFD->setInvalidDecl();
8415         }
8416 
8417         // If we're adding a template to a dependent context, we may need to
8418         // rebuilding some of the types used within the template parameter list,
8419         // now that we know what the current instantiation is.
8420         if (DC->isDependentContext()) {
8421           ContextRAII SavedContext(*this, DC);
8422           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8423             Invalid = true;
8424         }
8425 
8426         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8427                                                         NewFD->getLocation(),
8428                                                         Name, TemplateParams,
8429                                                         NewFD);
8430         FunctionTemplate->setLexicalDeclContext(CurContext);
8431         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8432 
8433         // For source fidelity, store the other template param lists.
8434         if (TemplateParamLists.size() > 1) {
8435           NewFD->setTemplateParameterListsInfo(Context,
8436                                                TemplateParamLists.drop_back(1));
8437         }
8438       } else {
8439         // This is a function template specialization.
8440         isFunctionTemplateSpecialization = true;
8441         // For source fidelity, store all the template param lists.
8442         if (TemplateParamLists.size() > 0)
8443           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8444 
8445         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8446         if (isFriend) {
8447           // We want to remove the "template<>", found here.
8448           SourceRange RemoveRange = TemplateParams->getSourceRange();
8449 
8450           // If we remove the template<> and the name is not a
8451           // template-id, we're actually silently creating a problem:
8452           // the friend declaration will refer to an untemplated decl,
8453           // and clearly the user wants a template specialization.  So
8454           // we need to insert '<>' after the name.
8455           SourceLocation InsertLoc;
8456           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8457             InsertLoc = D.getName().getSourceRange().getEnd();
8458             InsertLoc = getLocForEndOfToken(InsertLoc);
8459           }
8460 
8461           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8462             << Name << RemoveRange
8463             << FixItHint::CreateRemoval(RemoveRange)
8464             << FixItHint::CreateInsertion(InsertLoc, "<>");
8465         }
8466       }
8467     } else {
8468       // All template param lists were matched against the scope specifier:
8469       // this is NOT (an explicit specialization of) a template.
8470       if (TemplateParamLists.size() > 0)
8471         // For source fidelity, store all the template param lists.
8472         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8473     }
8474 
8475     if (Invalid) {
8476       NewFD->setInvalidDecl();
8477       if (FunctionTemplate)
8478         FunctionTemplate->setInvalidDecl();
8479     }
8480 
8481     // C++ [dcl.fct.spec]p5:
8482     //   The virtual specifier shall only be used in declarations of
8483     //   nonstatic class member functions that appear within a
8484     //   member-specification of a class declaration; see 10.3.
8485     //
8486     if (isVirtual && !NewFD->isInvalidDecl()) {
8487       if (!isVirtualOkay) {
8488         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8489              diag::err_virtual_non_function);
8490       } else if (!CurContext->isRecord()) {
8491         // 'virtual' was specified outside of the class.
8492         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8493              diag::err_virtual_out_of_class)
8494           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8495       } else if (NewFD->getDescribedFunctionTemplate()) {
8496         // C++ [temp.mem]p3:
8497         //  A member function template shall not be virtual.
8498         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8499              diag::err_virtual_member_function_template)
8500           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8501       } else {
8502         // Okay: Add virtual to the method.
8503         NewFD->setVirtualAsWritten(true);
8504       }
8505 
8506       if (getLangOpts().CPlusPlus14 &&
8507           NewFD->getReturnType()->isUndeducedType())
8508         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8509     }
8510 
8511     if (getLangOpts().CPlusPlus14 &&
8512         (NewFD->isDependentContext() ||
8513          (isFriend && CurContext->isDependentContext())) &&
8514         NewFD->getReturnType()->isUndeducedType()) {
8515       // If the function template is referenced directly (for instance, as a
8516       // member of the current instantiation), pretend it has a dependent type.
8517       // This is not really justified by the standard, but is the only sane
8518       // thing to do.
8519       // FIXME: For a friend function, we have not marked the function as being
8520       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8521       const FunctionProtoType *FPT =
8522           NewFD->getType()->castAs<FunctionProtoType>();
8523       QualType Result =
8524           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8525       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8526                                              FPT->getExtProtoInfo()));
8527     }
8528 
8529     // C++ [dcl.fct.spec]p3:
8530     //  The inline specifier shall not appear on a block scope function
8531     //  declaration.
8532     if (isInline && !NewFD->isInvalidDecl()) {
8533       if (CurContext->isFunctionOrMethod()) {
8534         // 'inline' is not allowed on block scope function declaration.
8535         Diag(D.getDeclSpec().getInlineSpecLoc(),
8536              diag::err_inline_declaration_block_scope) << Name
8537           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8538       }
8539     }
8540 
8541     // C++ [dcl.fct.spec]p6:
8542     //  The explicit specifier shall be used only in the declaration of a
8543     //  constructor or conversion function within its class definition;
8544     //  see 12.3.1 and 12.3.2.
8545     if (isExplicit && !NewFD->isInvalidDecl() &&
8546         !isa<CXXDeductionGuideDecl>(NewFD)) {
8547       if (!CurContext->isRecord()) {
8548         // 'explicit' was specified outside of the class.
8549         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8550              diag::err_explicit_out_of_class)
8551           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8552       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8553                  !isa<CXXConversionDecl>(NewFD)) {
8554         // 'explicit' was specified on a function that wasn't a constructor
8555         // or conversion function.
8556         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8557              diag::err_explicit_non_ctor_or_conv_function)
8558           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8559       }
8560     }
8561 
8562     if (isConstexpr) {
8563       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8564       // are implicitly inline.
8565       NewFD->setImplicitlyInline();
8566 
8567       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8568       // be either constructors or to return a literal type. Therefore,
8569       // destructors cannot be declared constexpr.
8570       if (isa<CXXDestructorDecl>(NewFD))
8571         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8572     }
8573 
8574     // If __module_private__ was specified, mark the function accordingly.
8575     if (D.getDeclSpec().isModulePrivateSpecified()) {
8576       if (isFunctionTemplateSpecialization) {
8577         SourceLocation ModulePrivateLoc
8578           = D.getDeclSpec().getModulePrivateSpecLoc();
8579         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8580           << 0
8581           << FixItHint::CreateRemoval(ModulePrivateLoc);
8582       } else {
8583         NewFD->setModulePrivate();
8584         if (FunctionTemplate)
8585           FunctionTemplate->setModulePrivate();
8586       }
8587     }
8588 
8589     if (isFriend) {
8590       if (FunctionTemplate) {
8591         FunctionTemplate->setObjectOfFriendDecl();
8592         FunctionTemplate->setAccess(AS_public);
8593       }
8594       NewFD->setObjectOfFriendDecl();
8595       NewFD->setAccess(AS_public);
8596     }
8597 
8598     // If a function is defined as defaulted or deleted, mark it as such now.
8599     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8600     // definition kind to FDK_Definition.
8601     switch (D.getFunctionDefinitionKind()) {
8602       case FDK_Declaration:
8603       case FDK_Definition:
8604         break;
8605 
8606       case FDK_Defaulted:
8607         NewFD->setDefaulted();
8608         break;
8609 
8610       case FDK_Deleted:
8611         NewFD->setDeletedAsWritten();
8612         break;
8613     }
8614 
8615     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8616         D.isFunctionDefinition()) {
8617       // C++ [class.mfct]p2:
8618       //   A member function may be defined (8.4) in its class definition, in
8619       //   which case it is an inline member function (7.1.2)
8620       NewFD->setImplicitlyInline();
8621     }
8622 
8623     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8624         !CurContext->isRecord()) {
8625       // C++ [class.static]p1:
8626       //   A data or function member of a class may be declared static
8627       //   in a class definition, in which case it is a static member of
8628       //   the class.
8629 
8630       // Complain about the 'static' specifier if it's on an out-of-line
8631       // member function definition.
8632       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8633            diag::err_static_out_of_line)
8634         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8635     }
8636 
8637     // C++11 [except.spec]p15:
8638     //   A deallocation function with no exception-specification is treated
8639     //   as if it were specified with noexcept(true).
8640     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8641     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8642          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8643         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8644       NewFD->setType(Context.getFunctionType(
8645           FPT->getReturnType(), FPT->getParamTypes(),
8646           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8647   }
8648 
8649   // Filter out previous declarations that don't match the scope.
8650   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8651                        D.getCXXScopeSpec().isNotEmpty() ||
8652                        isMemberSpecialization ||
8653                        isFunctionTemplateSpecialization);
8654 
8655   // Handle GNU asm-label extension (encoded as an attribute).
8656   if (Expr *E = (Expr*) D.getAsmLabel()) {
8657     // The parser guarantees this is a string.
8658     StringLiteral *SE = cast<StringLiteral>(E);
8659     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8660                                                 SE->getString(), 0));
8661   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8662     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8663       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8664     if (I != ExtnameUndeclaredIdentifiers.end()) {
8665       if (isDeclExternC(NewFD)) {
8666         NewFD->addAttr(I->second);
8667         ExtnameUndeclaredIdentifiers.erase(I);
8668       } else
8669         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8670             << /*Variable*/0 << NewFD;
8671     }
8672   }
8673 
8674   // Copy the parameter declarations from the declarator D to the function
8675   // declaration NewFD, if they are available.  First scavenge them into Params.
8676   SmallVector<ParmVarDecl*, 16> Params;
8677   unsigned FTIIdx;
8678   if (D.isFunctionDeclarator(FTIIdx)) {
8679     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8680 
8681     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8682     // function that takes no arguments, not a function that takes a
8683     // single void argument.
8684     // We let through "const void" here because Sema::GetTypeForDeclarator
8685     // already checks for that case.
8686     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8687       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8688         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8689         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8690         Param->setDeclContext(NewFD);
8691         Params.push_back(Param);
8692 
8693         if (Param->isInvalidDecl())
8694           NewFD->setInvalidDecl();
8695       }
8696     }
8697 
8698     if (!getLangOpts().CPlusPlus) {
8699       // In C, find all the tag declarations from the prototype and move them
8700       // into the function DeclContext. Remove them from the surrounding tag
8701       // injection context of the function, which is typically but not always
8702       // the TU.
8703       DeclContext *PrototypeTagContext =
8704           getTagInjectionContext(NewFD->getLexicalDeclContext());
8705       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8706         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8707 
8708         // We don't want to reparent enumerators. Look at their parent enum
8709         // instead.
8710         if (!TD) {
8711           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8712             TD = cast<EnumDecl>(ECD->getDeclContext());
8713         }
8714         if (!TD)
8715           continue;
8716         DeclContext *TagDC = TD->getLexicalDeclContext();
8717         if (!TagDC->containsDecl(TD))
8718           continue;
8719         TagDC->removeDecl(TD);
8720         TD->setDeclContext(NewFD);
8721         NewFD->addDecl(TD);
8722 
8723         // Preserve the lexical DeclContext if it is not the surrounding tag
8724         // injection context of the FD. In this example, the semantic context of
8725         // E will be f and the lexical context will be S, while both the
8726         // semantic and lexical contexts of S will be f:
8727         //   void f(struct S { enum E { a } f; } s);
8728         if (TagDC != PrototypeTagContext)
8729           TD->setLexicalDeclContext(TagDC);
8730       }
8731     }
8732   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8733     // When we're declaring a function with a typedef, typeof, etc as in the
8734     // following example, we'll need to synthesize (unnamed)
8735     // parameters for use in the declaration.
8736     //
8737     // @code
8738     // typedef void fn(int);
8739     // fn f;
8740     // @endcode
8741 
8742     // Synthesize a parameter for each argument type.
8743     for (const auto &AI : FT->param_types()) {
8744       ParmVarDecl *Param =
8745           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8746       Param->setScopeInfo(0, Params.size());
8747       Params.push_back(Param);
8748     }
8749   } else {
8750     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8751            "Should not need args for typedef of non-prototype fn");
8752   }
8753 
8754   // Finally, we know we have the right number of parameters, install them.
8755   NewFD->setParams(Params);
8756 
8757   if (D.getDeclSpec().isNoreturnSpecified())
8758     NewFD->addAttr(
8759         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8760                                        Context, 0));
8761 
8762   // Functions returning a variably modified type violate C99 6.7.5.2p2
8763   // because all functions have linkage.
8764   if (!NewFD->isInvalidDecl() &&
8765       NewFD->getReturnType()->isVariablyModifiedType()) {
8766     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8767     NewFD->setInvalidDecl();
8768   }
8769 
8770   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8771   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8772       !NewFD->hasAttr<SectionAttr>()) {
8773     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8774                                                  PragmaClangTextSection.SectionName,
8775                                                  PragmaClangTextSection.PragmaLocation));
8776   }
8777 
8778   // Apply an implicit SectionAttr if #pragma code_seg is active.
8779   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8780       !NewFD->hasAttr<SectionAttr>()) {
8781     NewFD->addAttr(
8782         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8783                                     CodeSegStack.CurrentValue->getString(),
8784                                     CodeSegStack.CurrentPragmaLocation));
8785     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8786                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8787                          ASTContext::PSF_Read,
8788                      NewFD))
8789       NewFD->dropAttr<SectionAttr>();
8790   }
8791 
8792   // Apply an implicit CodeSegAttr from class declspec or
8793   // apply an implicit SectionAttr from #pragma code_seg if active.
8794   if (!NewFD->hasAttr<CodeSegAttr>()) {
8795     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8796                                                                  D.isFunctionDefinition())) {
8797       NewFD->addAttr(SAttr);
8798     }
8799   }
8800 
8801   // Handle attributes.
8802   ProcessDeclAttributes(S, NewFD, D);
8803 
8804   if (getLangOpts().OpenCL) {
8805     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8806     // type declaration will generate a compilation error.
8807     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8808     if (AddressSpace != LangAS::Default) {
8809       Diag(NewFD->getLocation(),
8810            diag::err_opencl_return_value_with_address_space);
8811       NewFD->setInvalidDecl();
8812     }
8813   }
8814 
8815   if (!getLangOpts().CPlusPlus) {
8816     // Perform semantic checking on the function declaration.
8817     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8818       CheckMain(NewFD, D.getDeclSpec());
8819 
8820     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8821       CheckMSVCRTEntryPoint(NewFD);
8822 
8823     if (!NewFD->isInvalidDecl())
8824       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8825                                                   isMemberSpecialization));
8826     else if (!Previous.empty())
8827       // Recover gracefully from an invalid redeclaration.
8828       D.setRedeclaration(true);
8829     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8830             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8831            "previous declaration set still overloaded");
8832 
8833     // Diagnose no-prototype function declarations with calling conventions that
8834     // don't support variadic calls. Only do this in C and do it after merging
8835     // possibly prototyped redeclarations.
8836     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8837     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8838       CallingConv CC = FT->getExtInfo().getCC();
8839       if (!supportsVariadicCall(CC)) {
8840         // Windows system headers sometimes accidentally use stdcall without
8841         // (void) parameters, so we relax this to a warning.
8842         int DiagID =
8843             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8844         Diag(NewFD->getLocation(), DiagID)
8845             << FunctionType::getNameForCallConv(CC);
8846       }
8847     }
8848   } else {
8849     // C++11 [replacement.functions]p3:
8850     //  The program's definitions shall not be specified as inline.
8851     //
8852     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8853     //
8854     // Suppress the diagnostic if the function is __attribute__((used)), since
8855     // that forces an external definition to be emitted.
8856     if (D.getDeclSpec().isInlineSpecified() &&
8857         NewFD->isReplaceableGlobalAllocationFunction() &&
8858         !NewFD->hasAttr<UsedAttr>())
8859       Diag(D.getDeclSpec().getInlineSpecLoc(),
8860            diag::ext_operator_new_delete_declared_inline)
8861         << NewFD->getDeclName();
8862 
8863     // If the declarator is a template-id, translate the parser's template
8864     // argument list into our AST format.
8865     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8866       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8867       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8868       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8869       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8870                                          TemplateId->NumArgs);
8871       translateTemplateArguments(TemplateArgsPtr,
8872                                  TemplateArgs);
8873 
8874       HasExplicitTemplateArgs = true;
8875 
8876       if (NewFD->isInvalidDecl()) {
8877         HasExplicitTemplateArgs = false;
8878       } else if (FunctionTemplate) {
8879         // Function template with explicit template arguments.
8880         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8881           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8882 
8883         HasExplicitTemplateArgs = false;
8884       } else {
8885         assert((isFunctionTemplateSpecialization ||
8886                 D.getDeclSpec().isFriendSpecified()) &&
8887                "should have a 'template<>' for this decl");
8888         // "friend void foo<>(int);" is an implicit specialization decl.
8889         isFunctionTemplateSpecialization = true;
8890       }
8891     } else if (isFriend && isFunctionTemplateSpecialization) {
8892       // This combination is only possible in a recovery case;  the user
8893       // wrote something like:
8894       //   template <> friend void foo(int);
8895       // which we're recovering from as if the user had written:
8896       //   friend void foo<>(int);
8897       // Go ahead and fake up a template id.
8898       HasExplicitTemplateArgs = true;
8899       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8900       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8901     }
8902 
8903     // We do not add HD attributes to specializations here because
8904     // they may have different constexpr-ness compared to their
8905     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8906     // may end up with different effective targets. Instead, a
8907     // specialization inherits its target attributes from its template
8908     // in the CheckFunctionTemplateSpecialization() call below.
8909     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8910       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8911 
8912     // If it's a friend (and only if it's a friend), it's possible
8913     // that either the specialized function type or the specialized
8914     // template is dependent, and therefore matching will fail.  In
8915     // this case, don't check the specialization yet.
8916     bool InstantiationDependent = false;
8917     if (isFunctionTemplateSpecialization && isFriend &&
8918         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8919          TemplateSpecializationType::anyDependentTemplateArguments(
8920             TemplateArgs,
8921             InstantiationDependent))) {
8922       assert(HasExplicitTemplateArgs &&
8923              "friend function specialization without template args");
8924       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8925                                                        Previous))
8926         NewFD->setInvalidDecl();
8927     } else if (isFunctionTemplateSpecialization) {
8928       if (CurContext->isDependentContext() && CurContext->isRecord()
8929           && !isFriend) {
8930         isDependentClassScopeExplicitSpecialization = true;
8931       } else if (!NewFD->isInvalidDecl() &&
8932                  CheckFunctionTemplateSpecialization(
8933                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8934                      Previous))
8935         NewFD->setInvalidDecl();
8936 
8937       // C++ [dcl.stc]p1:
8938       //   A storage-class-specifier shall not be specified in an explicit
8939       //   specialization (14.7.3)
8940       FunctionTemplateSpecializationInfo *Info =
8941           NewFD->getTemplateSpecializationInfo();
8942       if (Info && SC != SC_None) {
8943         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8944           Diag(NewFD->getLocation(),
8945                diag::err_explicit_specialization_inconsistent_storage_class)
8946             << SC
8947             << FixItHint::CreateRemoval(
8948                                       D.getDeclSpec().getStorageClassSpecLoc());
8949 
8950         else
8951           Diag(NewFD->getLocation(),
8952                diag::ext_explicit_specialization_storage_class)
8953             << FixItHint::CreateRemoval(
8954                                       D.getDeclSpec().getStorageClassSpecLoc());
8955       }
8956     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8957       if (CheckMemberSpecialization(NewFD, Previous))
8958           NewFD->setInvalidDecl();
8959     }
8960 
8961     // Perform semantic checking on the function declaration.
8962     if (!isDependentClassScopeExplicitSpecialization) {
8963       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8964         CheckMain(NewFD, D.getDeclSpec());
8965 
8966       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8967         CheckMSVCRTEntryPoint(NewFD);
8968 
8969       if (!NewFD->isInvalidDecl())
8970         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8971                                                     isMemberSpecialization));
8972       else if (!Previous.empty())
8973         // Recover gracefully from an invalid redeclaration.
8974         D.setRedeclaration(true);
8975     }
8976 
8977     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8978             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8979            "previous declaration set still overloaded");
8980 
8981     NamedDecl *PrincipalDecl = (FunctionTemplate
8982                                 ? cast<NamedDecl>(FunctionTemplate)
8983                                 : NewFD);
8984 
8985     if (isFriend && NewFD->getPreviousDecl()) {
8986       AccessSpecifier Access = AS_public;
8987       if (!NewFD->isInvalidDecl())
8988         Access = NewFD->getPreviousDecl()->getAccess();
8989 
8990       NewFD->setAccess(Access);
8991       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8992     }
8993 
8994     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8995         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8996       PrincipalDecl->setNonMemberOperator();
8997 
8998     // If we have a function template, check the template parameter
8999     // list. This will check and merge default template arguments.
9000     if (FunctionTemplate) {
9001       FunctionTemplateDecl *PrevTemplate =
9002                                      FunctionTemplate->getPreviousDecl();
9003       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9004                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9005                                     : nullptr,
9006                             D.getDeclSpec().isFriendSpecified()
9007                               ? (D.isFunctionDefinition()
9008                                    ? TPC_FriendFunctionTemplateDefinition
9009                                    : TPC_FriendFunctionTemplate)
9010                               : (D.getCXXScopeSpec().isSet() &&
9011                                  DC && DC->isRecord() &&
9012                                  DC->isDependentContext())
9013                                   ? TPC_ClassTemplateMember
9014                                   : TPC_FunctionTemplate);
9015     }
9016 
9017     if (NewFD->isInvalidDecl()) {
9018       // Ignore all the rest of this.
9019     } else if (!D.isRedeclaration()) {
9020       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9021                                        AddToScope };
9022       // Fake up an access specifier if it's supposed to be a class member.
9023       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9024         NewFD->setAccess(AS_public);
9025 
9026       // Qualified decls generally require a previous declaration.
9027       if (D.getCXXScopeSpec().isSet()) {
9028         // ...with the major exception of templated-scope or
9029         // dependent-scope friend declarations.
9030 
9031         // TODO: we currently also suppress this check in dependent
9032         // contexts because (1) the parameter depth will be off when
9033         // matching friend templates and (2) we might actually be
9034         // selecting a friend based on a dependent factor.  But there
9035         // are situations where these conditions don't apply and we
9036         // can actually do this check immediately.
9037         if (isFriend &&
9038             (TemplateParamLists.size() ||
9039              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9040              CurContext->isDependentContext())) {
9041           // ignore these
9042         } else {
9043           // The user tried to provide an out-of-line definition for a
9044           // function that is a member of a class or namespace, but there
9045           // was no such member function declared (C++ [class.mfct]p2,
9046           // C++ [namespace.memdef]p2). For example:
9047           //
9048           // class X {
9049           //   void f() const;
9050           // };
9051           //
9052           // void X::f() { } // ill-formed
9053           //
9054           // Complain about this problem, and attempt to suggest close
9055           // matches (e.g., those that differ only in cv-qualifiers and
9056           // whether the parameter types are references).
9057 
9058           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9059                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9060             AddToScope = ExtraArgs.AddToScope;
9061             return Result;
9062           }
9063         }
9064 
9065         // Unqualified local friend declarations are required to resolve
9066         // to something.
9067       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9068         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9069                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9070           AddToScope = ExtraArgs.AddToScope;
9071           return Result;
9072         }
9073       }
9074     } else if (!D.isFunctionDefinition() &&
9075                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9076                !isFriend && !isFunctionTemplateSpecialization &&
9077                !isMemberSpecialization) {
9078       // An out-of-line member function declaration must also be a
9079       // definition (C++ [class.mfct]p2).
9080       // Note that this is not the case for explicit specializations of
9081       // function templates or member functions of class templates, per
9082       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9083       // extension for compatibility with old SWIG code which likes to
9084       // generate them.
9085       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9086         << D.getCXXScopeSpec().getRange();
9087     }
9088   }
9089 
9090   ProcessPragmaWeak(S, NewFD);
9091   checkAttributesAfterMerging(*this, *NewFD);
9092 
9093   AddKnownFunctionAttributes(NewFD);
9094 
9095   if (NewFD->hasAttr<OverloadableAttr>() &&
9096       !NewFD->getType()->getAs<FunctionProtoType>()) {
9097     Diag(NewFD->getLocation(),
9098          diag::err_attribute_overloadable_no_prototype)
9099       << NewFD;
9100 
9101     // Turn this into a variadic function with no parameters.
9102     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9103     FunctionProtoType::ExtProtoInfo EPI(
9104         Context.getDefaultCallingConvention(true, false));
9105     EPI.Variadic = true;
9106     EPI.ExtInfo = FT->getExtInfo();
9107 
9108     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9109     NewFD->setType(R);
9110   }
9111 
9112   // If there's a #pragma GCC visibility in scope, and this isn't a class
9113   // member, set the visibility of this function.
9114   if (!DC->isRecord() && NewFD->isExternallyVisible())
9115     AddPushedVisibilityAttribute(NewFD);
9116 
9117   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9118   // marking the function.
9119   AddCFAuditedAttribute(NewFD);
9120 
9121   // If this is a function definition, check if we have to apply optnone due to
9122   // a pragma.
9123   if(D.isFunctionDefinition())
9124     AddRangeBasedOptnone(NewFD);
9125 
9126   // If this is the first declaration of an extern C variable, update
9127   // the map of such variables.
9128   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9129       isIncompleteDeclExternC(*this, NewFD))
9130     RegisterLocallyScopedExternCDecl(NewFD, S);
9131 
9132   // Set this FunctionDecl's range up to the right paren.
9133   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9134 
9135   if (D.isRedeclaration() && !Previous.empty()) {
9136     NamedDecl *Prev = Previous.getRepresentativeDecl();
9137     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9138                                    isMemberSpecialization ||
9139                                        isFunctionTemplateSpecialization,
9140                                    D.isFunctionDefinition());
9141   }
9142 
9143   if (getLangOpts().CUDA) {
9144     IdentifierInfo *II = NewFD->getIdentifier();
9145     if (II &&
9146         II->isStr(getLangOpts().HIP ? "hipConfigureCall"
9147                                     : "cudaConfigureCall") &&
9148         !NewFD->isInvalidDecl() &&
9149         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9150       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9151         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9152       Context.setcudaConfigureCallDecl(NewFD);
9153     }
9154 
9155     // Variadic functions, other than a *declaration* of printf, are not allowed
9156     // in device-side CUDA code, unless someone passed
9157     // -fcuda-allow-variadic-functions.
9158     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9159         (NewFD->hasAttr<CUDADeviceAttr>() ||
9160          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9161         !(II && II->isStr("printf") && NewFD->isExternC() &&
9162           !D.isFunctionDefinition())) {
9163       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9164     }
9165   }
9166 
9167   MarkUnusedFileScopedDecl(NewFD);
9168 
9169   if (getLangOpts().CPlusPlus) {
9170     if (FunctionTemplate) {
9171       if (NewFD->isInvalidDecl())
9172         FunctionTemplate->setInvalidDecl();
9173       return FunctionTemplate;
9174     }
9175 
9176     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9177       CompleteMemberSpecialization(NewFD, Previous);
9178   }
9179 
9180   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9181     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9182     if ((getLangOpts().OpenCLVersion >= 120)
9183         && (SC == SC_Static)) {
9184       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9185       D.setInvalidType();
9186     }
9187 
9188     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9189     if (!NewFD->getReturnType()->isVoidType()) {
9190       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9191       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9192           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9193                                 : FixItHint());
9194       D.setInvalidType();
9195     }
9196 
9197     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9198     for (auto Param : NewFD->parameters())
9199       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9200   }
9201   for (const ParmVarDecl *Param : NewFD->parameters()) {
9202     QualType PT = Param->getType();
9203 
9204     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9205     // types.
9206     if (getLangOpts().OpenCLVersion >= 200) {
9207       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9208         QualType ElemTy = PipeTy->getElementType();
9209           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9210             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9211             D.setInvalidType();
9212           }
9213       }
9214     }
9215   }
9216 
9217   // Here we have an function template explicit specialization at class scope.
9218   // The actual specialization will be postponed to template instatiation
9219   // time via the ClassScopeFunctionSpecializationDecl node.
9220   if (isDependentClassScopeExplicitSpecialization) {
9221     ClassScopeFunctionSpecializationDecl *NewSpec =
9222                          ClassScopeFunctionSpecializationDecl::Create(
9223                                 Context, CurContext, NewFD->getLocation(),
9224                                 cast<CXXMethodDecl>(NewFD),
9225                                 HasExplicitTemplateArgs, TemplateArgs);
9226     CurContext->addDecl(NewSpec);
9227     AddToScope = false;
9228   }
9229 
9230   // Diagnose availability attributes. Availability cannot be used on functions
9231   // that are run during load/unload.
9232   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9233     if (NewFD->hasAttr<ConstructorAttr>()) {
9234       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9235           << 1;
9236       NewFD->dropAttr<AvailabilityAttr>();
9237     }
9238     if (NewFD->hasAttr<DestructorAttr>()) {
9239       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9240           << 2;
9241       NewFD->dropAttr<AvailabilityAttr>();
9242     }
9243   }
9244 
9245   return NewFD;
9246 }
9247 
9248 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9249 /// when __declspec(code_seg) "is applied to a class, all member functions of
9250 /// the class and nested classes -- this includes compiler-generated special
9251 /// member functions -- are put in the specified segment."
9252 /// The actual behavior is a little more complicated. The Microsoft compiler
9253 /// won't check outer classes if there is an active value from #pragma code_seg.
9254 /// The CodeSeg is always applied from the direct parent but only from outer
9255 /// classes when the #pragma code_seg stack is empty. See:
9256 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9257 /// available since MS has removed the page.
9258 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9259   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9260   if (!Method)
9261     return nullptr;
9262   const CXXRecordDecl *Parent = Method->getParent();
9263   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9264     Attr *NewAttr = SAttr->clone(S.getASTContext());
9265     NewAttr->setImplicit(true);
9266     return NewAttr;
9267   }
9268 
9269   // The Microsoft compiler won't check outer classes for the CodeSeg
9270   // when the #pragma code_seg stack is active.
9271   if (S.CodeSegStack.CurrentValue)
9272    return nullptr;
9273 
9274   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9275     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9276       Attr *NewAttr = SAttr->clone(S.getASTContext());
9277       NewAttr->setImplicit(true);
9278       return NewAttr;
9279     }
9280   }
9281   return nullptr;
9282 }
9283 
9284 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9285 /// containing class. Otherwise it will return implicit SectionAttr if the
9286 /// function is a definition and there is an active value on CodeSegStack
9287 /// (from the current #pragma code-seg value).
9288 ///
9289 /// \param FD Function being declared.
9290 /// \param IsDefinition Whether it is a definition or just a declarartion.
9291 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9292 ///          nullptr if no attribute should be added.
9293 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9294                                                        bool IsDefinition) {
9295   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9296     return A;
9297   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9298       CodeSegStack.CurrentValue) {
9299     return SectionAttr::CreateImplicit(getASTContext(),
9300                                        SectionAttr::Declspec_allocate,
9301                                        CodeSegStack.CurrentValue->getString(),
9302                                        CodeSegStack.CurrentPragmaLocation);
9303   }
9304   return nullptr;
9305 }
9306 /// Checks if the new declaration declared in dependent context must be
9307 /// put in the same redeclaration chain as the specified declaration.
9308 ///
9309 /// \param D Declaration that is checked.
9310 /// \param PrevDecl Previous declaration found with proper lookup method for the
9311 ///                 same declaration name.
9312 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9313 ///          belongs to.
9314 ///
9315 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9316   // Any declarations should be put into redeclaration chains except for
9317   // friend declaration in a dependent context that names a function in
9318   // namespace scope.
9319   //
9320   // This allows to compile code like:
9321   //
9322   //       void func();
9323   //       template<typename T> class C1 { friend void func() { } };
9324   //       template<typename T> class C2 { friend void func() { } };
9325   //
9326   // This code snippet is a valid code unless both templates are instantiated.
9327   return !(D->getLexicalDeclContext()->isDependentContext() &&
9328            D->getDeclContext()->isFileContext() &&
9329            D->getFriendObjectKind() != Decl::FOK_None);
9330 }
9331 
9332 namespace MultiVersioning {
9333 enum Type { None, Target, CPUSpecific, CPUDispatch};
9334 } // MultiVersionType
9335 
9336 static MultiVersioning::Type
9337 getMultiVersionType(const FunctionDecl *FD) {
9338   if (FD->hasAttr<TargetAttr>())
9339     return MultiVersioning::Target;
9340   if (FD->hasAttr<CPUDispatchAttr>())
9341     return MultiVersioning::CPUDispatch;
9342   if (FD->hasAttr<CPUSpecificAttr>())
9343     return MultiVersioning::CPUSpecific;
9344   return MultiVersioning::None;
9345 }
9346 /// Check the target attribute of the function for MultiVersion
9347 /// validity.
9348 ///
9349 /// Returns true if there was an error, false otherwise.
9350 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9351   const auto *TA = FD->getAttr<TargetAttr>();
9352   assert(TA && "MultiVersion Candidate requires a target attribute");
9353   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9354   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9355   enum ErrType { Feature = 0, Architecture = 1 };
9356 
9357   if (!ParseInfo.Architecture.empty() &&
9358       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9359     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9360         << Architecture << ParseInfo.Architecture;
9361     return true;
9362   }
9363 
9364   for (const auto &Feat : ParseInfo.Features) {
9365     auto BareFeat = StringRef{Feat}.substr(1);
9366     if (Feat[0] == '-') {
9367       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9368           << Feature << ("no-" + BareFeat).str();
9369       return true;
9370     }
9371 
9372     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9373         !TargetInfo.isValidFeatureName(BareFeat)) {
9374       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9375           << Feature << BareFeat;
9376       return true;
9377     }
9378   }
9379   return false;
9380 }
9381 
9382 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9383                                              const FunctionDecl *NewFD,
9384                                              bool CausesMV,
9385                                              MultiVersioning::Type MVType) {
9386   enum DoesntSupport {
9387     FuncTemplates = 0,
9388     VirtFuncs = 1,
9389     DeducedReturn = 2,
9390     Constructors = 3,
9391     Destructors = 4,
9392     DeletedFuncs = 5,
9393     DefaultedFuncs = 6,
9394     ConstexprFuncs = 7,
9395   };
9396   enum Different {
9397     CallingConv = 0,
9398     ReturnType = 1,
9399     ConstexprSpec = 2,
9400     InlineSpec = 3,
9401     StorageClass = 4,
9402     Linkage = 5
9403   };
9404 
9405   bool IsCPUSpecificCPUDispatchMVType =
9406       MVType == MultiVersioning::CPUDispatch ||
9407       MVType == MultiVersioning::CPUSpecific;
9408 
9409   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9410     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9411     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9412     return true;
9413   }
9414 
9415   if (!NewFD->getType()->getAs<FunctionProtoType>())
9416     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9417 
9418   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9419     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9420     if (OldFD)
9421       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9422     return true;
9423   }
9424 
9425   // For now, disallow all other attributes.  These should be opt-in, but
9426   // an analysis of all of them is a future FIXME.
9427   if (CausesMV && OldFD &&
9428       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9429     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9430         << IsCPUSpecificCPUDispatchMVType;
9431     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9432     return true;
9433   }
9434 
9435   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9436     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9437            << IsCPUSpecificCPUDispatchMVType;
9438 
9439   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9440     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9441            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9442 
9443   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9444     if (NewCXXFD->isVirtual())
9445       return S.Diag(NewCXXFD->getLocation(),
9446                     diag::err_multiversion_doesnt_support)
9447              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9448 
9449     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9450       return S.Diag(NewCXXCtor->getLocation(),
9451                     diag::err_multiversion_doesnt_support)
9452              << IsCPUSpecificCPUDispatchMVType << Constructors;
9453 
9454     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9455       return S.Diag(NewCXXDtor->getLocation(),
9456                     diag::err_multiversion_doesnt_support)
9457              << IsCPUSpecificCPUDispatchMVType << Destructors;
9458   }
9459 
9460   if (NewFD->isDeleted())
9461     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9462            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9463 
9464   if (NewFD->isDefaulted())
9465     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9466            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9467 
9468   if (NewFD->isConstexpr() && (MVType == MultiVersioning::CPUDispatch ||
9469                                MVType == MultiVersioning::CPUSpecific))
9470     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9471            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9472 
9473   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9474   const auto *NewType = cast<FunctionType>(NewQType);
9475   QualType NewReturnType = NewType->getReturnType();
9476 
9477   if (NewReturnType->isUndeducedType())
9478     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9479            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9480 
9481   // Only allow transition to MultiVersion if it hasn't been used.
9482   if (OldFD && CausesMV && OldFD->isUsed(false))
9483     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9484 
9485   // Ensure the return type is identical.
9486   if (OldFD) {
9487     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9488     const auto *OldType = cast<FunctionType>(OldQType);
9489     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9490     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9491 
9492     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9493       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9494              << CallingConv;
9495 
9496     QualType OldReturnType = OldType->getReturnType();
9497 
9498     if (OldReturnType != NewReturnType)
9499       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9500              << ReturnType;
9501 
9502     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9503       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9504              << ConstexprSpec;
9505 
9506     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9507       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9508              << InlineSpec;
9509 
9510     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9511       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9512              << StorageClass;
9513 
9514     if (OldFD->isExternC() != NewFD->isExternC())
9515       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9516              << Linkage;
9517 
9518     if (S.CheckEquivalentExceptionSpec(
9519             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9520             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9521       return true;
9522   }
9523   return false;
9524 }
9525 
9526 /// Check the validity of a multiversion function declaration that is the
9527 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9528 ///
9529 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9530 ///
9531 /// Returns true if there was an error, false otherwise.
9532 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9533                                            MultiVersioning::Type MVType,
9534                                            const TargetAttr *TA,
9535                                            const CPUDispatchAttr *CPUDisp,
9536                                            const CPUSpecificAttr *CPUSpec) {
9537   assert(MVType != MultiVersioning::None &&
9538          "Function lacks multiversion attribute");
9539 
9540   // Target only causes MV if it is default, otherwise this is a normal
9541   // function.
9542   if (MVType == MultiVersioning::Target && !TA->isDefaultVersion())
9543     return false;
9544 
9545   if (MVType == MultiVersioning::Target && CheckMultiVersionValue(S, FD)) {
9546     FD->setInvalidDecl();
9547     return true;
9548   }
9549 
9550   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9551     FD->setInvalidDecl();
9552     return true;
9553   }
9554 
9555   FD->setIsMultiVersion();
9556   return false;
9557 }
9558 
9559 static bool CheckTargetCausesMultiVersioning(
9560     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9561     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9562     LookupResult &Previous) {
9563   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9564   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9565   // Sort order doesn't matter, it just needs to be consistent.
9566   llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9567 
9568   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9569   // to change, this is a simple redeclaration.
9570   if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9571     return false;
9572 
9573   // Otherwise, this decl causes MultiVersioning.
9574   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9575     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9576     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9577     NewFD->setInvalidDecl();
9578     return true;
9579   }
9580 
9581   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9582                                        MultiVersioning::Target)) {
9583     NewFD->setInvalidDecl();
9584     return true;
9585   }
9586 
9587   if (CheckMultiVersionValue(S, NewFD)) {
9588     NewFD->setInvalidDecl();
9589     return true;
9590   }
9591 
9592   if (CheckMultiVersionValue(S, OldFD)) {
9593     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9594     NewFD->setInvalidDecl();
9595     return true;
9596   }
9597 
9598   TargetAttr::ParsedTargetAttr OldParsed =
9599       OldTA->parse(std::less<std::string>());
9600 
9601   if (OldParsed == NewParsed) {
9602     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9603     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9604     NewFD->setInvalidDecl();
9605     return true;
9606   }
9607 
9608   for (const auto *FD : OldFD->redecls()) {
9609     const auto *CurTA = FD->getAttr<TargetAttr>();
9610     if (!CurTA || CurTA->isInherited()) {
9611       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9612           << 0;
9613       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9614       NewFD->setInvalidDecl();
9615       return true;
9616     }
9617   }
9618 
9619   OldFD->setIsMultiVersion();
9620   NewFD->setIsMultiVersion();
9621   Redeclaration = false;
9622   MergeTypeWithPrevious = false;
9623   OldDecl = nullptr;
9624   Previous.clear();
9625   return false;
9626 }
9627 
9628 /// Check the validity of a new function declaration being added to an existing
9629 /// multiversioned declaration collection.
9630 static bool CheckMultiVersionAdditionalDecl(
9631     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9632     MultiVersioning::Type NewMVType, const TargetAttr *NewTA,
9633     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9634     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9635     LookupResult &Previous) {
9636 
9637   MultiVersioning::Type OldMVType = getMultiVersionType(OldFD);
9638   // Disallow mixing of multiversioning types.
9639   if ((OldMVType == MultiVersioning::Target &&
9640        NewMVType != MultiVersioning::Target) ||
9641       (NewMVType == MultiVersioning::Target &&
9642        OldMVType != MultiVersioning::Target)) {
9643     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9644     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9645     NewFD->setInvalidDecl();
9646     return true;
9647   }
9648 
9649   TargetAttr::ParsedTargetAttr NewParsed;
9650   if (NewTA) {
9651     NewParsed = NewTA->parse();
9652     llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9653   }
9654 
9655   bool UseMemberUsingDeclRules =
9656       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9657 
9658   // Next, check ALL non-overloads to see if this is a redeclaration of a
9659   // previous member of the MultiVersion set.
9660   for (NamedDecl *ND : Previous) {
9661     FunctionDecl *CurFD = ND->getAsFunction();
9662     if (!CurFD)
9663       continue;
9664     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9665       continue;
9666 
9667     if (NewMVType == MultiVersioning::Target) {
9668       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9669       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9670         NewFD->setIsMultiVersion();
9671         Redeclaration = true;
9672         OldDecl = ND;
9673         return false;
9674       }
9675 
9676       TargetAttr::ParsedTargetAttr CurParsed =
9677           CurTA->parse(std::less<std::string>());
9678       if (CurParsed == NewParsed) {
9679         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9680         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9681         NewFD->setInvalidDecl();
9682         return true;
9683       }
9684     } else {
9685       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9686       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9687       // Handle CPUDispatch/CPUSpecific versions.
9688       // Only 1 CPUDispatch function is allowed, this will make it go through
9689       // the redeclaration errors.
9690       if (NewMVType == MultiVersioning::CPUDispatch &&
9691           CurFD->hasAttr<CPUDispatchAttr>()) {
9692         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9693             std::equal(
9694                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9695                 NewCPUDisp->cpus_begin(),
9696                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9697                   return Cur->getName() == New->getName();
9698                 })) {
9699           NewFD->setIsMultiVersion();
9700           Redeclaration = true;
9701           OldDecl = ND;
9702           return false;
9703         }
9704 
9705         // If the declarations don't match, this is an error condition.
9706         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9707         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9708         NewFD->setInvalidDecl();
9709         return true;
9710       }
9711       if (NewMVType == MultiVersioning::CPUSpecific && CurCPUSpec) {
9712 
9713         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9714             std::equal(
9715                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9716                 NewCPUSpec->cpus_begin(),
9717                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9718                   return Cur->getName() == New->getName();
9719                 })) {
9720           NewFD->setIsMultiVersion();
9721           Redeclaration = true;
9722           OldDecl = ND;
9723           return false;
9724         }
9725 
9726         // Only 1 version of CPUSpecific is allowed for each CPU.
9727         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9728           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9729             if (CurII == NewII) {
9730               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9731                   << NewII;
9732               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9733               NewFD->setInvalidDecl();
9734               return true;
9735             }
9736           }
9737         }
9738       }
9739       // If the two decls aren't the same MVType, there is no possible error
9740       // condition.
9741     }
9742   }
9743 
9744   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9745   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9746   // handled in the attribute adding step.
9747   if (NewMVType == MultiVersioning::Target &&
9748       CheckMultiVersionValue(S, NewFD)) {
9749     NewFD->setInvalidDecl();
9750     return true;
9751   }
9752 
9753   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) {
9754     NewFD->setInvalidDecl();
9755     return true;
9756   }
9757 
9758   NewFD->setIsMultiVersion();
9759   Redeclaration = false;
9760   MergeTypeWithPrevious = false;
9761   OldDecl = nullptr;
9762   Previous.clear();
9763   return false;
9764 }
9765 
9766 
9767 /// Check the validity of a mulitversion function declaration.
9768 /// Also sets the multiversion'ness' of the function itself.
9769 ///
9770 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9771 ///
9772 /// Returns true if there was an error, false otherwise.
9773 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9774                                       bool &Redeclaration, NamedDecl *&OldDecl,
9775                                       bool &MergeTypeWithPrevious,
9776                                       LookupResult &Previous) {
9777   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9778   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9779   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9780 
9781   // Mixing Multiversioning types is prohibited.
9782   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9783       (NewCPUDisp && NewCPUSpec)) {
9784     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9785     NewFD->setInvalidDecl();
9786     return true;
9787   }
9788 
9789   MultiVersioning::Type MVType = getMultiVersionType(NewFD);
9790 
9791   // Main isn't allowed to become a multiversion function, however it IS
9792   // permitted to have 'main' be marked with the 'target' optimization hint.
9793   if (NewFD->isMain()) {
9794     if ((MVType == MultiVersioning::Target && NewTA->isDefaultVersion()) ||
9795         MVType == MultiVersioning::CPUDispatch ||
9796         MVType == MultiVersioning::CPUSpecific) {
9797       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9798       NewFD->setInvalidDecl();
9799       return true;
9800     }
9801     return false;
9802   }
9803 
9804   if (!OldDecl || !OldDecl->getAsFunction() ||
9805       OldDecl->getDeclContext()->getRedeclContext() !=
9806           NewFD->getDeclContext()->getRedeclContext()) {
9807     // If there's no previous declaration, AND this isn't attempting to cause
9808     // multiversioning, this isn't an error condition.
9809     if (MVType == MultiVersioning::None)
9810       return false;
9811     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9812                                           NewCPUSpec);
9813   }
9814 
9815   FunctionDecl *OldFD = OldDecl->getAsFunction();
9816 
9817   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::None)
9818     return false;
9819 
9820   if (OldFD->isMultiVersion() && MVType == MultiVersioning::None) {
9821     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9822         << (getMultiVersionType(OldFD) != MultiVersioning::Target);
9823     NewFD->setInvalidDecl();
9824     return true;
9825   }
9826 
9827   // Handle the target potentially causes multiversioning case.
9828   if (!OldFD->isMultiVersion() && MVType == MultiVersioning::Target)
9829     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9830                                             Redeclaration, OldDecl,
9831                                             MergeTypeWithPrevious, Previous);
9832   // Previous declarations lack CPUDispatch/CPUSpecific.
9833   if (!OldFD->isMultiVersion()) {
9834     S.Diag(OldFD->getLocation(), diag::err_multiversion_required_in_redecl)
9835         << 1;
9836     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9837     NewFD->setInvalidDecl();
9838     return true;
9839   }
9840 
9841   // At this point, we have a multiversion function decl (in OldFD) AND an
9842   // appropriate attribute in the current function decl.  Resolve that these are
9843   // still compatible with previous declarations.
9844   return CheckMultiVersionAdditionalDecl(
9845       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9846       OldDecl, MergeTypeWithPrevious, Previous);
9847 }
9848 
9849 /// Perform semantic checking of a new function declaration.
9850 ///
9851 /// Performs semantic analysis of the new function declaration
9852 /// NewFD. This routine performs all semantic checking that does not
9853 /// require the actual declarator involved in the declaration, and is
9854 /// used both for the declaration of functions as they are parsed
9855 /// (called via ActOnDeclarator) and for the declaration of functions
9856 /// that have been instantiated via C++ template instantiation (called
9857 /// via InstantiateDecl).
9858 ///
9859 /// \param IsMemberSpecialization whether this new function declaration is
9860 /// a member specialization (that replaces any definition provided by the
9861 /// previous declaration).
9862 ///
9863 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9864 ///
9865 /// \returns true if the function declaration is a redeclaration.
9866 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9867                                     LookupResult &Previous,
9868                                     bool IsMemberSpecialization) {
9869   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9870          "Variably modified return types are not handled here");
9871 
9872   // Determine whether the type of this function should be merged with
9873   // a previous visible declaration. This never happens for functions in C++,
9874   // and always happens in C if the previous declaration was visible.
9875   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9876                                !Previous.isShadowed();
9877 
9878   bool Redeclaration = false;
9879   NamedDecl *OldDecl = nullptr;
9880   bool MayNeedOverloadableChecks = false;
9881 
9882   // Merge or overload the declaration with an existing declaration of
9883   // the same name, if appropriate.
9884   if (!Previous.empty()) {
9885     // Determine whether NewFD is an overload of PrevDecl or
9886     // a declaration that requires merging. If it's an overload,
9887     // there's no more work to do here; we'll just add the new
9888     // function to the scope.
9889     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9890       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9891       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9892         Redeclaration = true;
9893         OldDecl = Candidate;
9894       }
9895     } else {
9896       MayNeedOverloadableChecks = true;
9897       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9898                             /*NewIsUsingDecl*/ false)) {
9899       case Ovl_Match:
9900         Redeclaration = true;
9901         break;
9902 
9903       case Ovl_NonFunction:
9904         Redeclaration = true;
9905         break;
9906 
9907       case Ovl_Overload:
9908         Redeclaration = false;
9909         break;
9910       }
9911     }
9912   }
9913 
9914   // Check for a previous extern "C" declaration with this name.
9915   if (!Redeclaration &&
9916       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9917     if (!Previous.empty()) {
9918       // This is an extern "C" declaration with the same name as a previous
9919       // declaration, and thus redeclares that entity...
9920       Redeclaration = true;
9921       OldDecl = Previous.getFoundDecl();
9922       MergeTypeWithPrevious = false;
9923 
9924       // ... except in the presence of __attribute__((overloadable)).
9925       if (OldDecl->hasAttr<OverloadableAttr>() ||
9926           NewFD->hasAttr<OverloadableAttr>()) {
9927         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9928           MayNeedOverloadableChecks = true;
9929           Redeclaration = false;
9930           OldDecl = nullptr;
9931         }
9932       }
9933     }
9934   }
9935 
9936   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9937                                 MergeTypeWithPrevious, Previous))
9938     return Redeclaration;
9939 
9940   // C++11 [dcl.constexpr]p8:
9941   //   A constexpr specifier for a non-static member function that is not
9942   //   a constructor declares that member function to be const.
9943   //
9944   // This needs to be delayed until we know whether this is an out-of-line
9945   // definition of a static member function.
9946   //
9947   // This rule is not present in C++1y, so we produce a backwards
9948   // compatibility warning whenever it happens in C++11.
9949   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9950   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9951       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9952       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9953     CXXMethodDecl *OldMD = nullptr;
9954     if (OldDecl)
9955       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9956     if (!OldMD || !OldMD->isStatic()) {
9957       const FunctionProtoType *FPT =
9958         MD->getType()->castAs<FunctionProtoType>();
9959       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9960       EPI.TypeQuals |= Qualifiers::Const;
9961       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9962                                           FPT->getParamTypes(), EPI));
9963 
9964       // Warn that we did this, if we're not performing template instantiation.
9965       // In that case, we'll have warned already when the template was defined.
9966       if (!inTemplateInstantiation()) {
9967         SourceLocation AddConstLoc;
9968         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9969                 .IgnoreParens().getAs<FunctionTypeLoc>())
9970           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9971 
9972         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9973           << FixItHint::CreateInsertion(AddConstLoc, " const");
9974       }
9975     }
9976   }
9977 
9978   if (Redeclaration) {
9979     // NewFD and OldDecl represent declarations that need to be
9980     // merged.
9981     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9982       NewFD->setInvalidDecl();
9983       return Redeclaration;
9984     }
9985 
9986     Previous.clear();
9987     Previous.addDecl(OldDecl);
9988 
9989     if (FunctionTemplateDecl *OldTemplateDecl =
9990             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9991       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
9992       NewFD->setPreviousDeclaration(OldFD);
9993       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9994       FunctionTemplateDecl *NewTemplateDecl
9995         = NewFD->getDescribedFunctionTemplate();
9996       assert(NewTemplateDecl && "Template/non-template mismatch");
9997       if (NewFD->isCXXClassMember()) {
9998         NewFD->setAccess(OldTemplateDecl->getAccess());
9999         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10000       }
10001 
10002       // If this is an explicit specialization of a member that is a function
10003       // template, mark it as a member specialization.
10004       if (IsMemberSpecialization &&
10005           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10006         NewTemplateDecl->setMemberSpecialization();
10007         assert(OldTemplateDecl->isMemberSpecialization());
10008         // Explicit specializations of a member template do not inherit deleted
10009         // status from the parent member template that they are specializing.
10010         if (OldFD->isDeleted()) {
10011           // FIXME: This assert will not hold in the presence of modules.
10012           assert(OldFD->getCanonicalDecl() == OldFD);
10013           // FIXME: We need an update record for this AST mutation.
10014           OldFD->setDeletedAsWritten(false);
10015         }
10016       }
10017 
10018     } else {
10019       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10020         auto *OldFD = cast<FunctionDecl>(OldDecl);
10021         // This needs to happen first so that 'inline' propagates.
10022         NewFD->setPreviousDeclaration(OldFD);
10023         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10024         if (NewFD->isCXXClassMember())
10025           NewFD->setAccess(OldFD->getAccess());
10026       }
10027     }
10028   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10029              !NewFD->getAttr<OverloadableAttr>()) {
10030     assert((Previous.empty() ||
10031             llvm::any_of(Previous,
10032                          [](const NamedDecl *ND) {
10033                            return ND->hasAttr<OverloadableAttr>();
10034                          })) &&
10035            "Non-redecls shouldn't happen without overloadable present");
10036 
10037     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10038       const auto *FD = dyn_cast<FunctionDecl>(ND);
10039       return FD && !FD->hasAttr<OverloadableAttr>();
10040     });
10041 
10042     if (OtherUnmarkedIter != Previous.end()) {
10043       Diag(NewFD->getLocation(),
10044            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10045       Diag((*OtherUnmarkedIter)->getLocation(),
10046            diag::note_attribute_overloadable_prev_overload)
10047           << false;
10048 
10049       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10050     }
10051   }
10052 
10053   // Semantic checking for this function declaration (in isolation).
10054 
10055   if (getLangOpts().CPlusPlus) {
10056     // C++-specific checks.
10057     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10058       CheckConstructor(Constructor);
10059     } else if (CXXDestructorDecl *Destructor =
10060                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10061       CXXRecordDecl *Record = Destructor->getParent();
10062       QualType ClassType = Context.getTypeDeclType(Record);
10063 
10064       // FIXME: Shouldn't we be able to perform this check even when the class
10065       // type is dependent? Both gcc and edg can handle that.
10066       if (!ClassType->isDependentType()) {
10067         DeclarationName Name
10068           = Context.DeclarationNames.getCXXDestructorName(
10069                                         Context.getCanonicalType(ClassType));
10070         if (NewFD->getDeclName() != Name) {
10071           Diag(NewFD->getLocation(), diag::err_destructor_name);
10072           NewFD->setInvalidDecl();
10073           return Redeclaration;
10074         }
10075       }
10076     } else if (CXXConversionDecl *Conversion
10077                = dyn_cast<CXXConversionDecl>(NewFD)) {
10078       ActOnConversionDeclarator(Conversion);
10079     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10080       if (auto *TD = Guide->getDescribedFunctionTemplate())
10081         CheckDeductionGuideTemplate(TD);
10082 
10083       // A deduction guide is not on the list of entities that can be
10084       // explicitly specialized.
10085       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10086         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10087             << /*explicit specialization*/ 1;
10088     }
10089 
10090     // Find any virtual functions that this function overrides.
10091     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10092       if (!Method->isFunctionTemplateSpecialization() &&
10093           !Method->getDescribedFunctionTemplate() &&
10094           Method->isCanonicalDecl()) {
10095         if (AddOverriddenMethods(Method->getParent(), Method)) {
10096           // If the function was marked as "static", we have a problem.
10097           if (NewFD->getStorageClass() == SC_Static) {
10098             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10099           }
10100         }
10101       }
10102 
10103       if (Method->isStatic())
10104         checkThisInStaticMemberFunctionType(Method);
10105     }
10106 
10107     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10108     if (NewFD->isOverloadedOperator() &&
10109         CheckOverloadedOperatorDeclaration(NewFD)) {
10110       NewFD->setInvalidDecl();
10111       return Redeclaration;
10112     }
10113 
10114     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10115     if (NewFD->getLiteralIdentifier() &&
10116         CheckLiteralOperatorDeclaration(NewFD)) {
10117       NewFD->setInvalidDecl();
10118       return Redeclaration;
10119     }
10120 
10121     // In C++, check default arguments now that we have merged decls. Unless
10122     // the lexical context is the class, because in this case this is done
10123     // during delayed parsing anyway.
10124     if (!CurContext->isRecord())
10125       CheckCXXDefaultArguments(NewFD);
10126 
10127     // If this function declares a builtin function, check the type of this
10128     // declaration against the expected type for the builtin.
10129     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10130       ASTContext::GetBuiltinTypeError Error;
10131       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10132       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10133       // If the type of the builtin differs only in its exception
10134       // specification, that's OK.
10135       // FIXME: If the types do differ in this way, it would be better to
10136       // retain the 'noexcept' form of the type.
10137       if (!T.isNull() &&
10138           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10139                                                             NewFD->getType()))
10140         // The type of this function differs from the type of the builtin,
10141         // so forget about the builtin entirely.
10142         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10143     }
10144 
10145     // If this function is declared as being extern "C", then check to see if
10146     // the function returns a UDT (class, struct, or union type) that is not C
10147     // compatible, and if it does, warn the user.
10148     // But, issue any diagnostic on the first declaration only.
10149     if (Previous.empty() && NewFD->isExternC()) {
10150       QualType R = NewFD->getReturnType();
10151       if (R->isIncompleteType() && !R->isVoidType())
10152         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10153             << NewFD << R;
10154       else if (!R.isPODType(Context) && !R->isVoidType() &&
10155                !R->isObjCObjectPointerType())
10156         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10157     }
10158 
10159     // C++1z [dcl.fct]p6:
10160     //   [...] whether the function has a non-throwing exception-specification
10161     //   [is] part of the function type
10162     //
10163     // This results in an ABI break between C++14 and C++17 for functions whose
10164     // declared type includes an exception-specification in a parameter or
10165     // return type. (Exception specifications on the function itself are OK in
10166     // most cases, and exception specifications are not permitted in most other
10167     // contexts where they could make it into a mangling.)
10168     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10169       auto HasNoexcept = [&](QualType T) -> bool {
10170         // Strip off declarator chunks that could be between us and a function
10171         // type. We don't need to look far, exception specifications are very
10172         // restricted prior to C++17.
10173         if (auto *RT = T->getAs<ReferenceType>())
10174           T = RT->getPointeeType();
10175         else if (T->isAnyPointerType())
10176           T = T->getPointeeType();
10177         else if (auto *MPT = T->getAs<MemberPointerType>())
10178           T = MPT->getPointeeType();
10179         if (auto *FPT = T->getAs<FunctionProtoType>())
10180           if (FPT->isNothrow())
10181             return true;
10182         return false;
10183       };
10184 
10185       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10186       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10187       for (QualType T : FPT->param_types())
10188         AnyNoexcept |= HasNoexcept(T);
10189       if (AnyNoexcept)
10190         Diag(NewFD->getLocation(),
10191              diag::warn_cxx17_compat_exception_spec_in_signature)
10192             << NewFD;
10193     }
10194 
10195     if (!Redeclaration && LangOpts.CUDA)
10196       checkCUDATargetOverload(NewFD, Previous);
10197   }
10198   return Redeclaration;
10199 }
10200 
10201 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10202   // C++11 [basic.start.main]p3:
10203   //   A program that [...] declares main to be inline, static or
10204   //   constexpr is ill-formed.
10205   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10206   //   appear in a declaration of main.
10207   // static main is not an error under C99, but we should warn about it.
10208   // We accept _Noreturn main as an extension.
10209   if (FD->getStorageClass() == SC_Static)
10210     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10211          ? diag::err_static_main : diag::warn_static_main)
10212       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10213   if (FD->isInlineSpecified())
10214     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10215       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10216   if (DS.isNoreturnSpecified()) {
10217     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10218     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10219     Diag(NoreturnLoc, diag::ext_noreturn_main);
10220     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10221       << FixItHint::CreateRemoval(NoreturnRange);
10222   }
10223   if (FD->isConstexpr()) {
10224     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10225       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10226     FD->setConstexpr(false);
10227   }
10228 
10229   if (getLangOpts().OpenCL) {
10230     Diag(FD->getLocation(), diag::err_opencl_no_main)
10231         << FD->hasAttr<OpenCLKernelAttr>();
10232     FD->setInvalidDecl();
10233     return;
10234   }
10235 
10236   QualType T = FD->getType();
10237   assert(T->isFunctionType() && "function decl is not of function type");
10238   const FunctionType* FT = T->castAs<FunctionType>();
10239 
10240   // Set default calling convention for main()
10241   if (FT->getCallConv() != CC_C) {
10242     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10243     FD->setType(QualType(FT, 0));
10244     T = Context.getCanonicalType(FD->getType());
10245   }
10246 
10247   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10248     // In C with GNU extensions we allow main() to have non-integer return
10249     // type, but we should warn about the extension, and we disable the
10250     // implicit-return-zero rule.
10251 
10252     // GCC in C mode accepts qualified 'int'.
10253     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10254       FD->setHasImplicitReturnZero(true);
10255     else {
10256       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10257       SourceRange RTRange = FD->getReturnTypeSourceRange();
10258       if (RTRange.isValid())
10259         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10260             << FixItHint::CreateReplacement(RTRange, "int");
10261     }
10262   } else {
10263     // In C and C++, main magically returns 0 if you fall off the end;
10264     // set the flag which tells us that.
10265     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10266 
10267     // All the standards say that main() should return 'int'.
10268     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10269       FD->setHasImplicitReturnZero(true);
10270     else {
10271       // Otherwise, this is just a flat-out error.
10272       SourceRange RTRange = FD->getReturnTypeSourceRange();
10273       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10274           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10275                                 : FixItHint());
10276       FD->setInvalidDecl(true);
10277     }
10278   }
10279 
10280   // Treat protoless main() as nullary.
10281   if (isa<FunctionNoProtoType>(FT)) return;
10282 
10283   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10284   unsigned nparams = FTP->getNumParams();
10285   assert(FD->getNumParams() == nparams);
10286 
10287   bool HasExtraParameters = (nparams > 3);
10288 
10289   if (FTP->isVariadic()) {
10290     Diag(FD->getLocation(), diag::ext_variadic_main);
10291     // FIXME: if we had information about the location of the ellipsis, we
10292     // could add a FixIt hint to remove it as a parameter.
10293   }
10294 
10295   // Darwin passes an undocumented fourth argument of type char**.  If
10296   // other platforms start sprouting these, the logic below will start
10297   // getting shifty.
10298   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10299     HasExtraParameters = false;
10300 
10301   if (HasExtraParameters) {
10302     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10303     FD->setInvalidDecl(true);
10304     nparams = 3;
10305   }
10306 
10307   // FIXME: a lot of the following diagnostics would be improved
10308   // if we had some location information about types.
10309 
10310   QualType CharPP =
10311     Context.getPointerType(Context.getPointerType(Context.CharTy));
10312   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10313 
10314   for (unsigned i = 0; i < nparams; ++i) {
10315     QualType AT = FTP->getParamType(i);
10316 
10317     bool mismatch = true;
10318 
10319     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10320       mismatch = false;
10321     else if (Expected[i] == CharPP) {
10322       // As an extension, the following forms are okay:
10323       //   char const **
10324       //   char const * const *
10325       //   char * const *
10326 
10327       QualifierCollector qs;
10328       const PointerType* PT;
10329       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10330           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10331           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10332                               Context.CharTy)) {
10333         qs.removeConst();
10334         mismatch = !qs.empty();
10335       }
10336     }
10337 
10338     if (mismatch) {
10339       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10340       // TODO: suggest replacing given type with expected type
10341       FD->setInvalidDecl(true);
10342     }
10343   }
10344 
10345   if (nparams == 1 && !FD->isInvalidDecl()) {
10346     Diag(FD->getLocation(), diag::warn_main_one_arg);
10347   }
10348 
10349   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10350     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10351     FD->setInvalidDecl();
10352   }
10353 }
10354 
10355 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10356   QualType T = FD->getType();
10357   assert(T->isFunctionType() && "function decl is not of function type");
10358   const FunctionType *FT = T->castAs<FunctionType>();
10359 
10360   // Set an implicit return of 'zero' if the function can return some integral,
10361   // enumeration, pointer or nullptr type.
10362   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10363       FT->getReturnType()->isAnyPointerType() ||
10364       FT->getReturnType()->isNullPtrType())
10365     // DllMain is exempt because a return value of zero means it failed.
10366     if (FD->getName() != "DllMain")
10367       FD->setHasImplicitReturnZero(true);
10368 
10369   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10370     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10371     FD->setInvalidDecl();
10372   }
10373 }
10374 
10375 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10376   // FIXME: Need strict checking.  In C89, we need to check for
10377   // any assignment, increment, decrement, function-calls, or
10378   // commas outside of a sizeof.  In C99, it's the same list,
10379   // except that the aforementioned are allowed in unevaluated
10380   // expressions.  Everything else falls under the
10381   // "may accept other forms of constant expressions" exception.
10382   // (We never end up here for C++, so the constant expression
10383   // rules there don't matter.)
10384   const Expr *Culprit;
10385   if (Init->isConstantInitializer(Context, false, &Culprit))
10386     return false;
10387   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10388     << Culprit->getSourceRange();
10389   return true;
10390 }
10391 
10392 namespace {
10393   // Visits an initialization expression to see if OrigDecl is evaluated in
10394   // its own initialization and throws a warning if it does.
10395   class SelfReferenceChecker
10396       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10397     Sema &S;
10398     Decl *OrigDecl;
10399     bool isRecordType;
10400     bool isPODType;
10401     bool isReferenceType;
10402 
10403     bool isInitList;
10404     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10405 
10406   public:
10407     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10408 
10409     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10410                                                     S(S), OrigDecl(OrigDecl) {
10411       isPODType = false;
10412       isRecordType = false;
10413       isReferenceType = false;
10414       isInitList = false;
10415       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10416         isPODType = VD->getType().isPODType(S.Context);
10417         isRecordType = VD->getType()->isRecordType();
10418         isReferenceType = VD->getType()->isReferenceType();
10419       }
10420     }
10421 
10422     // For most expressions, just call the visitor.  For initializer lists,
10423     // track the index of the field being initialized since fields are
10424     // initialized in order allowing use of previously initialized fields.
10425     void CheckExpr(Expr *E) {
10426       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10427       if (!InitList) {
10428         Visit(E);
10429         return;
10430       }
10431 
10432       // Track and increment the index here.
10433       isInitList = true;
10434       InitFieldIndex.push_back(0);
10435       for (auto Child : InitList->children()) {
10436         CheckExpr(cast<Expr>(Child));
10437         ++InitFieldIndex.back();
10438       }
10439       InitFieldIndex.pop_back();
10440     }
10441 
10442     // Returns true if MemberExpr is checked and no further checking is needed.
10443     // Returns false if additional checking is required.
10444     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10445       llvm::SmallVector<FieldDecl*, 4> Fields;
10446       Expr *Base = E;
10447       bool ReferenceField = false;
10448 
10449       // Get the field memebers used.
10450       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10451         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10452         if (!FD)
10453           return false;
10454         Fields.push_back(FD);
10455         if (FD->getType()->isReferenceType())
10456           ReferenceField = true;
10457         Base = ME->getBase()->IgnoreParenImpCasts();
10458       }
10459 
10460       // Keep checking only if the base Decl is the same.
10461       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10462       if (!DRE || DRE->getDecl() != OrigDecl)
10463         return false;
10464 
10465       // A reference field can be bound to an unininitialized field.
10466       if (CheckReference && !ReferenceField)
10467         return true;
10468 
10469       // Convert FieldDecls to their index number.
10470       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10471       for (const FieldDecl *I : llvm::reverse(Fields))
10472         UsedFieldIndex.push_back(I->getFieldIndex());
10473 
10474       // See if a warning is needed by checking the first difference in index
10475       // numbers.  If field being used has index less than the field being
10476       // initialized, then the use is safe.
10477       for (auto UsedIter = UsedFieldIndex.begin(),
10478                 UsedEnd = UsedFieldIndex.end(),
10479                 OrigIter = InitFieldIndex.begin(),
10480                 OrigEnd = InitFieldIndex.end();
10481            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10482         if (*UsedIter < *OrigIter)
10483           return true;
10484         if (*UsedIter > *OrigIter)
10485           break;
10486       }
10487 
10488       // TODO: Add a different warning which will print the field names.
10489       HandleDeclRefExpr(DRE);
10490       return true;
10491     }
10492 
10493     // For most expressions, the cast is directly above the DeclRefExpr.
10494     // For conditional operators, the cast can be outside the conditional
10495     // operator if both expressions are DeclRefExpr's.
10496     void HandleValue(Expr *E) {
10497       E = E->IgnoreParens();
10498       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10499         HandleDeclRefExpr(DRE);
10500         return;
10501       }
10502 
10503       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10504         Visit(CO->getCond());
10505         HandleValue(CO->getTrueExpr());
10506         HandleValue(CO->getFalseExpr());
10507         return;
10508       }
10509 
10510       if (BinaryConditionalOperator *BCO =
10511               dyn_cast<BinaryConditionalOperator>(E)) {
10512         Visit(BCO->getCond());
10513         HandleValue(BCO->getFalseExpr());
10514         return;
10515       }
10516 
10517       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10518         HandleValue(OVE->getSourceExpr());
10519         return;
10520       }
10521 
10522       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10523         if (BO->getOpcode() == BO_Comma) {
10524           Visit(BO->getLHS());
10525           HandleValue(BO->getRHS());
10526           return;
10527         }
10528       }
10529 
10530       if (isa<MemberExpr>(E)) {
10531         if (isInitList) {
10532           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10533                                       false /*CheckReference*/))
10534             return;
10535         }
10536 
10537         Expr *Base = E->IgnoreParenImpCasts();
10538         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10539           // Check for static member variables and don't warn on them.
10540           if (!isa<FieldDecl>(ME->getMemberDecl()))
10541             return;
10542           Base = ME->getBase()->IgnoreParenImpCasts();
10543         }
10544         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10545           HandleDeclRefExpr(DRE);
10546         return;
10547       }
10548 
10549       Visit(E);
10550     }
10551 
10552     // Reference types not handled in HandleValue are handled here since all
10553     // uses of references are bad, not just r-value uses.
10554     void VisitDeclRefExpr(DeclRefExpr *E) {
10555       if (isReferenceType)
10556         HandleDeclRefExpr(E);
10557     }
10558 
10559     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10560       if (E->getCastKind() == CK_LValueToRValue) {
10561         HandleValue(E->getSubExpr());
10562         return;
10563       }
10564 
10565       Inherited::VisitImplicitCastExpr(E);
10566     }
10567 
10568     void VisitMemberExpr(MemberExpr *E) {
10569       if (isInitList) {
10570         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10571           return;
10572       }
10573 
10574       // Don't warn on arrays since they can be treated as pointers.
10575       if (E->getType()->canDecayToPointerType()) return;
10576 
10577       // Warn when a non-static method call is followed by non-static member
10578       // field accesses, which is followed by a DeclRefExpr.
10579       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10580       bool Warn = (MD && !MD->isStatic());
10581       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10582       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10583         if (!isa<FieldDecl>(ME->getMemberDecl()))
10584           Warn = false;
10585         Base = ME->getBase()->IgnoreParenImpCasts();
10586       }
10587 
10588       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10589         if (Warn)
10590           HandleDeclRefExpr(DRE);
10591         return;
10592       }
10593 
10594       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10595       // Visit that expression.
10596       Visit(Base);
10597     }
10598 
10599     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10600       Expr *Callee = E->getCallee();
10601 
10602       if (isa<UnresolvedLookupExpr>(Callee))
10603         return Inherited::VisitCXXOperatorCallExpr(E);
10604 
10605       Visit(Callee);
10606       for (auto Arg: E->arguments())
10607         HandleValue(Arg->IgnoreParenImpCasts());
10608     }
10609 
10610     void VisitUnaryOperator(UnaryOperator *E) {
10611       // For POD record types, addresses of its own members are well-defined.
10612       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10613           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10614         if (!isPODType)
10615           HandleValue(E->getSubExpr());
10616         return;
10617       }
10618 
10619       if (E->isIncrementDecrementOp()) {
10620         HandleValue(E->getSubExpr());
10621         return;
10622       }
10623 
10624       Inherited::VisitUnaryOperator(E);
10625     }
10626 
10627     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10628 
10629     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10630       if (E->getConstructor()->isCopyConstructor()) {
10631         Expr *ArgExpr = E->getArg(0);
10632         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10633           if (ILE->getNumInits() == 1)
10634             ArgExpr = ILE->getInit(0);
10635         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10636           if (ICE->getCastKind() == CK_NoOp)
10637             ArgExpr = ICE->getSubExpr();
10638         HandleValue(ArgExpr);
10639         return;
10640       }
10641       Inherited::VisitCXXConstructExpr(E);
10642     }
10643 
10644     void VisitCallExpr(CallExpr *E) {
10645       // Treat std::move as a use.
10646       if (E->isCallToStdMove()) {
10647         HandleValue(E->getArg(0));
10648         return;
10649       }
10650 
10651       Inherited::VisitCallExpr(E);
10652     }
10653 
10654     void VisitBinaryOperator(BinaryOperator *E) {
10655       if (E->isCompoundAssignmentOp()) {
10656         HandleValue(E->getLHS());
10657         Visit(E->getRHS());
10658         return;
10659       }
10660 
10661       Inherited::VisitBinaryOperator(E);
10662     }
10663 
10664     // A custom visitor for BinaryConditionalOperator is needed because the
10665     // regular visitor would check the condition and true expression separately
10666     // but both point to the same place giving duplicate diagnostics.
10667     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10668       Visit(E->getCond());
10669       Visit(E->getFalseExpr());
10670     }
10671 
10672     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10673       Decl* ReferenceDecl = DRE->getDecl();
10674       if (OrigDecl != ReferenceDecl) return;
10675       unsigned diag;
10676       if (isReferenceType) {
10677         diag = diag::warn_uninit_self_reference_in_reference_init;
10678       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10679         diag = diag::warn_static_self_reference_in_init;
10680       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10681                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10682                  DRE->getDecl()->getType()->isRecordType()) {
10683         diag = diag::warn_uninit_self_reference_in_init;
10684       } else {
10685         // Local variables will be handled by the CFG analysis.
10686         return;
10687       }
10688 
10689       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10690                             S.PDiag(diag)
10691                                 << DRE->getDecl() << OrigDecl->getLocation()
10692                                 << DRE->getSourceRange());
10693     }
10694   };
10695 
10696   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10697   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10698                                  bool DirectInit) {
10699     // Parameters arguments are occassionially constructed with itself,
10700     // for instance, in recursive functions.  Skip them.
10701     if (isa<ParmVarDecl>(OrigDecl))
10702       return;
10703 
10704     E = E->IgnoreParens();
10705 
10706     // Skip checking T a = a where T is not a record or reference type.
10707     // Doing so is a way to silence uninitialized warnings.
10708     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10709       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10710         if (ICE->getCastKind() == CK_LValueToRValue)
10711           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10712             if (DRE->getDecl() == OrigDecl)
10713               return;
10714 
10715     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10716   }
10717 } // end anonymous namespace
10718 
10719 namespace {
10720   // Simple wrapper to add the name of a variable or (if no variable is
10721   // available) a DeclarationName into a diagnostic.
10722   struct VarDeclOrName {
10723     VarDecl *VDecl;
10724     DeclarationName Name;
10725 
10726     friend const Sema::SemaDiagnosticBuilder &
10727     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10728       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10729     }
10730   };
10731 } // end anonymous namespace
10732 
10733 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10734                                             DeclarationName Name, QualType Type,
10735                                             TypeSourceInfo *TSI,
10736                                             SourceRange Range, bool DirectInit,
10737                                             Expr *Init) {
10738   bool IsInitCapture = !VDecl;
10739   assert((!VDecl || !VDecl->isInitCapture()) &&
10740          "init captures are expected to be deduced prior to initialization");
10741 
10742   VarDeclOrName VN{VDecl, Name};
10743 
10744   DeducedType *Deduced = Type->getContainedDeducedType();
10745   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10746 
10747   // C++11 [dcl.spec.auto]p3
10748   if (!Init) {
10749     assert(VDecl && "no init for init capture deduction?");
10750 
10751     // Except for class argument deduction, and then for an initializing
10752     // declaration only, i.e. no static at class scope or extern.
10753     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10754         VDecl->hasExternalStorage() ||
10755         VDecl->isStaticDataMember()) {
10756       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10757         << VDecl->getDeclName() << Type;
10758       return QualType();
10759     }
10760   }
10761 
10762   ArrayRef<Expr*> DeduceInits;
10763   if (Init)
10764     DeduceInits = Init;
10765 
10766   if (DirectInit) {
10767     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10768       DeduceInits = PL->exprs();
10769   }
10770 
10771   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10772     assert(VDecl && "non-auto type for init capture deduction?");
10773     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10774     InitializationKind Kind = InitializationKind::CreateForInit(
10775         VDecl->getLocation(), DirectInit, Init);
10776     // FIXME: Initialization should not be taking a mutable list of inits.
10777     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10778     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10779                                                        InitsCopy);
10780   }
10781 
10782   if (DirectInit) {
10783     if (auto *IL = dyn_cast<InitListExpr>(Init))
10784       DeduceInits = IL->inits();
10785   }
10786 
10787   // Deduction only works if we have exactly one source expression.
10788   if (DeduceInits.empty()) {
10789     // It isn't possible to write this directly, but it is possible to
10790     // end up in this situation with "auto x(some_pack...);"
10791     Diag(Init->getBeginLoc(), IsInitCapture
10792                                   ? diag::err_init_capture_no_expression
10793                                   : diag::err_auto_var_init_no_expression)
10794         << VN << Type << Range;
10795     return QualType();
10796   }
10797 
10798   if (DeduceInits.size() > 1) {
10799     Diag(DeduceInits[1]->getBeginLoc(),
10800          IsInitCapture ? diag::err_init_capture_multiple_expressions
10801                        : diag::err_auto_var_init_multiple_expressions)
10802         << VN << Type << Range;
10803     return QualType();
10804   }
10805 
10806   Expr *DeduceInit = DeduceInits[0];
10807   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10808     Diag(Init->getBeginLoc(), IsInitCapture
10809                                   ? diag::err_init_capture_paren_braces
10810                                   : diag::err_auto_var_init_paren_braces)
10811         << isa<InitListExpr>(Init) << VN << Type << Range;
10812     return QualType();
10813   }
10814 
10815   // Expressions default to 'id' when we're in a debugger.
10816   bool DefaultedAnyToId = false;
10817   if (getLangOpts().DebuggerCastResultToId &&
10818       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10819     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10820     if (Result.isInvalid()) {
10821       return QualType();
10822     }
10823     Init = Result.get();
10824     DefaultedAnyToId = true;
10825   }
10826 
10827   // C++ [dcl.decomp]p1:
10828   //   If the assignment-expression [...] has array type A and no ref-qualifier
10829   //   is present, e has type cv A
10830   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10831       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10832       DeduceInit->getType()->isConstantArrayType())
10833     return Context.getQualifiedType(DeduceInit->getType(),
10834                                     Type.getQualifiers());
10835 
10836   QualType DeducedType;
10837   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10838     if (!IsInitCapture)
10839       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10840     else if (isa<InitListExpr>(Init))
10841       Diag(Range.getBegin(),
10842            diag::err_init_capture_deduction_failure_from_init_list)
10843           << VN
10844           << (DeduceInit->getType().isNull() ? TSI->getType()
10845                                              : DeduceInit->getType())
10846           << DeduceInit->getSourceRange();
10847     else
10848       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10849           << VN << TSI->getType()
10850           << (DeduceInit->getType().isNull() ? TSI->getType()
10851                                              : DeduceInit->getType())
10852           << DeduceInit->getSourceRange();
10853   }
10854 
10855   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10856   // 'id' instead of a specific object type prevents most of our usual
10857   // checks.
10858   // We only want to warn outside of template instantiations, though:
10859   // inside a template, the 'id' could have come from a parameter.
10860   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10861       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10862     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10863     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10864   }
10865 
10866   return DeducedType;
10867 }
10868 
10869 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10870                                          Expr *Init) {
10871   QualType DeducedType = deduceVarTypeFromInitializer(
10872       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10873       VDecl->getSourceRange(), DirectInit, Init);
10874   if (DeducedType.isNull()) {
10875     VDecl->setInvalidDecl();
10876     return true;
10877   }
10878 
10879   VDecl->setType(DeducedType);
10880   assert(VDecl->isLinkageValid());
10881 
10882   // In ARC, infer lifetime.
10883   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10884     VDecl->setInvalidDecl();
10885 
10886   // If this is a redeclaration, check that the type we just deduced matches
10887   // the previously declared type.
10888   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10889     // We never need to merge the type, because we cannot form an incomplete
10890     // array of auto, nor deduce such a type.
10891     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10892   }
10893 
10894   // Check the deduced type is valid for a variable declaration.
10895   CheckVariableDeclarationType(VDecl);
10896   return VDecl->isInvalidDecl();
10897 }
10898 
10899 /// AddInitializerToDecl - Adds the initializer Init to the
10900 /// declaration dcl. If DirectInit is true, this is C++ direct
10901 /// initialization rather than copy initialization.
10902 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10903   // If there is no declaration, there was an error parsing it.  Just ignore
10904   // the initializer.
10905   if (!RealDecl || RealDecl->isInvalidDecl()) {
10906     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10907     return;
10908   }
10909 
10910   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10911     // Pure-specifiers are handled in ActOnPureSpecifier.
10912     Diag(Method->getLocation(), diag::err_member_function_initialization)
10913       << Method->getDeclName() << Init->getSourceRange();
10914     Method->setInvalidDecl();
10915     return;
10916   }
10917 
10918   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10919   if (!VDecl) {
10920     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10921     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10922     RealDecl->setInvalidDecl();
10923     return;
10924   }
10925 
10926   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10927   if (VDecl->getType()->isUndeducedType()) {
10928     // Attempt typo correction early so that the type of the init expression can
10929     // be deduced based on the chosen correction if the original init contains a
10930     // TypoExpr.
10931     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10932     if (!Res.isUsable()) {
10933       RealDecl->setInvalidDecl();
10934       return;
10935     }
10936     Init = Res.get();
10937 
10938     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10939       return;
10940   }
10941 
10942   // dllimport cannot be used on variable definitions.
10943   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10944     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10945     VDecl->setInvalidDecl();
10946     return;
10947   }
10948 
10949   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10950     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10951     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10952     VDecl->setInvalidDecl();
10953     return;
10954   }
10955 
10956   if (!VDecl->getType()->isDependentType()) {
10957     // A definition must end up with a complete type, which means it must be
10958     // complete with the restriction that an array type might be completed by
10959     // the initializer; note that later code assumes this restriction.
10960     QualType BaseDeclType = VDecl->getType();
10961     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10962       BaseDeclType = Array->getElementType();
10963     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10964                             diag::err_typecheck_decl_incomplete_type)) {
10965       RealDecl->setInvalidDecl();
10966       return;
10967     }
10968 
10969     // The variable can not have an abstract class type.
10970     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10971                                diag::err_abstract_type_in_decl,
10972                                AbstractVariableType))
10973       VDecl->setInvalidDecl();
10974   }
10975 
10976   // If adding the initializer will turn this declaration into a definition,
10977   // and we already have a definition for this variable, diagnose or otherwise
10978   // handle the situation.
10979   VarDecl *Def;
10980   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10981       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10982       !VDecl->isThisDeclarationADemotedDefinition() &&
10983       checkVarDeclRedefinition(Def, VDecl))
10984     return;
10985 
10986   if (getLangOpts().CPlusPlus) {
10987     // C++ [class.static.data]p4
10988     //   If a static data member is of const integral or const
10989     //   enumeration type, its declaration in the class definition can
10990     //   specify a constant-initializer which shall be an integral
10991     //   constant expression (5.19). In that case, the member can appear
10992     //   in integral constant expressions. The member shall still be
10993     //   defined in a namespace scope if it is used in the program and the
10994     //   namespace scope definition shall not contain an initializer.
10995     //
10996     // We already performed a redefinition check above, but for static
10997     // data members we also need to check whether there was an in-class
10998     // declaration with an initializer.
10999     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11000       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11001           << VDecl->getDeclName();
11002       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11003            diag::note_previous_initializer)
11004           << 0;
11005       return;
11006     }
11007 
11008     if (VDecl->hasLocalStorage())
11009       setFunctionHasBranchProtectedScope();
11010 
11011     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11012       VDecl->setInvalidDecl();
11013       return;
11014     }
11015   }
11016 
11017   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11018   // a kernel function cannot be initialized."
11019   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11020     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11021     VDecl->setInvalidDecl();
11022     return;
11023   }
11024 
11025   // Get the decls type and save a reference for later, since
11026   // CheckInitializerTypes may change it.
11027   QualType DclT = VDecl->getType(), SavT = DclT;
11028 
11029   // Expressions default to 'id' when we're in a debugger
11030   // and we are assigning it to a variable of Objective-C pointer type.
11031   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11032       Init->getType() == Context.UnknownAnyTy) {
11033     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11034     if (Result.isInvalid()) {
11035       VDecl->setInvalidDecl();
11036       return;
11037     }
11038     Init = Result.get();
11039   }
11040 
11041   // Perform the initialization.
11042   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11043   if (!VDecl->isInvalidDecl()) {
11044     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11045     InitializationKind Kind = InitializationKind::CreateForInit(
11046         VDecl->getLocation(), DirectInit, Init);
11047 
11048     MultiExprArg Args = Init;
11049     if (CXXDirectInit)
11050       Args = MultiExprArg(CXXDirectInit->getExprs(),
11051                           CXXDirectInit->getNumExprs());
11052 
11053     // Try to correct any TypoExprs in the initialization arguments.
11054     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11055       ExprResult Res = CorrectDelayedTyposInExpr(
11056           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11057             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11058             return Init.Failed() ? ExprError() : E;
11059           });
11060       if (Res.isInvalid()) {
11061         VDecl->setInvalidDecl();
11062       } else if (Res.get() != Args[Idx]) {
11063         Args[Idx] = Res.get();
11064       }
11065     }
11066     if (VDecl->isInvalidDecl())
11067       return;
11068 
11069     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11070                                    /*TopLevelOfInitList=*/false,
11071                                    /*TreatUnavailableAsInvalid=*/false);
11072     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11073     if (Result.isInvalid()) {
11074       VDecl->setInvalidDecl();
11075       return;
11076     }
11077 
11078     Init = Result.getAs<Expr>();
11079   }
11080 
11081   // Check for self-references within variable initializers.
11082   // Variables declared within a function/method body (except for references)
11083   // are handled by a dataflow analysis.
11084   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11085       VDecl->getType()->isReferenceType()) {
11086     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11087   }
11088 
11089   // If the type changed, it means we had an incomplete type that was
11090   // completed by the initializer. For example:
11091   //   int ary[] = { 1, 3, 5 };
11092   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11093   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11094     VDecl->setType(DclT);
11095 
11096   if (!VDecl->isInvalidDecl()) {
11097     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11098 
11099     if (VDecl->hasAttr<BlocksAttr>())
11100       checkRetainCycles(VDecl, Init);
11101 
11102     // It is safe to assign a weak reference into a strong variable.
11103     // Although this code can still have problems:
11104     //   id x = self.weakProp;
11105     //   id y = self.weakProp;
11106     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11107     // paths through the function. This should be revisited if
11108     // -Wrepeated-use-of-weak is made flow-sensitive.
11109     if (FunctionScopeInfo *FSI = getCurFunction())
11110       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11111            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11112           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11113                            Init->getBeginLoc()))
11114         FSI->markSafeWeakUse(Init);
11115   }
11116 
11117   // The initialization is usually a full-expression.
11118   //
11119   // FIXME: If this is a braced initialization of an aggregate, it is not
11120   // an expression, and each individual field initializer is a separate
11121   // full-expression. For instance, in:
11122   //
11123   //   struct Temp { ~Temp(); };
11124   //   struct S { S(Temp); };
11125   //   struct T { S a, b; } t = { Temp(), Temp() }
11126   //
11127   // we should destroy the first Temp before constructing the second.
11128   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
11129                                           false,
11130                                           VDecl->isConstexpr());
11131   if (Result.isInvalid()) {
11132     VDecl->setInvalidDecl();
11133     return;
11134   }
11135   Init = Result.get();
11136 
11137   // Attach the initializer to the decl.
11138   VDecl->setInit(Init);
11139 
11140   if (VDecl->isLocalVarDecl()) {
11141     // Don't check the initializer if the declaration is malformed.
11142     if (VDecl->isInvalidDecl()) {
11143       // do nothing
11144 
11145     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11146     // This is true even in OpenCL C++.
11147     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11148       CheckForConstantInitializer(Init, DclT);
11149 
11150     // Otherwise, C++ does not restrict the initializer.
11151     } else if (getLangOpts().CPlusPlus) {
11152       // do nothing
11153 
11154     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11155     // static storage duration shall be constant expressions or string literals.
11156     } else if (VDecl->getStorageClass() == SC_Static) {
11157       CheckForConstantInitializer(Init, DclT);
11158 
11159     // C89 is stricter than C99 for aggregate initializers.
11160     // C89 6.5.7p3: All the expressions [...] in an initializer list
11161     // for an object that has aggregate or union type shall be
11162     // constant expressions.
11163     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11164                isa<InitListExpr>(Init)) {
11165       const Expr *Culprit;
11166       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11167         Diag(Culprit->getExprLoc(),
11168              diag::ext_aggregate_init_not_constant)
11169           << Culprit->getSourceRange();
11170       }
11171     }
11172   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11173              VDecl->getLexicalDeclContext()->isRecord()) {
11174     // This is an in-class initialization for a static data member, e.g.,
11175     //
11176     // struct S {
11177     //   static const int value = 17;
11178     // };
11179 
11180     // C++ [class.mem]p4:
11181     //   A member-declarator can contain a constant-initializer only
11182     //   if it declares a static member (9.4) of const integral or
11183     //   const enumeration type, see 9.4.2.
11184     //
11185     // C++11 [class.static.data]p3:
11186     //   If a non-volatile non-inline const static data member is of integral
11187     //   or enumeration type, its declaration in the class definition can
11188     //   specify a brace-or-equal-initializer in which every initializer-clause
11189     //   that is an assignment-expression is a constant expression. A static
11190     //   data member of literal type can be declared in the class definition
11191     //   with the constexpr specifier; if so, its declaration shall specify a
11192     //   brace-or-equal-initializer in which every initializer-clause that is
11193     //   an assignment-expression is a constant expression.
11194 
11195     // Do nothing on dependent types.
11196     if (DclT->isDependentType()) {
11197 
11198     // Allow any 'static constexpr' members, whether or not they are of literal
11199     // type. We separately check that every constexpr variable is of literal
11200     // type.
11201     } else if (VDecl->isConstexpr()) {
11202 
11203     // Require constness.
11204     } else if (!DclT.isConstQualified()) {
11205       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11206         << Init->getSourceRange();
11207       VDecl->setInvalidDecl();
11208 
11209     // We allow integer constant expressions in all cases.
11210     } else if (DclT->isIntegralOrEnumerationType()) {
11211       // Check whether the expression is a constant expression.
11212       SourceLocation Loc;
11213       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11214         // In C++11, a non-constexpr const static data member with an
11215         // in-class initializer cannot be volatile.
11216         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11217       else if (Init->isValueDependent())
11218         ; // Nothing to check.
11219       else if (Init->isIntegerConstantExpr(Context, &Loc))
11220         ; // Ok, it's an ICE!
11221       else if (Init->getType()->isScopedEnumeralType() &&
11222                Init->isCXX11ConstantExpr(Context))
11223         ; // Ok, it is a scoped-enum constant expression.
11224       else if (Init->isEvaluatable(Context)) {
11225         // If we can constant fold the initializer through heroics, accept it,
11226         // but report this as a use of an extension for -pedantic.
11227         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11228           << Init->getSourceRange();
11229       } else {
11230         // Otherwise, this is some crazy unknown case.  Report the issue at the
11231         // location provided by the isIntegerConstantExpr failed check.
11232         Diag(Loc, diag::err_in_class_initializer_non_constant)
11233           << Init->getSourceRange();
11234         VDecl->setInvalidDecl();
11235       }
11236 
11237     // We allow foldable floating-point constants as an extension.
11238     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11239       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11240       // it anyway and provide a fixit to add the 'constexpr'.
11241       if (getLangOpts().CPlusPlus11) {
11242         Diag(VDecl->getLocation(),
11243              diag::ext_in_class_initializer_float_type_cxx11)
11244             << DclT << Init->getSourceRange();
11245         Diag(VDecl->getBeginLoc(),
11246              diag::note_in_class_initializer_float_type_cxx11)
11247             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11248       } else {
11249         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11250           << DclT << Init->getSourceRange();
11251 
11252         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11253           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11254             << Init->getSourceRange();
11255           VDecl->setInvalidDecl();
11256         }
11257       }
11258 
11259     // Suggest adding 'constexpr' in C++11 for literal types.
11260     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11261       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11262           << DclT << Init->getSourceRange()
11263           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11264       VDecl->setConstexpr(true);
11265 
11266     } else {
11267       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11268         << DclT << Init->getSourceRange();
11269       VDecl->setInvalidDecl();
11270     }
11271   } else if (VDecl->isFileVarDecl()) {
11272     // In C, extern is typically used to avoid tentative definitions when
11273     // declaring variables in headers, but adding an intializer makes it a
11274     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11275     // In C++, extern is often used to give implictly static const variables
11276     // external linkage, so don't warn in that case. If selectany is present,
11277     // this might be header code intended for C and C++ inclusion, so apply the
11278     // C++ rules.
11279     if (VDecl->getStorageClass() == SC_Extern &&
11280         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11281          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11282         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11283         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11284       Diag(VDecl->getLocation(), diag::warn_extern_init);
11285 
11286     // C99 6.7.8p4. All file scoped initializers need to be constant.
11287     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11288       CheckForConstantInitializer(Init, DclT);
11289   }
11290 
11291   // We will represent direct-initialization similarly to copy-initialization:
11292   //    int x(1);  -as-> int x = 1;
11293   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11294   //
11295   // Clients that want to distinguish between the two forms, can check for
11296   // direct initializer using VarDecl::getInitStyle().
11297   // A major benefit is that clients that don't particularly care about which
11298   // exactly form was it (like the CodeGen) can handle both cases without
11299   // special case code.
11300 
11301   // C++ 8.5p11:
11302   // The form of initialization (using parentheses or '=') is generally
11303   // insignificant, but does matter when the entity being initialized has a
11304   // class type.
11305   if (CXXDirectInit) {
11306     assert(DirectInit && "Call-style initializer must be direct init.");
11307     VDecl->setInitStyle(VarDecl::CallInit);
11308   } else if (DirectInit) {
11309     // This must be list-initialization. No other way is direct-initialization.
11310     VDecl->setInitStyle(VarDecl::ListInit);
11311   }
11312 
11313   CheckCompleteVariableDeclaration(VDecl);
11314 }
11315 
11316 /// ActOnInitializerError - Given that there was an error parsing an
11317 /// initializer for the given declaration, try to return to some form
11318 /// of sanity.
11319 void Sema::ActOnInitializerError(Decl *D) {
11320   // Our main concern here is re-establishing invariants like "a
11321   // variable's type is either dependent or complete".
11322   if (!D || D->isInvalidDecl()) return;
11323 
11324   VarDecl *VD = dyn_cast<VarDecl>(D);
11325   if (!VD) return;
11326 
11327   // Bindings are not usable if we can't make sense of the initializer.
11328   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11329     for (auto *BD : DD->bindings())
11330       BD->setInvalidDecl();
11331 
11332   // Auto types are meaningless if we can't make sense of the initializer.
11333   if (ParsingInitForAutoVars.count(D)) {
11334     D->setInvalidDecl();
11335     return;
11336   }
11337 
11338   QualType Ty = VD->getType();
11339   if (Ty->isDependentType()) return;
11340 
11341   // Require a complete type.
11342   if (RequireCompleteType(VD->getLocation(),
11343                           Context.getBaseElementType(Ty),
11344                           diag::err_typecheck_decl_incomplete_type)) {
11345     VD->setInvalidDecl();
11346     return;
11347   }
11348 
11349   // Require a non-abstract type.
11350   if (RequireNonAbstractType(VD->getLocation(), Ty,
11351                              diag::err_abstract_type_in_decl,
11352                              AbstractVariableType)) {
11353     VD->setInvalidDecl();
11354     return;
11355   }
11356 
11357   // Don't bother complaining about constructors or destructors,
11358   // though.
11359 }
11360 
11361 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11362   // If there is no declaration, there was an error parsing it. Just ignore it.
11363   if (!RealDecl)
11364     return;
11365 
11366   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11367     QualType Type = Var->getType();
11368 
11369     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11370     if (isa<DecompositionDecl>(RealDecl)) {
11371       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11372       Var->setInvalidDecl();
11373       return;
11374     }
11375 
11376     if (Type->isUndeducedType() &&
11377         DeduceVariableDeclarationType(Var, false, nullptr))
11378       return;
11379 
11380     // C++11 [class.static.data]p3: A static data member can be declared with
11381     // the constexpr specifier; if so, its declaration shall specify
11382     // a brace-or-equal-initializer.
11383     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11384     // the definition of a variable [...] or the declaration of a static data
11385     // member.
11386     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11387         !Var->isThisDeclarationADemotedDefinition()) {
11388       if (Var->isStaticDataMember()) {
11389         // C++1z removes the relevant rule; the in-class declaration is always
11390         // a definition there.
11391         if (!getLangOpts().CPlusPlus17) {
11392           Diag(Var->getLocation(),
11393                diag::err_constexpr_static_mem_var_requires_init)
11394             << Var->getDeclName();
11395           Var->setInvalidDecl();
11396           return;
11397         }
11398       } else {
11399         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11400         Var->setInvalidDecl();
11401         return;
11402       }
11403     }
11404 
11405     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11406     // be initialized.
11407     if (!Var->isInvalidDecl() &&
11408         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11409         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11410       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11411       Var->setInvalidDecl();
11412       return;
11413     }
11414 
11415     switch (Var->isThisDeclarationADefinition()) {
11416     case VarDecl::Definition:
11417       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11418         break;
11419 
11420       // We have an out-of-line definition of a static data member
11421       // that has an in-class initializer, so we type-check this like
11422       // a declaration.
11423       //
11424       LLVM_FALLTHROUGH;
11425 
11426     case VarDecl::DeclarationOnly:
11427       // It's only a declaration.
11428 
11429       // Block scope. C99 6.7p7: If an identifier for an object is
11430       // declared with no linkage (C99 6.2.2p6), the type for the
11431       // object shall be complete.
11432       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11433           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11434           RequireCompleteType(Var->getLocation(), Type,
11435                               diag::err_typecheck_decl_incomplete_type))
11436         Var->setInvalidDecl();
11437 
11438       // Make sure that the type is not abstract.
11439       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11440           RequireNonAbstractType(Var->getLocation(), Type,
11441                                  diag::err_abstract_type_in_decl,
11442                                  AbstractVariableType))
11443         Var->setInvalidDecl();
11444       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11445           Var->getStorageClass() == SC_PrivateExtern) {
11446         Diag(Var->getLocation(), diag::warn_private_extern);
11447         Diag(Var->getLocation(), diag::note_private_extern);
11448       }
11449 
11450       return;
11451 
11452     case VarDecl::TentativeDefinition:
11453       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11454       // object that has file scope without an initializer, and without a
11455       // storage-class specifier or with the storage-class specifier "static",
11456       // constitutes a tentative definition. Note: A tentative definition with
11457       // external linkage is valid (C99 6.2.2p5).
11458       if (!Var->isInvalidDecl()) {
11459         if (const IncompleteArrayType *ArrayT
11460                                     = Context.getAsIncompleteArrayType(Type)) {
11461           if (RequireCompleteType(Var->getLocation(),
11462                                   ArrayT->getElementType(),
11463                                   diag::err_illegal_decl_array_incomplete_type))
11464             Var->setInvalidDecl();
11465         } else if (Var->getStorageClass() == SC_Static) {
11466           // C99 6.9.2p3: If the declaration of an identifier for an object is
11467           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11468           // declared type shall not be an incomplete type.
11469           // NOTE: code such as the following
11470           //     static struct s;
11471           //     struct s { int a; };
11472           // is accepted by gcc. Hence here we issue a warning instead of
11473           // an error and we do not invalidate the static declaration.
11474           // NOTE: to avoid multiple warnings, only check the first declaration.
11475           if (Var->isFirstDecl())
11476             RequireCompleteType(Var->getLocation(), Type,
11477                                 diag::ext_typecheck_decl_incomplete_type);
11478         }
11479       }
11480 
11481       // Record the tentative definition; we're done.
11482       if (!Var->isInvalidDecl())
11483         TentativeDefinitions.push_back(Var);
11484       return;
11485     }
11486 
11487     // Provide a specific diagnostic for uninitialized variable
11488     // definitions with incomplete array type.
11489     if (Type->isIncompleteArrayType()) {
11490       Diag(Var->getLocation(),
11491            diag::err_typecheck_incomplete_array_needs_initializer);
11492       Var->setInvalidDecl();
11493       return;
11494     }
11495 
11496     // Provide a specific diagnostic for uninitialized variable
11497     // definitions with reference type.
11498     if (Type->isReferenceType()) {
11499       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11500         << Var->getDeclName()
11501         << SourceRange(Var->getLocation(), Var->getLocation());
11502       Var->setInvalidDecl();
11503       return;
11504     }
11505 
11506     // Do not attempt to type-check the default initializer for a
11507     // variable with dependent type.
11508     if (Type->isDependentType())
11509       return;
11510 
11511     if (Var->isInvalidDecl())
11512       return;
11513 
11514     if (!Var->hasAttr<AliasAttr>()) {
11515       if (RequireCompleteType(Var->getLocation(),
11516                               Context.getBaseElementType(Type),
11517                               diag::err_typecheck_decl_incomplete_type)) {
11518         Var->setInvalidDecl();
11519         return;
11520       }
11521     } else {
11522       return;
11523     }
11524 
11525     // The variable can not have an abstract class type.
11526     if (RequireNonAbstractType(Var->getLocation(), Type,
11527                                diag::err_abstract_type_in_decl,
11528                                AbstractVariableType)) {
11529       Var->setInvalidDecl();
11530       return;
11531     }
11532 
11533     // Check for jumps past the implicit initializer.  C++0x
11534     // clarifies that this applies to a "variable with automatic
11535     // storage duration", not a "local variable".
11536     // C++11 [stmt.dcl]p3
11537     //   A program that jumps from a point where a variable with automatic
11538     //   storage duration is not in scope to a point where it is in scope is
11539     //   ill-formed unless the variable has scalar type, class type with a
11540     //   trivial default constructor and a trivial destructor, a cv-qualified
11541     //   version of one of these types, or an array of one of the preceding
11542     //   types and is declared without an initializer.
11543     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11544       if (const RecordType *Record
11545             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11546         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11547         // Mark the function (if we're in one) for further checking even if the
11548         // looser rules of C++11 do not require such checks, so that we can
11549         // diagnose incompatibilities with C++98.
11550         if (!CXXRecord->isPOD())
11551           setFunctionHasBranchProtectedScope();
11552       }
11553     }
11554 
11555     // C++03 [dcl.init]p9:
11556     //   If no initializer is specified for an object, and the
11557     //   object is of (possibly cv-qualified) non-POD class type (or
11558     //   array thereof), the object shall be default-initialized; if
11559     //   the object is of const-qualified type, the underlying class
11560     //   type shall have a user-declared default
11561     //   constructor. Otherwise, if no initializer is specified for
11562     //   a non- static object, the object and its subobjects, if
11563     //   any, have an indeterminate initial value); if the object
11564     //   or any of its subobjects are of const-qualified type, the
11565     //   program is ill-formed.
11566     // C++0x [dcl.init]p11:
11567     //   If no initializer is specified for an object, the object is
11568     //   default-initialized; [...].
11569     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11570     InitializationKind Kind
11571       = InitializationKind::CreateDefault(Var->getLocation());
11572 
11573     InitializationSequence InitSeq(*this, Entity, Kind, None);
11574     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11575     if (Init.isInvalid())
11576       Var->setInvalidDecl();
11577     else if (Init.get()) {
11578       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11579       // This is important for template substitution.
11580       Var->setInitStyle(VarDecl::CallInit);
11581     }
11582 
11583     CheckCompleteVariableDeclaration(Var);
11584   }
11585 }
11586 
11587 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11588   // If there is no declaration, there was an error parsing it. Ignore it.
11589   if (!D)
11590     return;
11591 
11592   VarDecl *VD = dyn_cast<VarDecl>(D);
11593   if (!VD) {
11594     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11595     D->setInvalidDecl();
11596     return;
11597   }
11598 
11599   VD->setCXXForRangeDecl(true);
11600 
11601   // for-range-declaration cannot be given a storage class specifier.
11602   int Error = -1;
11603   switch (VD->getStorageClass()) {
11604   case SC_None:
11605     break;
11606   case SC_Extern:
11607     Error = 0;
11608     break;
11609   case SC_Static:
11610     Error = 1;
11611     break;
11612   case SC_PrivateExtern:
11613     Error = 2;
11614     break;
11615   case SC_Auto:
11616     Error = 3;
11617     break;
11618   case SC_Register:
11619     Error = 4;
11620     break;
11621   }
11622   if (Error != -1) {
11623     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11624       << VD->getDeclName() << Error;
11625     D->setInvalidDecl();
11626   }
11627 }
11628 
11629 StmtResult
11630 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11631                                  IdentifierInfo *Ident,
11632                                  ParsedAttributes &Attrs,
11633                                  SourceLocation AttrEnd) {
11634   // C++1y [stmt.iter]p1:
11635   //   A range-based for statement of the form
11636   //      for ( for-range-identifier : for-range-initializer ) statement
11637   //   is equivalent to
11638   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11639   DeclSpec DS(Attrs.getPool().getFactory());
11640 
11641   const char *PrevSpec;
11642   unsigned DiagID;
11643   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11644                      getPrintingPolicy());
11645 
11646   Declarator D(DS, DeclaratorContext::ForContext);
11647   D.SetIdentifier(Ident, IdentLoc);
11648   D.takeAttributes(Attrs, AttrEnd);
11649 
11650   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11651   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11652                 IdentLoc);
11653   Decl *Var = ActOnDeclarator(S, D);
11654   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11655   FinalizeDeclaration(Var);
11656   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11657                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11658 }
11659 
11660 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11661   if (var->isInvalidDecl()) return;
11662 
11663   if (getLangOpts().OpenCL) {
11664     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11665     // initialiser
11666     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11667         !var->hasInit()) {
11668       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11669           << 1 /*Init*/;
11670       var->setInvalidDecl();
11671       return;
11672     }
11673   }
11674 
11675   // In Objective-C, don't allow jumps past the implicit initialization of a
11676   // local retaining variable.
11677   if (getLangOpts().ObjC1 &&
11678       var->hasLocalStorage()) {
11679     switch (var->getType().getObjCLifetime()) {
11680     case Qualifiers::OCL_None:
11681     case Qualifiers::OCL_ExplicitNone:
11682     case Qualifiers::OCL_Autoreleasing:
11683       break;
11684 
11685     case Qualifiers::OCL_Weak:
11686     case Qualifiers::OCL_Strong:
11687       setFunctionHasBranchProtectedScope();
11688       break;
11689     }
11690   }
11691 
11692   if (var->hasLocalStorage() &&
11693       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11694     setFunctionHasBranchProtectedScope();
11695 
11696   // Warn about externally-visible variables being defined without a
11697   // prior declaration.  We only want to do this for global
11698   // declarations, but we also specifically need to avoid doing it for
11699   // class members because the linkage of an anonymous class can
11700   // change if it's later given a typedef name.
11701   if (var->isThisDeclarationADefinition() &&
11702       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11703       var->isExternallyVisible() && var->hasLinkage() &&
11704       !var->isInline() && !var->getDescribedVarTemplate() &&
11705       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11706       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11707                                   var->getLocation())) {
11708     // Find a previous declaration that's not a definition.
11709     VarDecl *prev = var->getPreviousDecl();
11710     while (prev && prev->isThisDeclarationADefinition())
11711       prev = prev->getPreviousDecl();
11712 
11713     if (!prev)
11714       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11715   }
11716 
11717   // Cache the result of checking for constant initialization.
11718   Optional<bool> CacheHasConstInit;
11719   const Expr *CacheCulprit;
11720   auto checkConstInit = [&]() mutable {
11721     if (!CacheHasConstInit)
11722       CacheHasConstInit = var->getInit()->isConstantInitializer(
11723             Context, var->getType()->isReferenceType(), &CacheCulprit);
11724     return *CacheHasConstInit;
11725   };
11726 
11727   if (var->getTLSKind() == VarDecl::TLS_Static) {
11728     if (var->getType().isDestructedType()) {
11729       // GNU C++98 edits for __thread, [basic.start.term]p3:
11730       //   The type of an object with thread storage duration shall not
11731       //   have a non-trivial destructor.
11732       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11733       if (getLangOpts().CPlusPlus11)
11734         Diag(var->getLocation(), diag::note_use_thread_local);
11735     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11736       if (!checkConstInit()) {
11737         // GNU C++98 edits for __thread, [basic.start.init]p4:
11738         //   An object of thread storage duration shall not require dynamic
11739         //   initialization.
11740         // FIXME: Need strict checking here.
11741         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11742           << CacheCulprit->getSourceRange();
11743         if (getLangOpts().CPlusPlus11)
11744           Diag(var->getLocation(), diag::note_use_thread_local);
11745       }
11746     }
11747   }
11748 
11749   // Apply section attributes and pragmas to global variables.
11750   bool GlobalStorage = var->hasGlobalStorage();
11751   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11752       !inTemplateInstantiation()) {
11753     PragmaStack<StringLiteral *> *Stack = nullptr;
11754     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11755     if (var->getType().isConstQualified())
11756       Stack = &ConstSegStack;
11757     else if (!var->getInit()) {
11758       Stack = &BSSSegStack;
11759       SectionFlags |= ASTContext::PSF_Write;
11760     } else {
11761       Stack = &DataSegStack;
11762       SectionFlags |= ASTContext::PSF_Write;
11763     }
11764     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11765       var->addAttr(SectionAttr::CreateImplicit(
11766           Context, SectionAttr::Declspec_allocate,
11767           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11768     }
11769     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11770       if (UnifySection(SA->getName(), SectionFlags, var))
11771         var->dropAttr<SectionAttr>();
11772 
11773     // Apply the init_seg attribute if this has an initializer.  If the
11774     // initializer turns out to not be dynamic, we'll end up ignoring this
11775     // attribute.
11776     if (CurInitSeg && var->getInit())
11777       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11778                                                CurInitSegLoc));
11779   }
11780 
11781   // All the following checks are C++ only.
11782   if (!getLangOpts().CPlusPlus) {
11783       // If this variable must be emitted, add it as an initializer for the
11784       // current module.
11785      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11786        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11787      return;
11788   }
11789 
11790   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11791     CheckCompleteDecompositionDeclaration(DD);
11792 
11793   QualType type = var->getType();
11794   if (type->isDependentType()) return;
11795 
11796   // __block variables might require us to capture a copy-initializer.
11797   if (var->hasAttr<BlocksAttr>()) {
11798     // It's currently invalid to ever have a __block variable with an
11799     // array type; should we diagnose that here?
11800 
11801     // Regardless, we don't want to ignore array nesting when
11802     // constructing this copy.
11803     if (type->isStructureOrClassType()) {
11804       EnterExpressionEvaluationContext scope(
11805           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11806       SourceLocation poi = var->getLocation();
11807       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11808       ExprResult result
11809         = PerformMoveOrCopyInitialization(
11810             InitializedEntity::InitializeBlock(poi, type, false),
11811             var, var->getType(), varRef, /*AllowNRVO=*/true);
11812       if (!result.isInvalid()) {
11813         result = MaybeCreateExprWithCleanups(result);
11814         Expr *init = result.getAs<Expr>();
11815         Context.setBlockVarCopyInit(var, init, canThrow(init));
11816       }
11817 
11818       // The destructor's exception spefication is needed when IRGen generates
11819       // block copy/destroy functions. Resolve it here.
11820       if (const CXXRecordDecl *RD = type->getAsCXXRecordDecl())
11821         if (CXXDestructorDecl *DD = RD->getDestructor()) {
11822           auto *FPT = DD->getType()->getAs<FunctionProtoType>();
11823           FPT = ResolveExceptionSpec(poi, FPT);
11824         }
11825     }
11826   }
11827 
11828   Expr *Init = var->getInit();
11829   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11830   QualType baseType = Context.getBaseElementType(type);
11831 
11832   if (Init && !Init->isValueDependent()) {
11833     if (var->isConstexpr()) {
11834       SmallVector<PartialDiagnosticAt, 8> Notes;
11835       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11836         SourceLocation DiagLoc = var->getLocation();
11837         // If the note doesn't add any useful information other than a source
11838         // location, fold it into the primary diagnostic.
11839         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11840               diag::note_invalid_subexpr_in_const_expr) {
11841           DiagLoc = Notes[0].first;
11842           Notes.clear();
11843         }
11844         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11845           << var << Init->getSourceRange();
11846         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11847           Diag(Notes[I].first, Notes[I].second);
11848       }
11849     } else if (var->isUsableInConstantExpressions(Context)) {
11850       // Check whether the initializer of a const variable of integral or
11851       // enumeration type is an ICE now, since we can't tell whether it was
11852       // initialized by a constant expression if we check later.
11853       var->checkInitIsICE();
11854     }
11855 
11856     // Don't emit further diagnostics about constexpr globals since they
11857     // were just diagnosed.
11858     if (!var->isConstexpr() && GlobalStorage &&
11859             var->hasAttr<RequireConstantInitAttr>()) {
11860       // FIXME: Need strict checking in C++03 here.
11861       bool DiagErr = getLangOpts().CPlusPlus11
11862           ? !var->checkInitIsICE() : !checkConstInit();
11863       if (DiagErr) {
11864         auto attr = var->getAttr<RequireConstantInitAttr>();
11865         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11866           << Init->getSourceRange();
11867         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11868           << attr->getRange();
11869         if (getLangOpts().CPlusPlus11) {
11870           APValue Value;
11871           SmallVector<PartialDiagnosticAt, 8> Notes;
11872           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11873           for (auto &it : Notes)
11874             Diag(it.first, it.second);
11875         } else {
11876           Diag(CacheCulprit->getExprLoc(),
11877                diag::note_invalid_subexpr_in_const_expr)
11878               << CacheCulprit->getSourceRange();
11879         }
11880       }
11881     }
11882     else if (!var->isConstexpr() && IsGlobal &&
11883              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11884                                     var->getLocation())) {
11885       // Warn about globals which don't have a constant initializer.  Don't
11886       // warn about globals with a non-trivial destructor because we already
11887       // warned about them.
11888       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11889       if (!(RD && !RD->hasTrivialDestructor())) {
11890         if (!checkConstInit())
11891           Diag(var->getLocation(), diag::warn_global_constructor)
11892             << Init->getSourceRange();
11893       }
11894     }
11895   }
11896 
11897   // Require the destructor.
11898   if (const RecordType *recordType = baseType->getAs<RecordType>())
11899     FinalizeVarWithDestructor(var, recordType);
11900 
11901   // If this variable must be emitted, add it as an initializer for the current
11902   // module.
11903   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11904     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11905 }
11906 
11907 /// Determines if a variable's alignment is dependent.
11908 static bool hasDependentAlignment(VarDecl *VD) {
11909   if (VD->getType()->isDependentType())
11910     return true;
11911   for (auto *I : VD->specific_attrs<AlignedAttr>())
11912     if (I->isAlignmentDependent())
11913       return true;
11914   return false;
11915 }
11916 
11917 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11918 /// any semantic actions necessary after any initializer has been attached.
11919 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11920   // Note that we are no longer parsing the initializer for this declaration.
11921   ParsingInitForAutoVars.erase(ThisDecl);
11922 
11923   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11924   if (!VD)
11925     return;
11926 
11927   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11928   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11929       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11930     if (PragmaClangBSSSection.Valid)
11931       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11932                                                             PragmaClangBSSSection.SectionName,
11933                                                             PragmaClangBSSSection.PragmaLocation));
11934     if (PragmaClangDataSection.Valid)
11935       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11936                                                              PragmaClangDataSection.SectionName,
11937                                                              PragmaClangDataSection.PragmaLocation));
11938     if (PragmaClangRodataSection.Valid)
11939       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11940                                                                PragmaClangRodataSection.SectionName,
11941                                                                PragmaClangRodataSection.PragmaLocation));
11942   }
11943 
11944   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11945     for (auto *BD : DD->bindings()) {
11946       FinalizeDeclaration(BD);
11947     }
11948   }
11949 
11950   checkAttributesAfterMerging(*this, *VD);
11951 
11952   // Perform TLS alignment check here after attributes attached to the variable
11953   // which may affect the alignment have been processed. Only perform the check
11954   // if the target has a maximum TLS alignment (zero means no constraints).
11955   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11956     // Protect the check so that it's not performed on dependent types and
11957     // dependent alignments (we can't determine the alignment in that case).
11958     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11959         !VD->isInvalidDecl()) {
11960       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11961       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11962         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11963           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11964           << (unsigned)MaxAlignChars.getQuantity();
11965       }
11966     }
11967   }
11968 
11969   if (VD->isStaticLocal()) {
11970     if (FunctionDecl *FD =
11971             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11972       // Static locals inherit dll attributes from their function.
11973       if (Attr *A = getDLLAttr(FD)) {
11974         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11975         NewAttr->setInherited(true);
11976         VD->addAttr(NewAttr);
11977       }
11978       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
11979       // function, only __shared__ variables or variables without any device
11980       // memory qualifiers may be declared with static storage class.
11981       // Note: It is unclear how a function-scope non-const static variable
11982       // without device memory qualifier is implemented, therefore only static
11983       // const variable without device memory qualifier is allowed.
11984       [&]() {
11985         if (!getLangOpts().CUDA)
11986           return;
11987         if (VD->hasAttr<CUDASharedAttr>())
11988           return;
11989         if (VD->getType().isConstQualified() &&
11990             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11991           return;
11992         if (CUDADiagIfDeviceCode(VD->getLocation(),
11993                                  diag::err_device_static_local_var)
11994             << CurrentCUDATarget())
11995           VD->setInvalidDecl();
11996       }();
11997     }
11998   }
11999 
12000   // Perform check for initializers of device-side global variables.
12001   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12002   // 7.5). We must also apply the same checks to all __shared__
12003   // variables whether they are local or not. CUDA also allows
12004   // constant initializers for __constant__ and __device__ variables.
12005   if (getLangOpts().CUDA)
12006     checkAllowedCUDAInitializer(VD);
12007 
12008   // Grab the dllimport or dllexport attribute off of the VarDecl.
12009   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12010 
12011   // Imported static data members cannot be defined out-of-line.
12012   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12013     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12014         VD->isThisDeclarationADefinition()) {
12015       // We allow definitions of dllimport class template static data members
12016       // with a warning.
12017       CXXRecordDecl *Context =
12018         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12019       bool IsClassTemplateMember =
12020           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12021           Context->getDescribedClassTemplate();
12022 
12023       Diag(VD->getLocation(),
12024            IsClassTemplateMember
12025                ? diag::warn_attribute_dllimport_static_field_definition
12026                : diag::err_attribute_dllimport_static_field_definition);
12027       Diag(IA->getLocation(), diag::note_attribute);
12028       if (!IsClassTemplateMember)
12029         VD->setInvalidDecl();
12030     }
12031   }
12032 
12033   // dllimport/dllexport variables cannot be thread local, their TLS index
12034   // isn't exported with the variable.
12035   if (DLLAttr && VD->getTLSKind()) {
12036     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12037     if (F && getDLLAttr(F)) {
12038       assert(VD->isStaticLocal());
12039       // But if this is a static local in a dlimport/dllexport function, the
12040       // function will never be inlined, which means the var would never be
12041       // imported, so having it marked import/export is safe.
12042     } else {
12043       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12044                                                                     << DLLAttr;
12045       VD->setInvalidDecl();
12046     }
12047   }
12048 
12049   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12050     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12051       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12052       VD->dropAttr<UsedAttr>();
12053     }
12054   }
12055 
12056   const DeclContext *DC = VD->getDeclContext();
12057   // If there's a #pragma GCC visibility in scope, and this isn't a class
12058   // member, set the visibility of this variable.
12059   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12060     AddPushedVisibilityAttribute(VD);
12061 
12062   // FIXME: Warn on unused var template partial specializations.
12063   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12064     MarkUnusedFileScopedDecl(VD);
12065 
12066   // Now we have parsed the initializer and can update the table of magic
12067   // tag values.
12068   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12069       !VD->getType()->isIntegralOrEnumerationType())
12070     return;
12071 
12072   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12073     const Expr *MagicValueExpr = VD->getInit();
12074     if (!MagicValueExpr) {
12075       continue;
12076     }
12077     llvm::APSInt MagicValueInt;
12078     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12079       Diag(I->getRange().getBegin(),
12080            diag::err_type_tag_for_datatype_not_ice)
12081         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12082       continue;
12083     }
12084     if (MagicValueInt.getActiveBits() > 64) {
12085       Diag(I->getRange().getBegin(),
12086            diag::err_type_tag_for_datatype_too_large)
12087         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12088       continue;
12089     }
12090     uint64_t MagicValue = MagicValueInt.getZExtValue();
12091     RegisterTypeTagForDatatype(I->getArgumentKind(),
12092                                MagicValue,
12093                                I->getMatchingCType(),
12094                                I->getLayoutCompatible(),
12095                                I->getMustBeNull());
12096   }
12097 }
12098 
12099 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12100   auto *VD = dyn_cast<VarDecl>(DD);
12101   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12102 }
12103 
12104 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12105                                                    ArrayRef<Decl *> Group) {
12106   SmallVector<Decl*, 8> Decls;
12107 
12108   if (DS.isTypeSpecOwned())
12109     Decls.push_back(DS.getRepAsDecl());
12110 
12111   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12112   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12113   bool DiagnosedMultipleDecomps = false;
12114   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12115   bool DiagnosedNonDeducedAuto = false;
12116 
12117   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12118     if (Decl *D = Group[i]) {
12119       // For declarators, there are some additional syntactic-ish checks we need
12120       // to perform.
12121       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12122         if (!FirstDeclaratorInGroup)
12123           FirstDeclaratorInGroup = DD;
12124         if (!FirstDecompDeclaratorInGroup)
12125           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12126         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12127             !hasDeducedAuto(DD))
12128           FirstNonDeducedAutoInGroup = DD;
12129 
12130         if (FirstDeclaratorInGroup != DD) {
12131           // A decomposition declaration cannot be combined with any other
12132           // declaration in the same group.
12133           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12134             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12135                  diag::err_decomp_decl_not_alone)
12136                 << FirstDeclaratorInGroup->getSourceRange()
12137                 << DD->getSourceRange();
12138             DiagnosedMultipleDecomps = true;
12139           }
12140 
12141           // A declarator that uses 'auto' in any way other than to declare a
12142           // variable with a deduced type cannot be combined with any other
12143           // declarator in the same group.
12144           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12145             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12146                  diag::err_auto_non_deduced_not_alone)
12147                 << FirstNonDeducedAutoInGroup->getType()
12148                        ->hasAutoForTrailingReturnType()
12149                 << FirstDeclaratorInGroup->getSourceRange()
12150                 << DD->getSourceRange();
12151             DiagnosedNonDeducedAuto = true;
12152           }
12153         }
12154       }
12155 
12156       Decls.push_back(D);
12157     }
12158   }
12159 
12160   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12161     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12162       handleTagNumbering(Tag, S);
12163       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12164           getLangOpts().CPlusPlus)
12165         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12166     }
12167   }
12168 
12169   return BuildDeclaratorGroup(Decls);
12170 }
12171 
12172 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12173 /// group, performing any necessary semantic checking.
12174 Sema::DeclGroupPtrTy
12175 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12176   // C++14 [dcl.spec.auto]p7: (DR1347)
12177   //   If the type that replaces the placeholder type is not the same in each
12178   //   deduction, the program is ill-formed.
12179   if (Group.size() > 1) {
12180     QualType Deduced;
12181     VarDecl *DeducedDecl = nullptr;
12182     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12183       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12184       if (!D || D->isInvalidDecl())
12185         break;
12186       DeducedType *DT = D->getType()->getContainedDeducedType();
12187       if (!DT || DT->getDeducedType().isNull())
12188         continue;
12189       if (Deduced.isNull()) {
12190         Deduced = DT->getDeducedType();
12191         DeducedDecl = D;
12192       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12193         auto *AT = dyn_cast<AutoType>(DT);
12194         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12195              diag::err_auto_different_deductions)
12196           << (AT ? (unsigned)AT->getKeyword() : 3)
12197           << Deduced << DeducedDecl->getDeclName()
12198           << DT->getDeducedType() << D->getDeclName()
12199           << DeducedDecl->getInit()->getSourceRange()
12200           << D->getInit()->getSourceRange();
12201         D->setInvalidDecl();
12202         break;
12203       }
12204     }
12205   }
12206 
12207   ActOnDocumentableDecls(Group);
12208 
12209   return DeclGroupPtrTy::make(
12210       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12211 }
12212 
12213 void Sema::ActOnDocumentableDecl(Decl *D) {
12214   ActOnDocumentableDecls(D);
12215 }
12216 
12217 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12218   // Don't parse the comment if Doxygen diagnostics are ignored.
12219   if (Group.empty() || !Group[0])
12220     return;
12221 
12222   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12223                       Group[0]->getLocation()) &&
12224       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12225                       Group[0]->getLocation()))
12226     return;
12227 
12228   if (Group.size() >= 2) {
12229     // This is a decl group.  Normally it will contain only declarations
12230     // produced from declarator list.  But in case we have any definitions or
12231     // additional declaration references:
12232     //   'typedef struct S {} S;'
12233     //   'typedef struct S *S;'
12234     //   'struct S *pS;'
12235     // FinalizeDeclaratorGroup adds these as separate declarations.
12236     Decl *MaybeTagDecl = Group[0];
12237     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12238       Group = Group.slice(1);
12239     }
12240   }
12241 
12242   // See if there are any new comments that are not attached to a decl.
12243   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12244   if (!Comments.empty() &&
12245       !Comments.back()->isAttached()) {
12246     // There is at least one comment that not attached to a decl.
12247     // Maybe it should be attached to one of these decls?
12248     //
12249     // Note that this way we pick up not only comments that precede the
12250     // declaration, but also comments that *follow* the declaration -- thanks to
12251     // the lookahead in the lexer: we've consumed the semicolon and looked
12252     // ahead through comments.
12253     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12254       Context.getCommentForDecl(Group[i], &PP);
12255   }
12256 }
12257 
12258 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12259 /// to introduce parameters into function prototype scope.
12260 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12261   const DeclSpec &DS = D.getDeclSpec();
12262 
12263   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12264 
12265   // C++03 [dcl.stc]p2 also permits 'auto'.
12266   StorageClass SC = SC_None;
12267   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12268     SC = SC_Register;
12269     // In C++11, the 'register' storage class specifier is deprecated.
12270     // In C++17, it is not allowed, but we tolerate it as an extension.
12271     if (getLangOpts().CPlusPlus11) {
12272       Diag(DS.getStorageClassSpecLoc(),
12273            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12274                                      : diag::warn_deprecated_register)
12275         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12276     }
12277   } else if (getLangOpts().CPlusPlus &&
12278              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12279     SC = SC_Auto;
12280   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12281     Diag(DS.getStorageClassSpecLoc(),
12282          diag::err_invalid_storage_class_in_func_decl);
12283     D.getMutableDeclSpec().ClearStorageClassSpecs();
12284   }
12285 
12286   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12287     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12288       << DeclSpec::getSpecifierName(TSCS);
12289   if (DS.isInlineSpecified())
12290     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12291         << getLangOpts().CPlusPlus17;
12292   if (DS.isConstexprSpecified())
12293     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12294       << 0;
12295 
12296   DiagnoseFunctionSpecifiers(DS);
12297 
12298   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12299   QualType parmDeclType = TInfo->getType();
12300 
12301   if (getLangOpts().CPlusPlus) {
12302     // Check that there are no default arguments inside the type of this
12303     // parameter.
12304     CheckExtraCXXDefaultArguments(D);
12305 
12306     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12307     if (D.getCXXScopeSpec().isSet()) {
12308       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12309         << D.getCXXScopeSpec().getRange();
12310       D.getCXXScopeSpec().clear();
12311     }
12312   }
12313 
12314   // Ensure we have a valid name
12315   IdentifierInfo *II = nullptr;
12316   if (D.hasName()) {
12317     II = D.getIdentifier();
12318     if (!II) {
12319       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12320         << GetNameForDeclarator(D).getName();
12321       D.setInvalidType(true);
12322     }
12323   }
12324 
12325   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12326   if (II) {
12327     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12328                    ForVisibleRedeclaration);
12329     LookupName(R, S);
12330     if (R.isSingleResult()) {
12331       NamedDecl *PrevDecl = R.getFoundDecl();
12332       if (PrevDecl->isTemplateParameter()) {
12333         // Maybe we will complain about the shadowed template parameter.
12334         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12335         // Just pretend that we didn't see the previous declaration.
12336         PrevDecl = nullptr;
12337       } else if (S->isDeclScope(PrevDecl)) {
12338         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12339         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12340 
12341         // Recover by removing the name
12342         II = nullptr;
12343         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12344         D.setInvalidType(true);
12345       }
12346     }
12347   }
12348 
12349   // Temporarily put parameter variables in the translation unit, not
12350   // the enclosing context.  This prevents them from accidentally
12351   // looking like class members in C++.
12352   ParmVarDecl *New =
12353       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12354                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12355 
12356   if (D.isInvalidType())
12357     New->setInvalidDecl();
12358 
12359   assert(S->isFunctionPrototypeScope());
12360   assert(S->getFunctionPrototypeDepth() >= 1);
12361   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12362                     S->getNextFunctionPrototypeIndex());
12363 
12364   // Add the parameter declaration into this scope.
12365   S->AddDecl(New);
12366   if (II)
12367     IdResolver.AddDecl(New);
12368 
12369   ProcessDeclAttributes(S, New, D);
12370 
12371   if (D.getDeclSpec().isModulePrivateSpecified())
12372     Diag(New->getLocation(), diag::err_module_private_local)
12373       << 1 << New->getDeclName()
12374       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12375       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12376 
12377   if (New->hasAttr<BlocksAttr>()) {
12378     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12379   }
12380   return New;
12381 }
12382 
12383 /// Synthesizes a variable for a parameter arising from a
12384 /// typedef.
12385 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12386                                               SourceLocation Loc,
12387                                               QualType T) {
12388   /* FIXME: setting StartLoc == Loc.
12389      Would it be worth to modify callers so as to provide proper source
12390      location for the unnamed parameters, embedding the parameter's type? */
12391   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12392                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12393                                            SC_None, nullptr);
12394   Param->setImplicit();
12395   return Param;
12396 }
12397 
12398 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12399   // Don't diagnose unused-parameter errors in template instantiations; we
12400   // will already have done so in the template itself.
12401   if (inTemplateInstantiation())
12402     return;
12403 
12404   for (const ParmVarDecl *Parameter : Parameters) {
12405     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12406         !Parameter->hasAttr<UnusedAttr>()) {
12407       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12408         << Parameter->getDeclName();
12409     }
12410   }
12411 }
12412 
12413 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12414     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12415   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12416     return;
12417 
12418   // Warn if the return value is pass-by-value and larger than the specified
12419   // threshold.
12420   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12421     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12422     if (Size > LangOpts.NumLargeByValueCopy)
12423       Diag(D->getLocation(), diag::warn_return_value_size)
12424           << D->getDeclName() << Size;
12425   }
12426 
12427   // Warn if any parameter is pass-by-value and larger than the specified
12428   // threshold.
12429   for (const ParmVarDecl *Parameter : Parameters) {
12430     QualType T = Parameter->getType();
12431     if (T->isDependentType() || !T.isPODType(Context))
12432       continue;
12433     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12434     if (Size > LangOpts.NumLargeByValueCopy)
12435       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12436           << Parameter->getDeclName() << Size;
12437   }
12438 }
12439 
12440 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12441                                   SourceLocation NameLoc, IdentifierInfo *Name,
12442                                   QualType T, TypeSourceInfo *TSInfo,
12443                                   StorageClass SC) {
12444   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12445   if (getLangOpts().ObjCAutoRefCount &&
12446       T.getObjCLifetime() == Qualifiers::OCL_None &&
12447       T->isObjCLifetimeType()) {
12448 
12449     Qualifiers::ObjCLifetime lifetime;
12450 
12451     // Special cases for arrays:
12452     //   - if it's const, use __unsafe_unretained
12453     //   - otherwise, it's an error
12454     if (T->isArrayType()) {
12455       if (!T.isConstQualified()) {
12456         DelayedDiagnostics.add(
12457             sema::DelayedDiagnostic::makeForbiddenType(
12458             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12459       }
12460       lifetime = Qualifiers::OCL_ExplicitNone;
12461     } else {
12462       lifetime = T->getObjCARCImplicitLifetime();
12463     }
12464     T = Context.getLifetimeQualifiedType(T, lifetime);
12465   }
12466 
12467   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12468                                          Context.getAdjustedParameterType(T),
12469                                          TSInfo, SC, nullptr);
12470 
12471   // Parameters can not be abstract class types.
12472   // For record types, this is done by the AbstractClassUsageDiagnoser once
12473   // the class has been completely parsed.
12474   if (!CurContext->isRecord() &&
12475       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12476                              AbstractParamType))
12477     New->setInvalidDecl();
12478 
12479   // Parameter declarators cannot be interface types. All ObjC objects are
12480   // passed by reference.
12481   if (T->isObjCObjectType()) {
12482     SourceLocation TypeEndLoc =
12483         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12484     Diag(NameLoc,
12485          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12486       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12487     T = Context.getObjCObjectPointerType(T);
12488     New->setType(T);
12489   }
12490 
12491   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12492   // duration shall not be qualified by an address-space qualifier."
12493   // Since all parameters have automatic store duration, they can not have
12494   // an address space.
12495   if (T.getAddressSpace() != LangAS::Default &&
12496       // OpenCL allows function arguments declared to be an array of a type
12497       // to be qualified with an address space.
12498       !(getLangOpts().OpenCL &&
12499         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12500     Diag(NameLoc, diag::err_arg_with_address_space);
12501     New->setInvalidDecl();
12502   }
12503 
12504   return New;
12505 }
12506 
12507 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12508                                            SourceLocation LocAfterDecls) {
12509   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12510 
12511   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12512   // for a K&R function.
12513   if (!FTI.hasPrototype) {
12514     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12515       --i;
12516       if (FTI.Params[i].Param == nullptr) {
12517         SmallString<256> Code;
12518         llvm::raw_svector_ostream(Code)
12519             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12520         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12521             << FTI.Params[i].Ident
12522             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12523 
12524         // Implicitly declare the argument as type 'int' for lack of a better
12525         // type.
12526         AttributeFactory attrs;
12527         DeclSpec DS(attrs);
12528         const char* PrevSpec; // unused
12529         unsigned DiagID; // unused
12530         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12531                            DiagID, Context.getPrintingPolicy());
12532         // Use the identifier location for the type source range.
12533         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12534         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12535         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12536         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12537         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12538       }
12539     }
12540   }
12541 }
12542 
12543 Decl *
12544 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12545                               MultiTemplateParamsArg TemplateParameterLists,
12546                               SkipBodyInfo *SkipBody) {
12547   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12548   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12549   Scope *ParentScope = FnBodyScope->getParent();
12550 
12551   D.setFunctionDefinitionKind(FDK_Definition);
12552   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12553   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12554 }
12555 
12556 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12557   Consumer.HandleInlineFunctionDefinition(D);
12558 }
12559 
12560 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12561                              const FunctionDecl*& PossibleZeroParamPrototype) {
12562   // Don't warn about invalid declarations.
12563   if (FD->isInvalidDecl())
12564     return false;
12565 
12566   // Or declarations that aren't global.
12567   if (!FD->isGlobal())
12568     return false;
12569 
12570   // Don't warn about C++ member functions.
12571   if (isa<CXXMethodDecl>(FD))
12572     return false;
12573 
12574   // Don't warn about 'main'.
12575   if (FD->isMain())
12576     return false;
12577 
12578   // Don't warn about inline functions.
12579   if (FD->isInlined())
12580     return false;
12581 
12582   // Don't warn about function templates.
12583   if (FD->getDescribedFunctionTemplate())
12584     return false;
12585 
12586   // Don't warn about function template specializations.
12587   if (FD->isFunctionTemplateSpecialization())
12588     return false;
12589 
12590   // Don't warn for OpenCL kernels.
12591   if (FD->hasAttr<OpenCLKernelAttr>())
12592     return false;
12593 
12594   // Don't warn on explicitly deleted functions.
12595   if (FD->isDeleted())
12596     return false;
12597 
12598   bool MissingPrototype = true;
12599   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12600        Prev; Prev = Prev->getPreviousDecl()) {
12601     // Ignore any declarations that occur in function or method
12602     // scope, because they aren't visible from the header.
12603     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12604       continue;
12605 
12606     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12607     if (FD->getNumParams() == 0)
12608       PossibleZeroParamPrototype = Prev;
12609     break;
12610   }
12611 
12612   return MissingPrototype;
12613 }
12614 
12615 void
12616 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12617                                    const FunctionDecl *EffectiveDefinition,
12618                                    SkipBodyInfo *SkipBody) {
12619   const FunctionDecl *Definition = EffectiveDefinition;
12620   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12621     // If this is a friend function defined in a class template, it does not
12622     // have a body until it is used, nevertheless it is a definition, see
12623     // [temp.inst]p2:
12624     //
12625     // ... for the purpose of determining whether an instantiated redeclaration
12626     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12627     // corresponds to a definition in the template is considered to be a
12628     // definition.
12629     //
12630     // The following code must produce redefinition error:
12631     //
12632     //     template<typename T> struct C20 { friend void func_20() {} };
12633     //     C20<int> c20i;
12634     //     void func_20() {}
12635     //
12636     for (auto I : FD->redecls()) {
12637       if (I != FD && !I->isInvalidDecl() &&
12638           I->getFriendObjectKind() != Decl::FOK_None) {
12639         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12640           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12641             // A merged copy of the same function, instantiated as a member of
12642             // the same class, is OK.
12643             if (declaresSameEntity(OrigFD, Original) &&
12644                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12645                                    cast<Decl>(FD->getLexicalDeclContext())))
12646               continue;
12647           }
12648 
12649           if (Original->isThisDeclarationADefinition()) {
12650             Definition = I;
12651             break;
12652           }
12653         }
12654       }
12655     }
12656   }
12657   if (!Definition)
12658     return;
12659 
12660   if (canRedefineFunction(Definition, getLangOpts()))
12661     return;
12662 
12663   // Don't emit an error when this is redefinition of a typo-corrected
12664   // definition.
12665   if (TypoCorrectedFunctionDefinitions.count(Definition))
12666     return;
12667 
12668   // If we don't have a visible definition of the function, and it's inline or
12669   // a template, skip the new definition.
12670   if (SkipBody && !hasVisibleDefinition(Definition) &&
12671       (Definition->getFormalLinkage() == InternalLinkage ||
12672        Definition->isInlined() ||
12673        Definition->getDescribedFunctionTemplate() ||
12674        Definition->getNumTemplateParameterLists())) {
12675     SkipBody->ShouldSkip = true;
12676     if (auto *TD = Definition->getDescribedFunctionTemplate())
12677       makeMergedDefinitionVisible(TD);
12678     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12679     return;
12680   }
12681 
12682   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12683       Definition->getStorageClass() == SC_Extern)
12684     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12685         << FD->getDeclName() << getLangOpts().CPlusPlus;
12686   else
12687     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12688 
12689   Diag(Definition->getLocation(), diag::note_previous_definition);
12690   FD->setInvalidDecl();
12691 }
12692 
12693 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12694                                    Sema &S) {
12695   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12696 
12697   LambdaScopeInfo *LSI = S.PushLambdaScope();
12698   LSI->CallOperator = CallOperator;
12699   LSI->Lambda = LambdaClass;
12700   LSI->ReturnType = CallOperator->getReturnType();
12701   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12702 
12703   if (LCD == LCD_None)
12704     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12705   else if (LCD == LCD_ByCopy)
12706     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12707   else if (LCD == LCD_ByRef)
12708     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12709   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12710 
12711   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12712   LSI->Mutable = !CallOperator->isConst();
12713 
12714   // Add the captures to the LSI so they can be noted as already
12715   // captured within tryCaptureVar.
12716   auto I = LambdaClass->field_begin();
12717   for (const auto &C : LambdaClass->captures()) {
12718     if (C.capturesVariable()) {
12719       VarDecl *VD = C.getCapturedVar();
12720       if (VD->isInitCapture())
12721         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12722       QualType CaptureType = VD->getType();
12723       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12724       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12725           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12726           /*EllipsisLoc*/C.isPackExpansion()
12727                          ? C.getEllipsisLoc() : SourceLocation(),
12728           CaptureType, /*Expr*/ nullptr);
12729 
12730     } else if (C.capturesThis()) {
12731       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12732                               /*Expr*/ nullptr,
12733                               C.getCaptureKind() == LCK_StarThis);
12734     } else {
12735       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12736     }
12737     ++I;
12738   }
12739 }
12740 
12741 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12742                                     SkipBodyInfo *SkipBody) {
12743   if (!D) {
12744     // Parsing the function declaration failed in some way. Push on a fake scope
12745     // anyway so we can try to parse the function body.
12746     PushFunctionScope();
12747     return D;
12748   }
12749 
12750   FunctionDecl *FD = nullptr;
12751 
12752   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12753     FD = FunTmpl->getTemplatedDecl();
12754   else
12755     FD = cast<FunctionDecl>(D);
12756 
12757   // Check for defining attributes before the check for redefinition.
12758   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12759     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12760     FD->dropAttr<AliasAttr>();
12761     FD->setInvalidDecl();
12762   }
12763   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12764     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12765     FD->dropAttr<IFuncAttr>();
12766     FD->setInvalidDecl();
12767   }
12768 
12769   // See if this is a redefinition. If 'will have body' is already set, then
12770   // these checks were already performed when it was set.
12771   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12772     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12773 
12774     // If we're skipping the body, we're done. Don't enter the scope.
12775     if (SkipBody && SkipBody->ShouldSkip)
12776       return D;
12777   }
12778 
12779   // Mark this function as "will have a body eventually".  This lets users to
12780   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12781   // this function.
12782   FD->setWillHaveBody();
12783 
12784   // If we are instantiating a generic lambda call operator, push
12785   // a LambdaScopeInfo onto the function stack.  But use the information
12786   // that's already been calculated (ActOnLambdaExpr) to prime the current
12787   // LambdaScopeInfo.
12788   // When the template operator is being specialized, the LambdaScopeInfo,
12789   // has to be properly restored so that tryCaptureVariable doesn't try
12790   // and capture any new variables. In addition when calculating potential
12791   // captures during transformation of nested lambdas, it is necessary to
12792   // have the LSI properly restored.
12793   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12794     assert(inTemplateInstantiation() &&
12795            "There should be an active template instantiation on the stack "
12796            "when instantiating a generic lambda!");
12797     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12798   } else {
12799     // Enter a new function scope
12800     PushFunctionScope();
12801   }
12802 
12803   // Builtin functions cannot be defined.
12804   if (unsigned BuiltinID = FD->getBuiltinID()) {
12805     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12806         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12807       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12808       FD->setInvalidDecl();
12809     }
12810   }
12811 
12812   // The return type of a function definition must be complete
12813   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12814   QualType ResultType = FD->getReturnType();
12815   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12816       !FD->isInvalidDecl() &&
12817       RequireCompleteType(FD->getLocation(), ResultType,
12818                           diag::err_func_def_incomplete_result))
12819     FD->setInvalidDecl();
12820 
12821   if (FnBodyScope)
12822     PushDeclContext(FnBodyScope, FD);
12823 
12824   // Check the validity of our function parameters
12825   CheckParmsForFunctionDef(FD->parameters(),
12826                            /*CheckParameterNames=*/true);
12827 
12828   // Add non-parameter declarations already in the function to the current
12829   // scope.
12830   if (FnBodyScope) {
12831     for (Decl *NPD : FD->decls()) {
12832       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12833       if (!NonParmDecl)
12834         continue;
12835       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12836              "parameters should not be in newly created FD yet");
12837 
12838       // If the decl has a name, make it accessible in the current scope.
12839       if (NonParmDecl->getDeclName())
12840         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12841 
12842       // Similarly, dive into enums and fish their constants out, making them
12843       // accessible in this scope.
12844       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12845         for (auto *EI : ED->enumerators())
12846           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12847       }
12848     }
12849   }
12850 
12851   // Introduce our parameters into the function scope
12852   for (auto Param : FD->parameters()) {
12853     Param->setOwningFunction(FD);
12854 
12855     // If this has an identifier, add it to the scope stack.
12856     if (Param->getIdentifier() && FnBodyScope) {
12857       CheckShadow(FnBodyScope, Param);
12858 
12859       PushOnScopeChains(Param, FnBodyScope);
12860     }
12861   }
12862 
12863   // Ensure that the function's exception specification is instantiated.
12864   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12865     ResolveExceptionSpec(D->getLocation(), FPT);
12866 
12867   // dllimport cannot be applied to non-inline function definitions.
12868   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12869       !FD->isTemplateInstantiation()) {
12870     assert(!FD->hasAttr<DLLExportAttr>());
12871     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12872     FD->setInvalidDecl();
12873     return D;
12874   }
12875   // We want to attach documentation to original Decl (which might be
12876   // a function template).
12877   ActOnDocumentableDecl(D);
12878   if (getCurLexicalContext()->isObjCContainer() &&
12879       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12880       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12881     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12882 
12883   return D;
12884 }
12885 
12886 /// Given the set of return statements within a function body,
12887 /// compute the variables that are subject to the named return value
12888 /// optimization.
12889 ///
12890 /// Each of the variables that is subject to the named return value
12891 /// optimization will be marked as NRVO variables in the AST, and any
12892 /// return statement that has a marked NRVO variable as its NRVO candidate can
12893 /// use the named return value optimization.
12894 ///
12895 /// This function applies a very simplistic algorithm for NRVO: if every return
12896 /// statement in the scope of a variable has the same NRVO candidate, that
12897 /// candidate is an NRVO variable.
12898 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12899   ReturnStmt **Returns = Scope->Returns.data();
12900 
12901   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12902     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12903       if (!NRVOCandidate->isNRVOVariable())
12904         Returns[I]->setNRVOCandidate(nullptr);
12905     }
12906   }
12907 }
12908 
12909 bool Sema::canDelayFunctionBody(const Declarator &D) {
12910   // We can't delay parsing the body of a constexpr function template (yet).
12911   if (D.getDeclSpec().isConstexprSpecified())
12912     return false;
12913 
12914   // We can't delay parsing the body of a function template with a deduced
12915   // return type (yet).
12916   if (D.getDeclSpec().hasAutoTypeSpec()) {
12917     // If the placeholder introduces a non-deduced trailing return type,
12918     // we can still delay parsing it.
12919     if (D.getNumTypeObjects()) {
12920       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12921       if (Outer.Kind == DeclaratorChunk::Function &&
12922           Outer.Fun.hasTrailingReturnType()) {
12923         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12924         return Ty.isNull() || !Ty->isUndeducedType();
12925       }
12926     }
12927     return false;
12928   }
12929 
12930   return true;
12931 }
12932 
12933 bool Sema::canSkipFunctionBody(Decl *D) {
12934   // We cannot skip the body of a function (or function template) which is
12935   // constexpr, since we may need to evaluate its body in order to parse the
12936   // rest of the file.
12937   // We cannot skip the body of a function with an undeduced return type,
12938   // because any callers of that function need to know the type.
12939   if (const FunctionDecl *FD = D->getAsFunction()) {
12940     if (FD->isConstexpr())
12941       return false;
12942     // We can't simply call Type::isUndeducedType here, because inside template
12943     // auto can be deduced to a dependent type, which is not considered
12944     // "undeduced".
12945     if (FD->getReturnType()->getContainedDeducedType())
12946       return false;
12947   }
12948   return Consumer.shouldSkipFunctionBody(D);
12949 }
12950 
12951 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12952   if (!Decl)
12953     return nullptr;
12954   if (FunctionDecl *FD = Decl->getAsFunction())
12955     FD->setHasSkippedBody();
12956   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12957     MD->setHasSkippedBody();
12958   return Decl;
12959 }
12960 
12961 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12962   return ActOnFinishFunctionBody(D, BodyArg, false);
12963 }
12964 
12965 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12966                                     bool IsInstantiation) {
12967   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12968 
12969   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12970   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12971 
12972   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12973     CheckCompletedCoroutineBody(FD, Body);
12974 
12975   if (FD) {
12976     FD->setBody(Body);
12977     FD->setWillHaveBody(false);
12978 
12979     if (getLangOpts().CPlusPlus14) {
12980       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12981           FD->getReturnType()->isUndeducedType()) {
12982         // If the function has a deduced result type but contains no 'return'
12983         // statements, the result type as written must be exactly 'auto', and
12984         // the deduced result type is 'void'.
12985         if (!FD->getReturnType()->getAs<AutoType>()) {
12986           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12987               << FD->getReturnType();
12988           FD->setInvalidDecl();
12989         } else {
12990           // Substitute 'void' for the 'auto' in the type.
12991           TypeLoc ResultType = getReturnTypeLoc(FD);
12992           Context.adjustDeducedFunctionResultType(
12993               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12994         }
12995       }
12996     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12997       // In C++11, we don't use 'auto' deduction rules for lambda call
12998       // operators because we don't support return type deduction.
12999       auto *LSI = getCurLambda();
13000       if (LSI->HasImplicitReturnType) {
13001         deduceClosureReturnType(*LSI);
13002 
13003         // C++11 [expr.prim.lambda]p4:
13004         //   [...] if there are no return statements in the compound-statement
13005         //   [the deduced type is] the type void
13006         QualType RetType =
13007             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13008 
13009         // Update the return type to the deduced type.
13010         const FunctionProtoType *Proto =
13011             FD->getType()->getAs<FunctionProtoType>();
13012         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13013                                             Proto->getExtProtoInfo()));
13014       }
13015     }
13016 
13017     // If the function implicitly returns zero (like 'main') or is naked,
13018     // don't complain about missing return statements.
13019     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13020       WP.disableCheckFallThrough();
13021 
13022     // MSVC permits the use of pure specifier (=0) on function definition,
13023     // defined at class scope, warn about this non-standard construct.
13024     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13025       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13026 
13027     if (!FD->isInvalidDecl()) {
13028       // Don't diagnose unused parameters of defaulted or deleted functions.
13029       if (!FD->isDeleted() && !FD->isDefaulted())
13030         DiagnoseUnusedParameters(FD->parameters());
13031       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13032                                              FD->getReturnType(), FD);
13033 
13034       // If this is a structor, we need a vtable.
13035       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13036         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13037       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13038         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13039 
13040       // Try to apply the named return value optimization. We have to check
13041       // if we can do this here because lambdas keep return statements around
13042       // to deduce an implicit return type.
13043       if (FD->getReturnType()->isRecordType() &&
13044           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13045         computeNRVO(Body, getCurFunction());
13046     }
13047 
13048     // GNU warning -Wmissing-prototypes:
13049     //   Warn if a global function is defined without a previous
13050     //   prototype declaration. This warning is issued even if the
13051     //   definition itself provides a prototype. The aim is to detect
13052     //   global functions that fail to be declared in header files.
13053     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13054     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13055       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13056 
13057       if (PossibleZeroParamPrototype) {
13058         // We found a declaration that is not a prototype,
13059         // but that could be a zero-parameter prototype
13060         if (TypeSourceInfo *TI =
13061                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13062           TypeLoc TL = TI->getTypeLoc();
13063           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13064             Diag(PossibleZeroParamPrototype->getLocation(),
13065                  diag::note_declaration_not_a_prototype)
13066                 << PossibleZeroParamPrototype
13067                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13068         }
13069       }
13070 
13071       // GNU warning -Wstrict-prototypes
13072       //   Warn if K&R function is defined without a previous declaration.
13073       //   This warning is issued only if the definition itself does not provide
13074       //   a prototype. Only K&R definitions do not provide a prototype.
13075       //   An empty list in a function declarator that is part of a definition
13076       //   of that function specifies that the function has no parameters
13077       //   (C99 6.7.5.3p14)
13078       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13079           !LangOpts.CPlusPlus) {
13080         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13081         TypeLoc TL = TI->getTypeLoc();
13082         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13083         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13084       }
13085     }
13086 
13087     // Warn on CPUDispatch with an actual body.
13088     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13089       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13090         if (!CmpndBody->body_empty())
13091           Diag(CmpndBody->body_front()->getBeginLoc(),
13092                diag::warn_dispatch_body_ignored);
13093 
13094     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13095       const CXXMethodDecl *KeyFunction;
13096       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13097           MD->isVirtual() &&
13098           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13099           MD == KeyFunction->getCanonicalDecl()) {
13100         // Update the key-function state if necessary for this ABI.
13101         if (FD->isInlined() &&
13102             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13103           Context.setNonKeyFunction(MD);
13104 
13105           // If the newly-chosen key function is already defined, then we
13106           // need to mark the vtable as used retroactively.
13107           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13108           const FunctionDecl *Definition;
13109           if (KeyFunction && KeyFunction->isDefined(Definition))
13110             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13111         } else {
13112           // We just defined they key function; mark the vtable as used.
13113           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13114         }
13115       }
13116     }
13117 
13118     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13119            "Function parsing confused");
13120   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13121     assert(MD == getCurMethodDecl() && "Method parsing confused");
13122     MD->setBody(Body);
13123     if (!MD->isInvalidDecl()) {
13124       DiagnoseUnusedParameters(MD->parameters());
13125       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13126                                              MD->getReturnType(), MD);
13127 
13128       if (Body)
13129         computeNRVO(Body, getCurFunction());
13130     }
13131     if (getCurFunction()->ObjCShouldCallSuper) {
13132       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13133           << MD->getSelector().getAsString();
13134       getCurFunction()->ObjCShouldCallSuper = false;
13135     }
13136     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13137       const ObjCMethodDecl *InitMethod = nullptr;
13138       bool isDesignated =
13139           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13140       assert(isDesignated && InitMethod);
13141       (void)isDesignated;
13142 
13143       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13144         auto IFace = MD->getClassInterface();
13145         if (!IFace)
13146           return false;
13147         auto SuperD = IFace->getSuperClass();
13148         if (!SuperD)
13149           return false;
13150         return SuperD->getIdentifier() ==
13151             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13152       };
13153       // Don't issue this warning for unavailable inits or direct subclasses
13154       // of NSObject.
13155       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13156         Diag(MD->getLocation(),
13157              diag::warn_objc_designated_init_missing_super_call);
13158         Diag(InitMethod->getLocation(),
13159              diag::note_objc_designated_init_marked_here);
13160       }
13161       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13162     }
13163     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13164       // Don't issue this warning for unavaialable inits.
13165       if (!MD->isUnavailable())
13166         Diag(MD->getLocation(),
13167              diag::warn_objc_secondary_init_missing_init_call);
13168       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13169     }
13170   } else {
13171     // Parsing the function declaration failed in some way. Pop the fake scope
13172     // we pushed on.
13173     PopFunctionScopeInfo(ActivePolicy, dcl);
13174     return nullptr;
13175   }
13176 
13177   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13178     DiagnoseUnguardedAvailabilityViolations(dcl);
13179 
13180   assert(!getCurFunction()->ObjCShouldCallSuper &&
13181          "This should only be set for ObjC methods, which should have been "
13182          "handled in the block above.");
13183 
13184   // Verify and clean out per-function state.
13185   if (Body && (!FD || !FD->isDefaulted())) {
13186     // C++ constructors that have function-try-blocks can't have return
13187     // statements in the handlers of that block. (C++ [except.handle]p14)
13188     // Verify this.
13189     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13190       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13191 
13192     // Verify that gotos and switch cases don't jump into scopes illegally.
13193     if (getCurFunction()->NeedsScopeChecking() &&
13194         !PP.isCodeCompletionEnabled())
13195       DiagnoseInvalidJumps(Body);
13196 
13197     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13198       if (!Destructor->getParent()->isDependentType())
13199         CheckDestructor(Destructor);
13200 
13201       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13202                                              Destructor->getParent());
13203     }
13204 
13205     // If any errors have occurred, clear out any temporaries that may have
13206     // been leftover. This ensures that these temporaries won't be picked up for
13207     // deletion in some later function.
13208     if (getDiagnostics().hasErrorOccurred() ||
13209         getDiagnostics().getSuppressAllDiagnostics()) {
13210       DiscardCleanupsInEvaluationContext();
13211     }
13212     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13213         !isa<FunctionTemplateDecl>(dcl)) {
13214       // Since the body is valid, issue any analysis-based warnings that are
13215       // enabled.
13216       ActivePolicy = &WP;
13217     }
13218 
13219     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13220         (!CheckConstexprFunctionDecl(FD) ||
13221          !CheckConstexprFunctionBody(FD, Body)))
13222       FD->setInvalidDecl();
13223 
13224     if (FD && FD->hasAttr<NakedAttr>()) {
13225       for (const Stmt *S : Body->children()) {
13226         // Allow local register variables without initializer as they don't
13227         // require prologue.
13228         bool RegisterVariables = false;
13229         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13230           for (const auto *Decl : DS->decls()) {
13231             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13232               RegisterVariables =
13233                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13234               if (!RegisterVariables)
13235                 break;
13236             }
13237           }
13238         }
13239         if (RegisterVariables)
13240           continue;
13241         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13242           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13243           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13244           FD->setInvalidDecl();
13245           break;
13246         }
13247       }
13248     }
13249 
13250     assert(ExprCleanupObjects.size() ==
13251                ExprEvalContexts.back().NumCleanupObjects &&
13252            "Leftover temporaries in function");
13253     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13254     assert(MaybeODRUseExprs.empty() &&
13255            "Leftover expressions for odr-use checking");
13256   }
13257 
13258   if (!IsInstantiation)
13259     PopDeclContext();
13260 
13261   PopFunctionScopeInfo(ActivePolicy, dcl);
13262   // If any errors have occurred, clear out any temporaries that may have
13263   // been leftover. This ensures that these temporaries won't be picked up for
13264   // deletion in some later function.
13265   if (getDiagnostics().hasErrorOccurred()) {
13266     DiscardCleanupsInEvaluationContext();
13267   }
13268 
13269   return dcl;
13270 }
13271 
13272 /// When we finish delayed parsing of an attribute, we must attach it to the
13273 /// relevant Decl.
13274 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13275                                        ParsedAttributes &Attrs) {
13276   // Always attach attributes to the underlying decl.
13277   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13278     D = TD->getTemplatedDecl();
13279   ProcessDeclAttributeList(S, D, Attrs);
13280 
13281   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13282     if (Method->isStatic())
13283       checkThisInStaticMemberFunctionAttributes(Method);
13284 }
13285 
13286 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13287 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13288 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13289                                           IdentifierInfo &II, Scope *S) {
13290   // Find the scope in which the identifier is injected and the corresponding
13291   // DeclContext.
13292   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13293   // In that case, we inject the declaration into the translation unit scope
13294   // instead.
13295   Scope *BlockScope = S;
13296   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13297     BlockScope = BlockScope->getParent();
13298 
13299   Scope *ContextScope = BlockScope;
13300   while (!ContextScope->getEntity())
13301     ContextScope = ContextScope->getParent();
13302   ContextRAII SavedContext(*this, ContextScope->getEntity());
13303 
13304   // Before we produce a declaration for an implicitly defined
13305   // function, see whether there was a locally-scoped declaration of
13306   // this name as a function or variable. If so, use that
13307   // (non-visible) declaration, and complain about it.
13308   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13309   if (ExternCPrev) {
13310     // We still need to inject the function into the enclosing block scope so
13311     // that later (non-call) uses can see it.
13312     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13313 
13314     // C89 footnote 38:
13315     //   If in fact it is not defined as having type "function returning int",
13316     //   the behavior is undefined.
13317     if (!isa<FunctionDecl>(ExternCPrev) ||
13318         !Context.typesAreCompatible(
13319             cast<FunctionDecl>(ExternCPrev)->getType(),
13320             Context.getFunctionNoProtoType(Context.IntTy))) {
13321       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13322           << ExternCPrev << !getLangOpts().C99;
13323       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13324       return ExternCPrev;
13325     }
13326   }
13327 
13328   // Extension in C99.  Legal in C90, but warn about it.
13329   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13330   unsigned diag_id;
13331   if (II.getName().startswith("__builtin_"))
13332     diag_id = diag::warn_builtin_unknown;
13333   else if (getLangOpts().C99 || getLangOpts().OpenCL)
13334     diag_id = diag::ext_implicit_function_decl;
13335   else
13336     diag_id = diag::warn_implicit_function_decl;
13337   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
13338 
13339   // If we found a prior declaration of this function, don't bother building
13340   // another one. We've already pushed that one into scope, so there's nothing
13341   // more to do.
13342   if (ExternCPrev)
13343     return ExternCPrev;
13344 
13345   // Because typo correction is expensive, only do it if the implicit
13346   // function declaration is going to be treated as an error.
13347   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13348     TypoCorrection Corrected;
13349     if (S &&
13350         (Corrected = CorrectTypo(
13351              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13352              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13353       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13354                    /*ErrorRecovery*/false);
13355   }
13356 
13357   // Set a Declarator for the implicit definition: int foo();
13358   const char *Dummy;
13359   AttributeFactory attrFactory;
13360   DeclSpec DS(attrFactory);
13361   unsigned DiagID;
13362   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13363                                   Context.getPrintingPolicy());
13364   (void)Error; // Silence warning.
13365   assert(!Error && "Error setting up implicit decl!");
13366   SourceLocation NoLoc;
13367   Declarator D(DS, DeclaratorContext::BlockContext);
13368   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13369                                              /*IsAmbiguous=*/false,
13370                                              /*LParenLoc=*/NoLoc,
13371                                              /*Params=*/nullptr,
13372                                              /*NumParams=*/0,
13373                                              /*EllipsisLoc=*/NoLoc,
13374                                              /*RParenLoc=*/NoLoc,
13375                                              /*TypeQuals=*/0,
13376                                              /*RefQualifierIsLvalueRef=*/true,
13377                                              /*RefQualifierLoc=*/NoLoc,
13378                                              /*ConstQualifierLoc=*/NoLoc,
13379                                              /*VolatileQualifierLoc=*/NoLoc,
13380                                              /*RestrictQualifierLoc=*/NoLoc,
13381                                              /*MutableLoc=*/NoLoc, EST_None,
13382                                              /*ESpecRange=*/SourceRange(),
13383                                              /*Exceptions=*/nullptr,
13384                                              /*ExceptionRanges=*/nullptr,
13385                                              /*NumExceptions=*/0,
13386                                              /*NoexceptExpr=*/nullptr,
13387                                              /*ExceptionSpecTokens=*/nullptr,
13388                                              /*DeclsInPrototype=*/None, Loc,
13389                                              Loc, D),
13390                 std::move(DS.getAttributes()), SourceLocation());
13391   D.SetIdentifier(&II, Loc);
13392 
13393   // Insert this function into the enclosing block scope.
13394   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13395   FD->setImplicit();
13396 
13397   AddKnownFunctionAttributes(FD);
13398 
13399   return FD;
13400 }
13401 
13402 /// Adds any function attributes that we know a priori based on
13403 /// the declaration of this function.
13404 ///
13405 /// These attributes can apply both to implicitly-declared builtins
13406 /// (like __builtin___printf_chk) or to library-declared functions
13407 /// like NSLog or printf.
13408 ///
13409 /// We need to check for duplicate attributes both here and where user-written
13410 /// attributes are applied to declarations.
13411 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13412   if (FD->isInvalidDecl())
13413     return;
13414 
13415   // If this is a built-in function, map its builtin attributes to
13416   // actual attributes.
13417   if (unsigned BuiltinID = FD->getBuiltinID()) {
13418     // Handle printf-formatting attributes.
13419     unsigned FormatIdx;
13420     bool HasVAListArg;
13421     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13422       if (!FD->hasAttr<FormatAttr>()) {
13423         const char *fmt = "printf";
13424         unsigned int NumParams = FD->getNumParams();
13425         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13426             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13427           fmt = "NSString";
13428         FD->addAttr(FormatAttr::CreateImplicit(Context,
13429                                                &Context.Idents.get(fmt),
13430                                                FormatIdx+1,
13431                                                HasVAListArg ? 0 : FormatIdx+2,
13432                                                FD->getLocation()));
13433       }
13434     }
13435     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13436                                              HasVAListArg)) {
13437      if (!FD->hasAttr<FormatAttr>())
13438        FD->addAttr(FormatAttr::CreateImplicit(Context,
13439                                               &Context.Idents.get("scanf"),
13440                                               FormatIdx+1,
13441                                               HasVAListArg ? 0 : FormatIdx+2,
13442                                               FD->getLocation()));
13443     }
13444 
13445     // Mark const if we don't care about errno and that is the only thing
13446     // preventing the function from being const. This allows IRgen to use LLVM
13447     // intrinsics for such functions.
13448     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13449         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13450       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13451 
13452     // We make "fma" on some platforms const because we know it does not set
13453     // errno in those environments even though it could set errno based on the
13454     // C standard.
13455     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13456     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13457         !FD->hasAttr<ConstAttr>()) {
13458       switch (BuiltinID) {
13459       case Builtin::BI__builtin_fma:
13460       case Builtin::BI__builtin_fmaf:
13461       case Builtin::BI__builtin_fmal:
13462       case Builtin::BIfma:
13463       case Builtin::BIfmaf:
13464       case Builtin::BIfmal:
13465         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13466         break;
13467       default:
13468         break;
13469       }
13470     }
13471 
13472     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13473         !FD->hasAttr<ReturnsTwiceAttr>())
13474       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13475                                          FD->getLocation()));
13476     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13477       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13478     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13479       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13480     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13481       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13482     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13483         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13484       // Add the appropriate attribute, depending on the CUDA compilation mode
13485       // and which target the builtin belongs to. For example, during host
13486       // compilation, aux builtins are __device__, while the rest are __host__.
13487       if (getLangOpts().CUDAIsDevice !=
13488           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13489         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13490       else
13491         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13492     }
13493   }
13494 
13495   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13496   // throw, add an implicit nothrow attribute to any extern "C" function we come
13497   // across.
13498   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13499       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13500     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13501     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13502       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13503   }
13504 
13505   IdentifierInfo *Name = FD->getIdentifier();
13506   if (!Name)
13507     return;
13508   if ((!getLangOpts().CPlusPlus &&
13509        FD->getDeclContext()->isTranslationUnit()) ||
13510       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13511        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13512        LinkageSpecDecl::lang_c)) {
13513     // Okay: this could be a libc/libm/Objective-C function we know
13514     // about.
13515   } else
13516     return;
13517 
13518   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13519     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13520     // target-specific builtins, perhaps?
13521     if (!FD->hasAttr<FormatAttr>())
13522       FD->addAttr(FormatAttr::CreateImplicit(Context,
13523                                              &Context.Idents.get("printf"), 2,
13524                                              Name->isStr("vasprintf") ? 0 : 3,
13525                                              FD->getLocation()));
13526   }
13527 
13528   if (Name->isStr("__CFStringMakeConstantString")) {
13529     // We already have a __builtin___CFStringMakeConstantString,
13530     // but builds that use -fno-constant-cfstrings don't go through that.
13531     if (!FD->hasAttr<FormatArgAttr>())
13532       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13533                                                 FD->getLocation()));
13534   }
13535 }
13536 
13537 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13538                                     TypeSourceInfo *TInfo) {
13539   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13540   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13541 
13542   if (!TInfo) {
13543     assert(D.isInvalidType() && "no declarator info for valid type");
13544     TInfo = Context.getTrivialTypeSourceInfo(T);
13545   }
13546 
13547   // Scope manipulation handled by caller.
13548   TypedefDecl *NewTD =
13549       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13550                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13551 
13552   // Bail out immediately if we have an invalid declaration.
13553   if (D.isInvalidType()) {
13554     NewTD->setInvalidDecl();
13555     return NewTD;
13556   }
13557 
13558   if (D.getDeclSpec().isModulePrivateSpecified()) {
13559     if (CurContext->isFunctionOrMethod())
13560       Diag(NewTD->getLocation(), diag::err_module_private_local)
13561         << 2 << NewTD->getDeclName()
13562         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13563         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13564     else
13565       NewTD->setModulePrivate();
13566   }
13567 
13568   // C++ [dcl.typedef]p8:
13569   //   If the typedef declaration defines an unnamed class (or
13570   //   enum), the first typedef-name declared by the declaration
13571   //   to be that class type (or enum type) is used to denote the
13572   //   class type (or enum type) for linkage purposes only.
13573   // We need to check whether the type was declared in the declaration.
13574   switch (D.getDeclSpec().getTypeSpecType()) {
13575   case TST_enum:
13576   case TST_struct:
13577   case TST_interface:
13578   case TST_union:
13579   case TST_class: {
13580     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13581     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13582     break;
13583   }
13584 
13585   default:
13586     break;
13587   }
13588 
13589   return NewTD;
13590 }
13591 
13592 /// Check that this is a valid underlying type for an enum declaration.
13593 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13594   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13595   QualType T = TI->getType();
13596 
13597   if (T->isDependentType())
13598     return false;
13599 
13600   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13601     if (BT->isInteger())
13602       return false;
13603 
13604   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13605   return true;
13606 }
13607 
13608 /// Check whether this is a valid redeclaration of a previous enumeration.
13609 /// \return true if the redeclaration was invalid.
13610 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13611                                   QualType EnumUnderlyingTy, bool IsFixed,
13612                                   const EnumDecl *Prev) {
13613   if (IsScoped != Prev->isScoped()) {
13614     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13615       << Prev->isScoped();
13616     Diag(Prev->getLocation(), diag::note_previous_declaration);
13617     return true;
13618   }
13619 
13620   if (IsFixed && Prev->isFixed()) {
13621     if (!EnumUnderlyingTy->isDependentType() &&
13622         !Prev->getIntegerType()->isDependentType() &&
13623         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13624                                         Prev->getIntegerType())) {
13625       // TODO: Highlight the underlying type of the redeclaration.
13626       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13627         << EnumUnderlyingTy << Prev->getIntegerType();
13628       Diag(Prev->getLocation(), diag::note_previous_declaration)
13629           << Prev->getIntegerTypeRange();
13630       return true;
13631     }
13632   } else if (IsFixed != Prev->isFixed()) {
13633     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13634       << Prev->isFixed();
13635     Diag(Prev->getLocation(), diag::note_previous_declaration);
13636     return true;
13637   }
13638 
13639   return false;
13640 }
13641 
13642 /// Get diagnostic %select index for tag kind for
13643 /// redeclaration diagnostic message.
13644 /// WARNING: Indexes apply to particular diagnostics only!
13645 ///
13646 /// \returns diagnostic %select index.
13647 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13648   switch (Tag) {
13649   case TTK_Struct: return 0;
13650   case TTK_Interface: return 1;
13651   case TTK_Class:  return 2;
13652   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13653   }
13654 }
13655 
13656 /// Determine if tag kind is a class-key compatible with
13657 /// class for redeclaration (class, struct, or __interface).
13658 ///
13659 /// \returns true iff the tag kind is compatible.
13660 static bool isClassCompatTagKind(TagTypeKind Tag)
13661 {
13662   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13663 }
13664 
13665 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13666                                              TagTypeKind TTK) {
13667   if (isa<TypedefDecl>(PrevDecl))
13668     return NTK_Typedef;
13669   else if (isa<TypeAliasDecl>(PrevDecl))
13670     return NTK_TypeAlias;
13671   else if (isa<ClassTemplateDecl>(PrevDecl))
13672     return NTK_Template;
13673   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13674     return NTK_TypeAliasTemplate;
13675   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13676     return NTK_TemplateTemplateArgument;
13677   switch (TTK) {
13678   case TTK_Struct:
13679   case TTK_Interface:
13680   case TTK_Class:
13681     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13682   case TTK_Union:
13683     return NTK_NonUnion;
13684   case TTK_Enum:
13685     return NTK_NonEnum;
13686   }
13687   llvm_unreachable("invalid TTK");
13688 }
13689 
13690 /// Determine whether a tag with a given kind is acceptable
13691 /// as a redeclaration of the given tag declaration.
13692 ///
13693 /// \returns true if the new tag kind is acceptable, false otherwise.
13694 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13695                                         TagTypeKind NewTag, bool isDefinition,
13696                                         SourceLocation NewTagLoc,
13697                                         const IdentifierInfo *Name) {
13698   // C++ [dcl.type.elab]p3:
13699   //   The class-key or enum keyword present in the
13700   //   elaborated-type-specifier shall agree in kind with the
13701   //   declaration to which the name in the elaborated-type-specifier
13702   //   refers. This rule also applies to the form of
13703   //   elaborated-type-specifier that declares a class-name or
13704   //   friend class since it can be construed as referring to the
13705   //   definition of the class. Thus, in any
13706   //   elaborated-type-specifier, the enum keyword shall be used to
13707   //   refer to an enumeration (7.2), the union class-key shall be
13708   //   used to refer to a union (clause 9), and either the class or
13709   //   struct class-key shall be used to refer to a class (clause 9)
13710   //   declared using the class or struct class-key.
13711   TagTypeKind OldTag = Previous->getTagKind();
13712   if (!isDefinition || !isClassCompatTagKind(NewTag))
13713     if (OldTag == NewTag)
13714       return true;
13715 
13716   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13717     // Warn about the struct/class tag mismatch.
13718     bool isTemplate = false;
13719     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13720       isTemplate = Record->getDescribedClassTemplate();
13721 
13722     if (inTemplateInstantiation()) {
13723       // In a template instantiation, do not offer fix-its for tag mismatches
13724       // since they usually mess up the template instead of fixing the problem.
13725       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13726         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13727         << getRedeclDiagFromTagKind(OldTag);
13728       return true;
13729     }
13730 
13731     if (isDefinition) {
13732       // On definitions, check previous tags and issue a fix-it for each
13733       // one that doesn't match the current tag.
13734       if (Previous->getDefinition()) {
13735         // Don't suggest fix-its for redefinitions.
13736         return true;
13737       }
13738 
13739       bool previousMismatch = false;
13740       for (auto I : Previous->redecls()) {
13741         if (I->getTagKind() != NewTag) {
13742           if (!previousMismatch) {
13743             previousMismatch = true;
13744             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13745               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13746               << getRedeclDiagFromTagKind(I->getTagKind());
13747           }
13748           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13749             << getRedeclDiagFromTagKind(NewTag)
13750             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13751                  TypeWithKeyword::getTagTypeKindName(NewTag));
13752         }
13753       }
13754       return true;
13755     }
13756 
13757     // Check for a previous definition.  If current tag and definition
13758     // are same type, do nothing.  If no definition, but disagree with
13759     // with previous tag type, give a warning, but no fix-it.
13760     const TagDecl *Redecl = Previous->getDefinition() ?
13761                             Previous->getDefinition() : Previous;
13762     if (Redecl->getTagKind() == NewTag) {
13763       return true;
13764     }
13765 
13766     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13767       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13768       << getRedeclDiagFromTagKind(OldTag);
13769     Diag(Redecl->getLocation(), diag::note_previous_use);
13770 
13771     // If there is a previous definition, suggest a fix-it.
13772     if (Previous->getDefinition()) {
13773         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13774           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13775           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13776                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13777     }
13778 
13779     return true;
13780   }
13781   return false;
13782 }
13783 
13784 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13785 /// from an outer enclosing namespace or file scope inside a friend declaration.
13786 /// This should provide the commented out code in the following snippet:
13787 ///   namespace N {
13788 ///     struct X;
13789 ///     namespace M {
13790 ///       struct Y { friend struct /*N::*/ X; };
13791 ///     }
13792 ///   }
13793 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13794                                          SourceLocation NameLoc) {
13795   // While the decl is in a namespace, do repeated lookup of that name and see
13796   // if we get the same namespace back.  If we do not, continue until
13797   // translation unit scope, at which point we have a fully qualified NNS.
13798   SmallVector<IdentifierInfo *, 4> Namespaces;
13799   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13800   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13801     // This tag should be declared in a namespace, which can only be enclosed by
13802     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13803     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13804     if (!Namespace || Namespace->isAnonymousNamespace())
13805       return FixItHint();
13806     IdentifierInfo *II = Namespace->getIdentifier();
13807     Namespaces.push_back(II);
13808     NamedDecl *Lookup = SemaRef.LookupSingleName(
13809         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13810     if (Lookup == Namespace)
13811       break;
13812   }
13813 
13814   // Once we have all the namespaces, reverse them to go outermost first, and
13815   // build an NNS.
13816   SmallString<64> Insertion;
13817   llvm::raw_svector_ostream OS(Insertion);
13818   if (DC->isTranslationUnit())
13819     OS << "::";
13820   std::reverse(Namespaces.begin(), Namespaces.end());
13821   for (auto *II : Namespaces)
13822     OS << II->getName() << "::";
13823   return FixItHint::CreateInsertion(NameLoc, Insertion);
13824 }
13825 
13826 /// Determine whether a tag originally declared in context \p OldDC can
13827 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13828 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13829 /// using-declaration).
13830 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13831                                          DeclContext *NewDC) {
13832   OldDC = OldDC->getRedeclContext();
13833   NewDC = NewDC->getRedeclContext();
13834 
13835   if (OldDC->Equals(NewDC))
13836     return true;
13837 
13838   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13839   // encloses the other).
13840   if (S.getLangOpts().MSVCCompat &&
13841       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13842     return true;
13843 
13844   return false;
13845 }
13846 
13847 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
13848 /// former case, Name will be non-null.  In the later case, Name will be null.
13849 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13850 /// reference/declaration/definition of a tag.
13851 ///
13852 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13853 /// trailing-type-specifier) other than one in an alias-declaration.
13854 ///
13855 /// \param SkipBody If non-null, will be set to indicate if the caller should
13856 /// skip the definition of this tag and treat it as if it were a declaration.
13857 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13858                      SourceLocation KWLoc, CXXScopeSpec &SS,
13859                      IdentifierInfo *Name, SourceLocation NameLoc,
13860                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
13861                      SourceLocation ModulePrivateLoc,
13862                      MultiTemplateParamsArg TemplateParameterLists,
13863                      bool &OwnedDecl, bool &IsDependent,
13864                      SourceLocation ScopedEnumKWLoc,
13865                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
13866                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13867                      SkipBodyInfo *SkipBody) {
13868   // If this is not a definition, it must have a name.
13869   IdentifierInfo *OrigName = Name;
13870   assert((Name != nullptr || TUK == TUK_Definition) &&
13871          "Nameless record must be a definition!");
13872   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13873 
13874   OwnedDecl = false;
13875   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13876   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13877 
13878   // FIXME: Check member specializations more carefully.
13879   bool isMemberSpecialization = false;
13880   bool Invalid = false;
13881 
13882   // We only need to do this matching if we have template parameters
13883   // or a scope specifier, which also conveniently avoids this work
13884   // for non-C++ cases.
13885   if (TemplateParameterLists.size() > 0 ||
13886       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13887     if (TemplateParameterList *TemplateParams =
13888             MatchTemplateParametersToScopeSpecifier(
13889                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13890                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13891       if (Kind == TTK_Enum) {
13892         Diag(KWLoc, diag::err_enum_template);
13893         return nullptr;
13894       }
13895 
13896       if (TemplateParams->size() > 0) {
13897         // This is a declaration or definition of a class template (which may
13898         // be a member of another template).
13899 
13900         if (Invalid)
13901           return nullptr;
13902 
13903         OwnedDecl = false;
13904         DeclResult Result = CheckClassTemplate(
13905             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
13906             AS, ModulePrivateLoc,
13907             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
13908             TemplateParameterLists.data(), SkipBody);
13909         return Result.get();
13910       } else {
13911         // The "template<>" header is extraneous.
13912         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13913           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13914         isMemberSpecialization = true;
13915       }
13916     }
13917   }
13918 
13919   // Figure out the underlying type if this a enum declaration. We need to do
13920   // this early, because it's needed to detect if this is an incompatible
13921   // redeclaration.
13922   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13923   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13924 
13925   if (Kind == TTK_Enum) {
13926     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13927       // No underlying type explicitly specified, or we failed to parse the
13928       // type, default to int.
13929       EnumUnderlying = Context.IntTy.getTypePtr();
13930     } else if (UnderlyingType.get()) {
13931       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13932       // integral type; any cv-qualification is ignored.
13933       TypeSourceInfo *TI = nullptr;
13934       GetTypeFromParser(UnderlyingType.get(), &TI);
13935       EnumUnderlying = TI;
13936 
13937       if (CheckEnumUnderlyingType(TI))
13938         // Recover by falling back to int.
13939         EnumUnderlying = Context.IntTy.getTypePtr();
13940 
13941       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13942                                           UPPC_FixedUnderlyingType))
13943         EnumUnderlying = Context.IntTy.getTypePtr();
13944 
13945     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13946       // For MSVC ABI compatibility, unfixed enums must use an underlying type
13947       // of 'int'. However, if this is an unfixed forward declaration, don't set
13948       // the underlying type unless the user enables -fms-compatibility. This
13949       // makes unfixed forward declared enums incomplete and is more conforming.
13950       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13951         EnumUnderlying = Context.IntTy.getTypePtr();
13952     }
13953   }
13954 
13955   DeclContext *SearchDC = CurContext;
13956   DeclContext *DC = CurContext;
13957   bool isStdBadAlloc = false;
13958   bool isStdAlignValT = false;
13959 
13960   RedeclarationKind Redecl = forRedeclarationInCurContext();
13961   if (TUK == TUK_Friend || TUK == TUK_Reference)
13962     Redecl = NotForRedeclaration;
13963 
13964   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13965   /// implemented asks for structural equivalence checking, the returned decl
13966   /// here is passed back to the parser, allowing the tag body to be parsed.
13967   auto createTagFromNewDecl = [&]() -> TagDecl * {
13968     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13969     // If there is an identifier, use the location of the identifier as the
13970     // location of the decl, otherwise use the location of the struct/union
13971     // keyword.
13972     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13973     TagDecl *New = nullptr;
13974 
13975     if (Kind == TTK_Enum) {
13976       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13977                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
13978       // If this is an undefined enum, bail.
13979       if (TUK != TUK_Definition && !Invalid)
13980         return nullptr;
13981       if (EnumUnderlying) {
13982         EnumDecl *ED = cast<EnumDecl>(New);
13983         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13984           ED->setIntegerTypeSourceInfo(TI);
13985         else
13986           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13987         ED->setPromotionType(ED->getIntegerType());
13988       }
13989     } else { // struct/union
13990       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13991                                nullptr);
13992     }
13993 
13994     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13995       // Add alignment attributes if necessary; these attributes are checked
13996       // when the ASTContext lays out the structure.
13997       //
13998       // It is important for implementing the correct semantics that this
13999       // happen here (in ActOnTag). The #pragma pack stack is
14000       // maintained as a result of parser callbacks which can occur at
14001       // many points during the parsing of a struct declaration (because
14002       // the #pragma tokens are effectively skipped over during the
14003       // parsing of the struct).
14004       if (TUK == TUK_Definition) {
14005         AddAlignmentAttributesForRecord(RD);
14006         AddMsStructLayoutForRecord(RD);
14007       }
14008     }
14009     New->setLexicalDeclContext(CurContext);
14010     return New;
14011   };
14012 
14013   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14014   if (Name && SS.isNotEmpty()) {
14015     // We have a nested-name tag ('struct foo::bar').
14016 
14017     // Check for invalid 'foo::'.
14018     if (SS.isInvalid()) {
14019       Name = nullptr;
14020       goto CreateNewDecl;
14021     }
14022 
14023     // If this is a friend or a reference to a class in a dependent
14024     // context, don't try to make a decl for it.
14025     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14026       DC = computeDeclContext(SS, false);
14027       if (!DC) {
14028         IsDependent = true;
14029         return nullptr;
14030       }
14031     } else {
14032       DC = computeDeclContext(SS, true);
14033       if (!DC) {
14034         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14035           << SS.getRange();
14036         return nullptr;
14037       }
14038     }
14039 
14040     if (RequireCompleteDeclContext(SS, DC))
14041       return nullptr;
14042 
14043     SearchDC = DC;
14044     // Look-up name inside 'foo::'.
14045     LookupQualifiedName(Previous, DC);
14046 
14047     if (Previous.isAmbiguous())
14048       return nullptr;
14049 
14050     if (Previous.empty()) {
14051       // Name lookup did not find anything. However, if the
14052       // nested-name-specifier refers to the current instantiation,
14053       // and that current instantiation has any dependent base
14054       // classes, we might find something at instantiation time: treat
14055       // this as a dependent elaborated-type-specifier.
14056       // But this only makes any sense for reference-like lookups.
14057       if (Previous.wasNotFoundInCurrentInstantiation() &&
14058           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14059         IsDependent = true;
14060         return nullptr;
14061       }
14062 
14063       // A tag 'foo::bar' must already exist.
14064       Diag(NameLoc, diag::err_not_tag_in_scope)
14065         << Kind << Name << DC << SS.getRange();
14066       Name = nullptr;
14067       Invalid = true;
14068       goto CreateNewDecl;
14069     }
14070   } else if (Name) {
14071     // C++14 [class.mem]p14:
14072     //   If T is the name of a class, then each of the following shall have a
14073     //   name different from T:
14074     //    -- every member of class T that is itself a type
14075     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14076         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14077       return nullptr;
14078 
14079     // If this is a named struct, check to see if there was a previous forward
14080     // declaration or definition.
14081     // FIXME: We're looking into outer scopes here, even when we
14082     // shouldn't be. Doing so can result in ambiguities that we
14083     // shouldn't be diagnosing.
14084     LookupName(Previous, S);
14085 
14086     // When declaring or defining a tag, ignore ambiguities introduced
14087     // by types using'ed into this scope.
14088     if (Previous.isAmbiguous() &&
14089         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14090       LookupResult::Filter F = Previous.makeFilter();
14091       while (F.hasNext()) {
14092         NamedDecl *ND = F.next();
14093         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14094                 SearchDC->getRedeclContext()))
14095           F.erase();
14096       }
14097       F.done();
14098     }
14099 
14100     // C++11 [namespace.memdef]p3:
14101     //   If the name in a friend declaration is neither qualified nor
14102     //   a template-id and the declaration is a function or an
14103     //   elaborated-type-specifier, the lookup to determine whether
14104     //   the entity has been previously declared shall not consider
14105     //   any scopes outside the innermost enclosing namespace.
14106     //
14107     // MSVC doesn't implement the above rule for types, so a friend tag
14108     // declaration may be a redeclaration of a type declared in an enclosing
14109     // scope.  They do implement this rule for friend functions.
14110     //
14111     // Does it matter that this should be by scope instead of by
14112     // semantic context?
14113     if (!Previous.empty() && TUK == TUK_Friend) {
14114       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14115       LookupResult::Filter F = Previous.makeFilter();
14116       bool FriendSawTagOutsideEnclosingNamespace = false;
14117       while (F.hasNext()) {
14118         NamedDecl *ND = F.next();
14119         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14120         if (DC->isFileContext() &&
14121             !EnclosingNS->Encloses(ND->getDeclContext())) {
14122           if (getLangOpts().MSVCCompat)
14123             FriendSawTagOutsideEnclosingNamespace = true;
14124           else
14125             F.erase();
14126         }
14127       }
14128       F.done();
14129 
14130       // Diagnose this MSVC extension in the easy case where lookup would have
14131       // unambiguously found something outside the enclosing namespace.
14132       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14133         NamedDecl *ND = Previous.getFoundDecl();
14134         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14135             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14136       }
14137     }
14138 
14139     // Note:  there used to be some attempt at recovery here.
14140     if (Previous.isAmbiguous())
14141       return nullptr;
14142 
14143     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14144       // FIXME: This makes sure that we ignore the contexts associated
14145       // with C structs, unions, and enums when looking for a matching
14146       // tag declaration or definition. See the similar lookup tweak
14147       // in Sema::LookupName; is there a better way to deal with this?
14148       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14149         SearchDC = SearchDC->getParent();
14150     }
14151   }
14152 
14153   if (Previous.isSingleResult() &&
14154       Previous.getFoundDecl()->isTemplateParameter()) {
14155     // Maybe we will complain about the shadowed template parameter.
14156     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14157     // Just pretend that we didn't see the previous declaration.
14158     Previous.clear();
14159   }
14160 
14161   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14162       DC->Equals(getStdNamespace())) {
14163     if (Name->isStr("bad_alloc")) {
14164       // This is a declaration of or a reference to "std::bad_alloc".
14165       isStdBadAlloc = true;
14166 
14167       // If std::bad_alloc has been implicitly declared (but made invisible to
14168       // name lookup), fill in this implicit declaration as the previous
14169       // declaration, so that the declarations get chained appropriately.
14170       if (Previous.empty() && StdBadAlloc)
14171         Previous.addDecl(getStdBadAlloc());
14172     } else if (Name->isStr("align_val_t")) {
14173       isStdAlignValT = true;
14174       if (Previous.empty() && StdAlignValT)
14175         Previous.addDecl(getStdAlignValT());
14176     }
14177   }
14178 
14179   // If we didn't find a previous declaration, and this is a reference
14180   // (or friend reference), move to the correct scope.  In C++, we
14181   // also need to do a redeclaration lookup there, just in case
14182   // there's a shadow friend decl.
14183   if (Name && Previous.empty() &&
14184       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14185     if (Invalid) goto CreateNewDecl;
14186     assert(SS.isEmpty());
14187 
14188     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14189       // C++ [basic.scope.pdecl]p5:
14190       //   -- for an elaborated-type-specifier of the form
14191       //
14192       //          class-key identifier
14193       //
14194       //      if the elaborated-type-specifier is used in the
14195       //      decl-specifier-seq or parameter-declaration-clause of a
14196       //      function defined in namespace scope, the identifier is
14197       //      declared as a class-name in the namespace that contains
14198       //      the declaration; otherwise, except as a friend
14199       //      declaration, the identifier is declared in the smallest
14200       //      non-class, non-function-prototype scope that contains the
14201       //      declaration.
14202       //
14203       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14204       // C structs and unions.
14205       //
14206       // It is an error in C++ to declare (rather than define) an enum
14207       // type, including via an elaborated type specifier.  We'll
14208       // diagnose that later; for now, declare the enum in the same
14209       // scope as we would have picked for any other tag type.
14210       //
14211       // GNU C also supports this behavior as part of its incomplete
14212       // enum types extension, while GNU C++ does not.
14213       //
14214       // Find the context where we'll be declaring the tag.
14215       // FIXME: We would like to maintain the current DeclContext as the
14216       // lexical context,
14217       SearchDC = getTagInjectionContext(SearchDC);
14218 
14219       // Find the scope where we'll be declaring the tag.
14220       S = getTagInjectionScope(S, getLangOpts());
14221     } else {
14222       assert(TUK == TUK_Friend);
14223       // C++ [namespace.memdef]p3:
14224       //   If a friend declaration in a non-local class first declares a
14225       //   class or function, the friend class or function is a member of
14226       //   the innermost enclosing namespace.
14227       SearchDC = SearchDC->getEnclosingNamespaceContext();
14228     }
14229 
14230     // In C++, we need to do a redeclaration lookup to properly
14231     // diagnose some problems.
14232     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14233     // hidden declaration so that we don't get ambiguity errors when using a
14234     // type declared by an elaborated-type-specifier.  In C that is not correct
14235     // and we should instead merge compatible types found by lookup.
14236     if (getLangOpts().CPlusPlus) {
14237       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14238       LookupQualifiedName(Previous, SearchDC);
14239     } else {
14240       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14241       LookupName(Previous, S);
14242     }
14243   }
14244 
14245   // If we have a known previous declaration to use, then use it.
14246   if (Previous.empty() && SkipBody && SkipBody->Previous)
14247     Previous.addDecl(SkipBody->Previous);
14248 
14249   if (!Previous.empty()) {
14250     NamedDecl *PrevDecl = Previous.getFoundDecl();
14251     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14252 
14253     // It's okay to have a tag decl in the same scope as a typedef
14254     // which hides a tag decl in the same scope.  Finding this
14255     // insanity with a redeclaration lookup can only actually happen
14256     // in C++.
14257     //
14258     // This is also okay for elaborated-type-specifiers, which is
14259     // technically forbidden by the current standard but which is
14260     // okay according to the likely resolution of an open issue;
14261     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14262     if (getLangOpts().CPlusPlus) {
14263       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14264         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14265           TagDecl *Tag = TT->getDecl();
14266           if (Tag->getDeclName() == Name &&
14267               Tag->getDeclContext()->getRedeclContext()
14268                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14269             PrevDecl = Tag;
14270             Previous.clear();
14271             Previous.addDecl(Tag);
14272             Previous.resolveKind();
14273           }
14274         }
14275       }
14276     }
14277 
14278     // If this is a redeclaration of a using shadow declaration, it must
14279     // declare a tag in the same context. In MSVC mode, we allow a
14280     // redefinition if either context is within the other.
14281     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14282       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14283       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14284           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14285           !(OldTag && isAcceptableTagRedeclContext(
14286                           *this, OldTag->getDeclContext(), SearchDC))) {
14287         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14288         Diag(Shadow->getTargetDecl()->getLocation(),
14289              diag::note_using_decl_target);
14290         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14291             << 0;
14292         // Recover by ignoring the old declaration.
14293         Previous.clear();
14294         goto CreateNewDecl;
14295       }
14296     }
14297 
14298     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14299       // If this is a use of a previous tag, or if the tag is already declared
14300       // in the same scope (so that the definition/declaration completes or
14301       // rementions the tag), reuse the decl.
14302       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14303           isDeclInScope(DirectPrevDecl, SearchDC, S,
14304                         SS.isNotEmpty() || isMemberSpecialization)) {
14305         // Make sure that this wasn't declared as an enum and now used as a
14306         // struct or something similar.
14307         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14308                                           TUK == TUK_Definition, KWLoc,
14309                                           Name)) {
14310           bool SafeToContinue
14311             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14312                Kind != TTK_Enum);
14313           if (SafeToContinue)
14314             Diag(KWLoc, diag::err_use_with_wrong_tag)
14315               << Name
14316               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14317                                               PrevTagDecl->getKindName());
14318           else
14319             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14320           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14321 
14322           if (SafeToContinue)
14323             Kind = PrevTagDecl->getTagKind();
14324           else {
14325             // Recover by making this an anonymous redefinition.
14326             Name = nullptr;
14327             Previous.clear();
14328             Invalid = true;
14329           }
14330         }
14331 
14332         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14333           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14334 
14335           // If this is an elaborated-type-specifier for a scoped enumeration,
14336           // the 'class' keyword is not necessary and not permitted.
14337           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14338             if (ScopedEnum)
14339               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14340                 << PrevEnum->isScoped()
14341                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14342             return PrevTagDecl;
14343           }
14344 
14345           QualType EnumUnderlyingTy;
14346           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14347             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14348           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14349             EnumUnderlyingTy = QualType(T, 0);
14350 
14351           // All conflicts with previous declarations are recovered by
14352           // returning the previous declaration, unless this is a definition,
14353           // in which case we want the caller to bail out.
14354           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14355                                      ScopedEnum, EnumUnderlyingTy,
14356                                      IsFixed, PrevEnum))
14357             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14358         }
14359 
14360         // C++11 [class.mem]p1:
14361         //   A member shall not be declared twice in the member-specification,
14362         //   except that a nested class or member class template can be declared
14363         //   and then later defined.
14364         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14365             S->isDeclScope(PrevDecl)) {
14366           Diag(NameLoc, diag::ext_member_redeclared);
14367           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14368         }
14369 
14370         if (!Invalid) {
14371           // If this is a use, just return the declaration we found, unless
14372           // we have attributes.
14373           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14374             if (!Attrs.empty()) {
14375               // FIXME: Diagnose these attributes. For now, we create a new
14376               // declaration to hold them.
14377             } else if (TUK == TUK_Reference &&
14378                        (PrevTagDecl->getFriendObjectKind() ==
14379                             Decl::FOK_Undeclared ||
14380                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14381                        SS.isEmpty()) {
14382               // This declaration is a reference to an existing entity, but
14383               // has different visibility from that entity: it either makes
14384               // a friend visible or it makes a type visible in a new module.
14385               // In either case, create a new declaration. We only do this if
14386               // the declaration would have meant the same thing if no prior
14387               // declaration were found, that is, if it was found in the same
14388               // scope where we would have injected a declaration.
14389               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14390                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14391                 return PrevTagDecl;
14392               // This is in the injected scope, create a new declaration in
14393               // that scope.
14394               S = getTagInjectionScope(S, getLangOpts());
14395             } else {
14396               return PrevTagDecl;
14397             }
14398           }
14399 
14400           // Diagnose attempts to redefine a tag.
14401           if (TUK == TUK_Definition) {
14402             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14403               // If we're defining a specialization and the previous definition
14404               // is from an implicit instantiation, don't emit an error
14405               // here; we'll catch this in the general case below.
14406               bool IsExplicitSpecializationAfterInstantiation = false;
14407               if (isMemberSpecialization) {
14408                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14409                   IsExplicitSpecializationAfterInstantiation =
14410                     RD->getTemplateSpecializationKind() !=
14411                     TSK_ExplicitSpecialization;
14412                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14413                   IsExplicitSpecializationAfterInstantiation =
14414                     ED->getTemplateSpecializationKind() !=
14415                     TSK_ExplicitSpecialization;
14416               }
14417 
14418               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14419               // not keep more that one definition around (merge them). However,
14420               // ensure the decl passes the structural compatibility check in
14421               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14422               NamedDecl *Hidden = nullptr;
14423               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14424                 // There is a definition of this tag, but it is not visible. We
14425                 // explicitly make use of C++'s one definition rule here, and
14426                 // assume that this definition is identical to the hidden one
14427                 // we already have. Make the existing definition visible and
14428                 // use it in place of this one.
14429                 if (!getLangOpts().CPlusPlus) {
14430                   // Postpone making the old definition visible until after we
14431                   // complete parsing the new one and do the structural
14432                   // comparison.
14433                   SkipBody->CheckSameAsPrevious = true;
14434                   SkipBody->New = createTagFromNewDecl();
14435                   SkipBody->Previous = Hidden;
14436                 } else {
14437                   SkipBody->ShouldSkip = true;
14438                   makeMergedDefinitionVisible(Hidden);
14439                 }
14440                 return Def;
14441               } else if (!IsExplicitSpecializationAfterInstantiation) {
14442                 // A redeclaration in function prototype scope in C isn't
14443                 // visible elsewhere, so merely issue a warning.
14444                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14445                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14446                 else
14447                   Diag(NameLoc, diag::err_redefinition) << Name;
14448                 notePreviousDefinition(Def,
14449                                        NameLoc.isValid() ? NameLoc : KWLoc);
14450                 // If this is a redefinition, recover by making this
14451                 // struct be anonymous, which will make any later
14452                 // references get the previous definition.
14453                 Name = nullptr;
14454                 Previous.clear();
14455                 Invalid = true;
14456               }
14457             } else {
14458               // If the type is currently being defined, complain
14459               // about a nested redefinition.
14460               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14461               if (TD->isBeingDefined()) {
14462                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14463                 Diag(PrevTagDecl->getLocation(),
14464                      diag::note_previous_definition);
14465                 Name = nullptr;
14466                 Previous.clear();
14467                 Invalid = true;
14468               }
14469             }
14470 
14471             // Okay, this is definition of a previously declared or referenced
14472             // tag. We're going to create a new Decl for it.
14473           }
14474 
14475           // Okay, we're going to make a redeclaration.  If this is some kind
14476           // of reference, make sure we build the redeclaration in the same DC
14477           // as the original, and ignore the current access specifier.
14478           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14479             SearchDC = PrevTagDecl->getDeclContext();
14480             AS = AS_none;
14481           }
14482         }
14483         // If we get here we have (another) forward declaration or we
14484         // have a definition.  Just create a new decl.
14485 
14486       } else {
14487         // If we get here, this is a definition of a new tag type in a nested
14488         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14489         // new decl/type.  We set PrevDecl to NULL so that the entities
14490         // have distinct types.
14491         Previous.clear();
14492       }
14493       // If we get here, we're going to create a new Decl. If PrevDecl
14494       // is non-NULL, it's a definition of the tag declared by
14495       // PrevDecl. If it's NULL, we have a new definition.
14496 
14497     // Otherwise, PrevDecl is not a tag, but was found with tag
14498     // lookup.  This is only actually possible in C++, where a few
14499     // things like templates still live in the tag namespace.
14500     } else {
14501       // Use a better diagnostic if an elaborated-type-specifier
14502       // found the wrong kind of type on the first
14503       // (non-redeclaration) lookup.
14504       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14505           !Previous.isForRedeclaration()) {
14506         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14507         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14508                                                        << Kind;
14509         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14510         Invalid = true;
14511 
14512       // Otherwise, only diagnose if the declaration is in scope.
14513       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14514                                 SS.isNotEmpty() || isMemberSpecialization)) {
14515         // do nothing
14516 
14517       // Diagnose implicit declarations introduced by elaborated types.
14518       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14519         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14520         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14521         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14522         Invalid = true;
14523 
14524       // Otherwise it's a declaration.  Call out a particularly common
14525       // case here.
14526       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14527         unsigned Kind = 0;
14528         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14529         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14530           << Name << Kind << TND->getUnderlyingType();
14531         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14532         Invalid = true;
14533 
14534       // Otherwise, diagnose.
14535       } else {
14536         // The tag name clashes with something else in the target scope,
14537         // issue an error and recover by making this tag be anonymous.
14538         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14539         notePreviousDefinition(PrevDecl, NameLoc);
14540         Name = nullptr;
14541         Invalid = true;
14542       }
14543 
14544       // The existing declaration isn't relevant to us; we're in a
14545       // new scope, so clear out the previous declaration.
14546       Previous.clear();
14547     }
14548   }
14549 
14550 CreateNewDecl:
14551 
14552   TagDecl *PrevDecl = nullptr;
14553   if (Previous.isSingleResult())
14554     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14555 
14556   // If there is an identifier, use the location of the identifier as the
14557   // location of the decl, otherwise use the location of the struct/union
14558   // keyword.
14559   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14560 
14561   // Otherwise, create a new declaration. If there is a previous
14562   // declaration of the same entity, the two will be linked via
14563   // PrevDecl.
14564   TagDecl *New;
14565 
14566   if (Kind == TTK_Enum) {
14567     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14568     // enum X { A, B, C } D;    D should chain to X.
14569     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14570                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14571                            ScopedEnumUsesClassTag, IsFixed);
14572 
14573     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14574       StdAlignValT = cast<EnumDecl>(New);
14575 
14576     // If this is an undefined enum, warn.
14577     if (TUK != TUK_Definition && !Invalid) {
14578       TagDecl *Def;
14579       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14580           cast<EnumDecl>(New)->isFixed()) {
14581         // C++0x: 7.2p2: opaque-enum-declaration.
14582         // Conflicts are diagnosed above. Do nothing.
14583       }
14584       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14585         Diag(Loc, diag::ext_forward_ref_enum_def)
14586           << New;
14587         Diag(Def->getLocation(), diag::note_previous_definition);
14588       } else {
14589         unsigned DiagID = diag::ext_forward_ref_enum;
14590         if (getLangOpts().MSVCCompat)
14591           DiagID = diag::ext_ms_forward_ref_enum;
14592         else if (getLangOpts().CPlusPlus)
14593           DiagID = diag::err_forward_ref_enum;
14594         Diag(Loc, DiagID);
14595       }
14596     }
14597 
14598     if (EnumUnderlying) {
14599       EnumDecl *ED = cast<EnumDecl>(New);
14600       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14601         ED->setIntegerTypeSourceInfo(TI);
14602       else
14603         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14604       ED->setPromotionType(ED->getIntegerType());
14605       assert(ED->isComplete() && "enum with type should be complete");
14606     }
14607   } else {
14608     // struct/union/class
14609 
14610     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14611     // struct X { int A; } D;    D should chain to X.
14612     if (getLangOpts().CPlusPlus) {
14613       // FIXME: Look for a way to use RecordDecl for simple structs.
14614       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14615                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14616 
14617       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14618         StdBadAlloc = cast<CXXRecordDecl>(New);
14619     } else
14620       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14621                                cast_or_null<RecordDecl>(PrevDecl));
14622   }
14623 
14624   // C++11 [dcl.type]p3:
14625   //   A type-specifier-seq shall not define a class or enumeration [...].
14626   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14627       TUK == TUK_Definition) {
14628     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14629       << Context.getTagDeclType(New);
14630     Invalid = true;
14631   }
14632 
14633   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14634       DC->getDeclKind() == Decl::Enum) {
14635     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14636       << Context.getTagDeclType(New);
14637     Invalid = true;
14638   }
14639 
14640   // Maybe add qualifier info.
14641   if (SS.isNotEmpty()) {
14642     if (SS.isSet()) {
14643       // If this is either a declaration or a definition, check the
14644       // nested-name-specifier against the current context.
14645       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14646           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14647                                        isMemberSpecialization))
14648         Invalid = true;
14649 
14650       New->setQualifierInfo(SS.getWithLocInContext(Context));
14651       if (TemplateParameterLists.size() > 0) {
14652         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14653       }
14654     }
14655     else
14656       Invalid = true;
14657   }
14658 
14659   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14660     // Add alignment attributes if necessary; these attributes are checked when
14661     // the ASTContext lays out the structure.
14662     //
14663     // It is important for implementing the correct semantics that this
14664     // happen here (in ActOnTag). The #pragma pack stack is
14665     // maintained as a result of parser callbacks which can occur at
14666     // many points during the parsing of a struct declaration (because
14667     // the #pragma tokens are effectively skipped over during the
14668     // parsing of the struct).
14669     if (TUK == TUK_Definition) {
14670       AddAlignmentAttributesForRecord(RD);
14671       AddMsStructLayoutForRecord(RD);
14672     }
14673   }
14674 
14675   if (ModulePrivateLoc.isValid()) {
14676     if (isMemberSpecialization)
14677       Diag(New->getLocation(), diag::err_module_private_specialization)
14678         << 2
14679         << FixItHint::CreateRemoval(ModulePrivateLoc);
14680     // __module_private__ does not apply to local classes. However, we only
14681     // diagnose this as an error when the declaration specifiers are
14682     // freestanding. Here, we just ignore the __module_private__.
14683     else if (!SearchDC->isFunctionOrMethod())
14684       New->setModulePrivate();
14685   }
14686 
14687   // If this is a specialization of a member class (of a class template),
14688   // check the specialization.
14689   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14690     Invalid = true;
14691 
14692   // If we're declaring or defining a tag in function prototype scope in C,
14693   // note that this type can only be used within the function and add it to
14694   // the list of decls to inject into the function definition scope.
14695   if ((Name || Kind == TTK_Enum) &&
14696       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14697     if (getLangOpts().CPlusPlus) {
14698       // C++ [dcl.fct]p6:
14699       //   Types shall not be defined in return or parameter types.
14700       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14701         Diag(Loc, diag::err_type_defined_in_param_type)
14702             << Name;
14703         Invalid = true;
14704       }
14705     } else if (!PrevDecl) {
14706       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14707     }
14708   }
14709 
14710   if (Invalid)
14711     New->setInvalidDecl();
14712 
14713   // Set the lexical context. If the tag has a C++ scope specifier, the
14714   // lexical context will be different from the semantic context.
14715   New->setLexicalDeclContext(CurContext);
14716 
14717   // Mark this as a friend decl if applicable.
14718   // In Microsoft mode, a friend declaration also acts as a forward
14719   // declaration so we always pass true to setObjectOfFriendDecl to make
14720   // the tag name visible.
14721   if (TUK == TUK_Friend)
14722     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14723 
14724   // Set the access specifier.
14725   if (!Invalid && SearchDC->isRecord())
14726     SetMemberAccessSpecifier(New, PrevDecl, AS);
14727 
14728   if (PrevDecl)
14729     CheckRedeclarationModuleOwnership(New, PrevDecl);
14730 
14731   if (TUK == TUK_Definition)
14732     New->startDefinition();
14733 
14734   ProcessDeclAttributeList(S, New, Attrs);
14735   AddPragmaAttributes(S, New);
14736 
14737   // If this has an identifier, add it to the scope stack.
14738   if (TUK == TUK_Friend) {
14739     // We might be replacing an existing declaration in the lookup tables;
14740     // if so, borrow its access specifier.
14741     if (PrevDecl)
14742       New->setAccess(PrevDecl->getAccess());
14743 
14744     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14745     DC->makeDeclVisibleInContext(New);
14746     if (Name) // can be null along some error paths
14747       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14748         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14749   } else if (Name) {
14750     S = getNonFieldDeclScope(S);
14751     PushOnScopeChains(New, S, true);
14752   } else {
14753     CurContext->addDecl(New);
14754   }
14755 
14756   // If this is the C FILE type, notify the AST context.
14757   if (IdentifierInfo *II = New->getIdentifier())
14758     if (!New->isInvalidDecl() &&
14759         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14760         II->isStr("FILE"))
14761       Context.setFILEDecl(New);
14762 
14763   if (PrevDecl)
14764     mergeDeclAttributes(New, PrevDecl);
14765 
14766   // If there's a #pragma GCC visibility in scope, set the visibility of this
14767   // record.
14768   AddPushedVisibilityAttribute(New);
14769 
14770   if (isMemberSpecialization && !New->isInvalidDecl())
14771     CompleteMemberSpecialization(New, Previous);
14772 
14773   OwnedDecl = true;
14774   // In C++, don't return an invalid declaration. We can't recover well from
14775   // the cases where we make the type anonymous.
14776   if (Invalid && getLangOpts().CPlusPlus) {
14777     if (New->isBeingDefined())
14778       if (auto RD = dyn_cast<RecordDecl>(New))
14779         RD->completeDefinition();
14780     return nullptr;
14781   } else {
14782     return New;
14783   }
14784 }
14785 
14786 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14787   AdjustDeclIfTemplate(TagD);
14788   TagDecl *Tag = cast<TagDecl>(TagD);
14789 
14790   // Enter the tag context.
14791   PushDeclContext(S, Tag);
14792 
14793   ActOnDocumentableDecl(TagD);
14794 
14795   // If there's a #pragma GCC visibility in scope, set the visibility of this
14796   // record.
14797   AddPushedVisibilityAttribute(Tag);
14798 }
14799 
14800 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14801                                     SkipBodyInfo &SkipBody) {
14802   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14803     return false;
14804 
14805   // Make the previous decl visible.
14806   makeMergedDefinitionVisible(SkipBody.Previous);
14807   return true;
14808 }
14809 
14810 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14811   assert(isa<ObjCContainerDecl>(IDecl) &&
14812          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14813   DeclContext *OCD = cast<DeclContext>(IDecl);
14814   assert(getContainingDC(OCD) == CurContext &&
14815       "The next DeclContext should be lexically contained in the current one.");
14816   CurContext = OCD;
14817   return IDecl;
14818 }
14819 
14820 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14821                                            SourceLocation FinalLoc,
14822                                            bool IsFinalSpelledSealed,
14823                                            SourceLocation LBraceLoc) {
14824   AdjustDeclIfTemplate(TagD);
14825   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14826 
14827   FieldCollector->StartClass();
14828 
14829   if (!Record->getIdentifier())
14830     return;
14831 
14832   if (FinalLoc.isValid())
14833     Record->addAttr(new (Context)
14834                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14835 
14836   // C++ [class]p2:
14837   //   [...] The class-name is also inserted into the scope of the
14838   //   class itself; this is known as the injected-class-name. For
14839   //   purposes of access checking, the injected-class-name is treated
14840   //   as if it were a public member name.
14841   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
14842       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
14843       Record->getLocation(), Record->getIdentifier(),
14844       /*PrevDecl=*/nullptr,
14845       /*DelayTypeCreation=*/true);
14846   Context.getTypeDeclType(InjectedClassName, Record);
14847   InjectedClassName->setImplicit();
14848   InjectedClassName->setAccess(AS_public);
14849   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14850       InjectedClassName->setDescribedClassTemplate(Template);
14851   PushOnScopeChains(InjectedClassName, S);
14852   assert(InjectedClassName->isInjectedClassName() &&
14853          "Broken injected-class-name");
14854 }
14855 
14856 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14857                                     SourceRange BraceRange) {
14858   AdjustDeclIfTemplate(TagD);
14859   TagDecl *Tag = cast<TagDecl>(TagD);
14860   Tag->setBraceRange(BraceRange);
14861 
14862   // Make sure we "complete" the definition even it is invalid.
14863   if (Tag->isBeingDefined()) {
14864     assert(Tag->isInvalidDecl() && "We should already have completed it");
14865     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14866       RD->completeDefinition();
14867   }
14868 
14869   if (isa<CXXRecordDecl>(Tag)) {
14870     FieldCollector->FinishClass();
14871   }
14872 
14873   // Exit this scope of this tag's definition.
14874   PopDeclContext();
14875 
14876   if (getCurLexicalContext()->isObjCContainer() &&
14877       Tag->getDeclContext()->isFileContext())
14878     Tag->setTopLevelDeclInObjCContainer();
14879 
14880   // Notify the consumer that we've defined a tag.
14881   if (!Tag->isInvalidDecl())
14882     Consumer.HandleTagDeclDefinition(Tag);
14883 }
14884 
14885 void Sema::ActOnObjCContainerFinishDefinition() {
14886   // Exit this scope of this interface definition.
14887   PopDeclContext();
14888 }
14889 
14890 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14891   assert(DC == CurContext && "Mismatch of container contexts");
14892   OriginalLexicalContext = DC;
14893   ActOnObjCContainerFinishDefinition();
14894 }
14895 
14896 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14897   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14898   OriginalLexicalContext = nullptr;
14899 }
14900 
14901 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14902   AdjustDeclIfTemplate(TagD);
14903   TagDecl *Tag = cast<TagDecl>(TagD);
14904   Tag->setInvalidDecl();
14905 
14906   // Make sure we "complete" the definition even it is invalid.
14907   if (Tag->isBeingDefined()) {
14908     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14909       RD->completeDefinition();
14910   }
14911 
14912   // We're undoing ActOnTagStartDefinition here, not
14913   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14914   // the FieldCollector.
14915 
14916   PopDeclContext();
14917 }
14918 
14919 // Note that FieldName may be null for anonymous bitfields.
14920 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14921                                 IdentifierInfo *FieldName,
14922                                 QualType FieldTy, bool IsMsStruct,
14923                                 Expr *BitWidth, bool *ZeroWidth) {
14924   // Default to true; that shouldn't confuse checks for emptiness
14925   if (ZeroWidth)
14926     *ZeroWidth = true;
14927 
14928   // C99 6.7.2.1p4 - verify the field type.
14929   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14930   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14931     // Handle incomplete types with specific error.
14932     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14933       return ExprError();
14934     if (FieldName)
14935       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14936         << FieldName << FieldTy << BitWidth->getSourceRange();
14937     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14938       << FieldTy << BitWidth->getSourceRange();
14939   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14940                                              UPPC_BitFieldWidth))
14941     return ExprError();
14942 
14943   // If the bit-width is type- or value-dependent, don't try to check
14944   // it now.
14945   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14946     return BitWidth;
14947 
14948   llvm::APSInt Value;
14949   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14950   if (ICE.isInvalid())
14951     return ICE;
14952   BitWidth = ICE.get();
14953 
14954   if (Value != 0 && ZeroWidth)
14955     *ZeroWidth = false;
14956 
14957   // Zero-width bitfield is ok for anonymous field.
14958   if (Value == 0 && FieldName)
14959     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14960 
14961   if (Value.isSigned() && Value.isNegative()) {
14962     if (FieldName)
14963       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14964                << FieldName << Value.toString(10);
14965     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14966       << Value.toString(10);
14967   }
14968 
14969   if (!FieldTy->isDependentType()) {
14970     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14971     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14972     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14973 
14974     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14975     // ABI.
14976     bool CStdConstraintViolation =
14977         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14978     bool MSBitfieldViolation =
14979         Value.ugt(TypeStorageSize) &&
14980         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14981     if (CStdConstraintViolation || MSBitfieldViolation) {
14982       unsigned DiagWidth =
14983           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14984       if (FieldName)
14985         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14986                << FieldName << (unsigned)Value.getZExtValue()
14987                << !CStdConstraintViolation << DiagWidth;
14988 
14989       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14990              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14991              << DiagWidth;
14992     }
14993 
14994     // Warn on types where the user might conceivably expect to get all
14995     // specified bits as value bits: that's all integral types other than
14996     // 'bool'.
14997     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14998       if (FieldName)
14999         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15000             << FieldName << (unsigned)Value.getZExtValue()
15001             << (unsigned)TypeWidth;
15002       else
15003         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15004             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15005     }
15006   }
15007 
15008   return BitWidth;
15009 }
15010 
15011 /// ActOnField - Each field of a C struct/union is passed into this in order
15012 /// to create a FieldDecl object for it.
15013 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15014                        Declarator &D, Expr *BitfieldWidth) {
15015   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15016                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15017                                /*InitStyle=*/ICIS_NoInit, AS_public);
15018   return Res;
15019 }
15020 
15021 /// HandleField - Analyze a field of a C struct or a C++ data member.
15022 ///
15023 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15024                              SourceLocation DeclStart,
15025                              Declarator &D, Expr *BitWidth,
15026                              InClassInitStyle InitStyle,
15027                              AccessSpecifier AS) {
15028   if (D.isDecompositionDeclarator()) {
15029     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15030     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15031       << Decomp.getSourceRange();
15032     return nullptr;
15033   }
15034 
15035   IdentifierInfo *II = D.getIdentifier();
15036   SourceLocation Loc = DeclStart;
15037   if (II) Loc = D.getIdentifierLoc();
15038 
15039   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15040   QualType T = TInfo->getType();
15041   if (getLangOpts().CPlusPlus) {
15042     CheckExtraCXXDefaultArguments(D);
15043 
15044     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15045                                         UPPC_DataMemberType)) {
15046       D.setInvalidType();
15047       T = Context.IntTy;
15048       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15049     }
15050   }
15051 
15052   // TR 18037 does not allow fields to be declared with address spaces.
15053   if (T.getQualifiers().hasAddressSpace() ||
15054       T->isDependentAddressSpaceType() ||
15055       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15056     Diag(Loc, diag::err_field_with_address_space);
15057     D.setInvalidType();
15058   }
15059 
15060   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15061   // used as structure or union field: image, sampler, event or block types.
15062   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
15063                           T->isSamplerT() || T->isBlockPointerType())) {
15064     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15065     D.setInvalidType();
15066   }
15067 
15068   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15069 
15070   if (D.getDeclSpec().isInlineSpecified())
15071     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15072         << getLangOpts().CPlusPlus17;
15073   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15074     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15075          diag::err_invalid_thread)
15076       << DeclSpec::getSpecifierName(TSCS);
15077 
15078   // Check to see if this name was declared as a member previously
15079   NamedDecl *PrevDecl = nullptr;
15080   LookupResult Previous(*this, II, Loc, LookupMemberName,
15081                         ForVisibleRedeclaration);
15082   LookupName(Previous, S);
15083   switch (Previous.getResultKind()) {
15084     case LookupResult::Found:
15085     case LookupResult::FoundUnresolvedValue:
15086       PrevDecl = Previous.getAsSingle<NamedDecl>();
15087       break;
15088 
15089     case LookupResult::FoundOverloaded:
15090       PrevDecl = Previous.getRepresentativeDecl();
15091       break;
15092 
15093     case LookupResult::NotFound:
15094     case LookupResult::NotFoundInCurrentInstantiation:
15095     case LookupResult::Ambiguous:
15096       break;
15097   }
15098   Previous.suppressDiagnostics();
15099 
15100   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15101     // Maybe we will complain about the shadowed template parameter.
15102     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15103     // Just pretend that we didn't see the previous declaration.
15104     PrevDecl = nullptr;
15105   }
15106 
15107   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15108     PrevDecl = nullptr;
15109 
15110   bool Mutable
15111     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15112   SourceLocation TSSL = D.getBeginLoc();
15113   FieldDecl *NewFD
15114     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15115                      TSSL, AS, PrevDecl, &D);
15116 
15117   if (NewFD->isInvalidDecl())
15118     Record->setInvalidDecl();
15119 
15120   if (D.getDeclSpec().isModulePrivateSpecified())
15121     NewFD->setModulePrivate();
15122 
15123   if (NewFD->isInvalidDecl() && PrevDecl) {
15124     // Don't introduce NewFD into scope; there's already something
15125     // with the same name in the same scope.
15126   } else if (II) {
15127     PushOnScopeChains(NewFD, S);
15128   } else
15129     Record->addDecl(NewFD);
15130 
15131   return NewFD;
15132 }
15133 
15134 /// Build a new FieldDecl and check its well-formedness.
15135 ///
15136 /// This routine builds a new FieldDecl given the fields name, type,
15137 /// record, etc. \p PrevDecl should refer to any previous declaration
15138 /// with the same name and in the same scope as the field to be
15139 /// created.
15140 ///
15141 /// \returns a new FieldDecl.
15142 ///
15143 /// \todo The Declarator argument is a hack. It will be removed once
15144 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15145                                 TypeSourceInfo *TInfo,
15146                                 RecordDecl *Record, SourceLocation Loc,
15147                                 bool Mutable, Expr *BitWidth,
15148                                 InClassInitStyle InitStyle,
15149                                 SourceLocation TSSL,
15150                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15151                                 Declarator *D) {
15152   IdentifierInfo *II = Name.getAsIdentifierInfo();
15153   bool InvalidDecl = false;
15154   if (D) InvalidDecl = D->isInvalidType();
15155 
15156   // If we receive a broken type, recover by assuming 'int' and
15157   // marking this declaration as invalid.
15158   if (T.isNull()) {
15159     InvalidDecl = true;
15160     T = Context.IntTy;
15161   }
15162 
15163   QualType EltTy = Context.getBaseElementType(T);
15164   if (!EltTy->isDependentType()) {
15165     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15166       // Fields of incomplete type force their record to be invalid.
15167       Record->setInvalidDecl();
15168       InvalidDecl = true;
15169     } else {
15170       NamedDecl *Def;
15171       EltTy->isIncompleteType(&Def);
15172       if (Def && Def->isInvalidDecl()) {
15173         Record->setInvalidDecl();
15174         InvalidDecl = true;
15175       }
15176     }
15177   }
15178 
15179   // OpenCL v1.2 s6.9.c: bitfields are not supported.
15180   if (BitWidth && getLangOpts().OpenCL) {
15181     Diag(Loc, diag::err_opencl_bitfields);
15182     InvalidDecl = true;
15183   }
15184 
15185   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15186   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15187       T.hasQualifiers()) {
15188     InvalidDecl = true;
15189     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15190   }
15191 
15192   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15193   // than a variably modified type.
15194   if (!InvalidDecl && T->isVariablyModifiedType()) {
15195     bool SizeIsNegative;
15196     llvm::APSInt Oversized;
15197 
15198     TypeSourceInfo *FixedTInfo =
15199       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15200                                                     SizeIsNegative,
15201                                                     Oversized);
15202     if (FixedTInfo) {
15203       Diag(Loc, diag::warn_illegal_constant_array_size);
15204       TInfo = FixedTInfo;
15205       T = FixedTInfo->getType();
15206     } else {
15207       if (SizeIsNegative)
15208         Diag(Loc, diag::err_typecheck_negative_array_size);
15209       else if (Oversized.getBoolValue())
15210         Diag(Loc, diag::err_array_too_large)
15211           << Oversized.toString(10);
15212       else
15213         Diag(Loc, diag::err_typecheck_field_variable_size);
15214       InvalidDecl = true;
15215     }
15216   }
15217 
15218   // Fields can not have abstract class types
15219   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15220                                              diag::err_abstract_type_in_decl,
15221                                              AbstractFieldType))
15222     InvalidDecl = true;
15223 
15224   bool ZeroWidth = false;
15225   if (InvalidDecl)
15226     BitWidth = nullptr;
15227   // If this is declared as a bit-field, check the bit-field.
15228   if (BitWidth) {
15229     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15230                               &ZeroWidth).get();
15231     if (!BitWidth) {
15232       InvalidDecl = true;
15233       BitWidth = nullptr;
15234       ZeroWidth = false;
15235     }
15236   }
15237 
15238   // Check that 'mutable' is consistent with the type of the declaration.
15239   if (!InvalidDecl && Mutable) {
15240     unsigned DiagID = 0;
15241     if (T->isReferenceType())
15242       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15243                                         : diag::err_mutable_reference;
15244     else if (T.isConstQualified())
15245       DiagID = diag::err_mutable_const;
15246 
15247     if (DiagID) {
15248       SourceLocation ErrLoc = Loc;
15249       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15250         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15251       Diag(ErrLoc, DiagID);
15252       if (DiagID != diag::ext_mutable_reference) {
15253         Mutable = false;
15254         InvalidDecl = true;
15255       }
15256     }
15257   }
15258 
15259   // C++11 [class.union]p8 (DR1460):
15260   //   At most one variant member of a union may have a
15261   //   brace-or-equal-initializer.
15262   if (InitStyle != ICIS_NoInit)
15263     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15264 
15265   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15266                                        BitWidth, Mutable, InitStyle);
15267   if (InvalidDecl)
15268     NewFD->setInvalidDecl();
15269 
15270   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15271     Diag(Loc, diag::err_duplicate_member) << II;
15272     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15273     NewFD->setInvalidDecl();
15274   }
15275 
15276   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15277     if (Record->isUnion()) {
15278       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15279         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15280         if (RDecl->getDefinition()) {
15281           // C++ [class.union]p1: An object of a class with a non-trivial
15282           // constructor, a non-trivial copy constructor, a non-trivial
15283           // destructor, or a non-trivial copy assignment operator
15284           // cannot be a member of a union, nor can an array of such
15285           // objects.
15286           if (CheckNontrivialField(NewFD))
15287             NewFD->setInvalidDecl();
15288         }
15289       }
15290 
15291       // C++ [class.union]p1: If a union contains a member of reference type,
15292       // the program is ill-formed, except when compiling with MSVC extensions
15293       // enabled.
15294       if (EltTy->isReferenceType()) {
15295         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15296                                     diag::ext_union_member_of_reference_type :
15297                                     diag::err_union_member_of_reference_type)
15298           << NewFD->getDeclName() << EltTy;
15299         if (!getLangOpts().MicrosoftExt)
15300           NewFD->setInvalidDecl();
15301       }
15302     }
15303   }
15304 
15305   // FIXME: We need to pass in the attributes given an AST
15306   // representation, not a parser representation.
15307   if (D) {
15308     // FIXME: The current scope is almost... but not entirely... correct here.
15309     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15310 
15311     if (NewFD->hasAttrs())
15312       CheckAlignasUnderalignment(NewFD);
15313   }
15314 
15315   // In auto-retain/release, infer strong retension for fields of
15316   // retainable type.
15317   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15318     NewFD->setInvalidDecl();
15319 
15320   if (T.isObjCGCWeak())
15321     Diag(Loc, diag::warn_attribute_weak_on_field);
15322 
15323   NewFD->setAccess(AS);
15324   return NewFD;
15325 }
15326 
15327 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15328   assert(FD);
15329   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15330 
15331   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15332     return false;
15333 
15334   QualType EltTy = Context.getBaseElementType(FD->getType());
15335   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15336     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15337     if (RDecl->getDefinition()) {
15338       // We check for copy constructors before constructors
15339       // because otherwise we'll never get complaints about
15340       // copy constructors.
15341 
15342       CXXSpecialMember member = CXXInvalid;
15343       // We're required to check for any non-trivial constructors. Since the
15344       // implicit default constructor is suppressed if there are any
15345       // user-declared constructors, we just need to check that there is a
15346       // trivial default constructor and a trivial copy constructor. (We don't
15347       // worry about move constructors here, since this is a C++98 check.)
15348       if (RDecl->hasNonTrivialCopyConstructor())
15349         member = CXXCopyConstructor;
15350       else if (!RDecl->hasTrivialDefaultConstructor())
15351         member = CXXDefaultConstructor;
15352       else if (RDecl->hasNonTrivialCopyAssignment())
15353         member = CXXCopyAssignment;
15354       else if (RDecl->hasNonTrivialDestructor())
15355         member = CXXDestructor;
15356 
15357       if (member != CXXInvalid) {
15358         if (!getLangOpts().CPlusPlus11 &&
15359             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15360           // Objective-C++ ARC: it is an error to have a non-trivial field of
15361           // a union. However, system headers in Objective-C programs
15362           // occasionally have Objective-C lifetime objects within unions,
15363           // and rather than cause the program to fail, we make those
15364           // members unavailable.
15365           SourceLocation Loc = FD->getLocation();
15366           if (getSourceManager().isInSystemHeader(Loc)) {
15367             if (!FD->hasAttr<UnavailableAttr>())
15368               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15369                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15370             return false;
15371           }
15372         }
15373 
15374         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15375                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15376                diag::err_illegal_union_or_anon_struct_member)
15377           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15378         DiagnoseNontrivial(RDecl, member);
15379         return !getLangOpts().CPlusPlus11;
15380       }
15381     }
15382   }
15383 
15384   return false;
15385 }
15386 
15387 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15388 ///  AST enum value.
15389 static ObjCIvarDecl::AccessControl
15390 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15391   switch (ivarVisibility) {
15392   default: llvm_unreachable("Unknown visitibility kind");
15393   case tok::objc_private: return ObjCIvarDecl::Private;
15394   case tok::objc_public: return ObjCIvarDecl::Public;
15395   case tok::objc_protected: return ObjCIvarDecl::Protected;
15396   case tok::objc_package: return ObjCIvarDecl::Package;
15397   }
15398 }
15399 
15400 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15401 /// in order to create an IvarDecl object for it.
15402 Decl *Sema::ActOnIvar(Scope *S,
15403                                 SourceLocation DeclStart,
15404                                 Declarator &D, Expr *BitfieldWidth,
15405                                 tok::ObjCKeywordKind Visibility) {
15406 
15407   IdentifierInfo *II = D.getIdentifier();
15408   Expr *BitWidth = (Expr*)BitfieldWidth;
15409   SourceLocation Loc = DeclStart;
15410   if (II) Loc = D.getIdentifierLoc();
15411 
15412   // FIXME: Unnamed fields can be handled in various different ways, for
15413   // example, unnamed unions inject all members into the struct namespace!
15414 
15415   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15416   QualType T = TInfo->getType();
15417 
15418   if (BitWidth) {
15419     // 6.7.2.1p3, 6.7.2.1p4
15420     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15421     if (!BitWidth)
15422       D.setInvalidType();
15423   } else {
15424     // Not a bitfield.
15425 
15426     // validate II.
15427 
15428   }
15429   if (T->isReferenceType()) {
15430     Diag(Loc, diag::err_ivar_reference_type);
15431     D.setInvalidType();
15432   }
15433   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15434   // than a variably modified type.
15435   else if (T->isVariablyModifiedType()) {
15436     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15437     D.setInvalidType();
15438   }
15439 
15440   // Get the visibility (access control) for this ivar.
15441   ObjCIvarDecl::AccessControl ac =
15442     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15443                                         : ObjCIvarDecl::None;
15444   // Must set ivar's DeclContext to its enclosing interface.
15445   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15446   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15447     return nullptr;
15448   ObjCContainerDecl *EnclosingContext;
15449   if (ObjCImplementationDecl *IMPDecl =
15450       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15451     if (LangOpts.ObjCRuntime.isFragile()) {
15452     // Case of ivar declared in an implementation. Context is that of its class.
15453       EnclosingContext = IMPDecl->getClassInterface();
15454       assert(EnclosingContext && "Implementation has no class interface!");
15455     }
15456     else
15457       EnclosingContext = EnclosingDecl;
15458   } else {
15459     if (ObjCCategoryDecl *CDecl =
15460         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15461       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15462         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15463         return nullptr;
15464       }
15465     }
15466     EnclosingContext = EnclosingDecl;
15467   }
15468 
15469   // Construct the decl.
15470   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15471                                              DeclStart, Loc, II, T,
15472                                              TInfo, ac, (Expr *)BitfieldWidth);
15473 
15474   if (II) {
15475     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15476                                            ForVisibleRedeclaration);
15477     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15478         && !isa<TagDecl>(PrevDecl)) {
15479       Diag(Loc, diag::err_duplicate_member) << II;
15480       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15481       NewID->setInvalidDecl();
15482     }
15483   }
15484 
15485   // Process attributes attached to the ivar.
15486   ProcessDeclAttributes(S, NewID, D);
15487 
15488   if (D.isInvalidType())
15489     NewID->setInvalidDecl();
15490 
15491   // In ARC, infer 'retaining' for ivars of retainable type.
15492   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15493     NewID->setInvalidDecl();
15494 
15495   if (D.getDeclSpec().isModulePrivateSpecified())
15496     NewID->setModulePrivate();
15497 
15498   if (II) {
15499     // FIXME: When interfaces are DeclContexts, we'll need to add
15500     // these to the interface.
15501     S->AddDecl(NewID);
15502     IdResolver.AddDecl(NewID);
15503   }
15504 
15505   if (LangOpts.ObjCRuntime.isNonFragile() &&
15506       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15507     Diag(Loc, diag::warn_ivars_in_interface);
15508 
15509   return NewID;
15510 }
15511 
15512 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15513 /// class and class extensions. For every class \@interface and class
15514 /// extension \@interface, if the last ivar is a bitfield of any type,
15515 /// then add an implicit `char :0` ivar to the end of that interface.
15516 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15517                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15518   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15519     return;
15520 
15521   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15522   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15523 
15524   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15525     return;
15526   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15527   if (!ID) {
15528     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15529       if (!CD->IsClassExtension())
15530         return;
15531     }
15532     // No need to add this to end of @implementation.
15533     else
15534       return;
15535   }
15536   // All conditions are met. Add a new bitfield to the tail end of ivars.
15537   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15538   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15539 
15540   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15541                               DeclLoc, DeclLoc, nullptr,
15542                               Context.CharTy,
15543                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15544                                                                DeclLoc),
15545                               ObjCIvarDecl::Private, BW,
15546                               true);
15547   AllIvarDecls.push_back(Ivar);
15548 }
15549 
15550 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15551                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15552                        SourceLocation RBrac,
15553                        const ParsedAttributesView &Attrs) {
15554   assert(EnclosingDecl && "missing record or interface decl");
15555 
15556   // If this is an Objective-C @implementation or category and we have
15557   // new fields here we should reset the layout of the interface since
15558   // it will now change.
15559   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15560     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15561     switch (DC->getKind()) {
15562     default: break;
15563     case Decl::ObjCCategory:
15564       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15565       break;
15566     case Decl::ObjCImplementation:
15567       Context.
15568         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15569       break;
15570     }
15571   }
15572 
15573   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15574   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15575 
15576   // Start counting up the number of named members; make sure to include
15577   // members of anonymous structs and unions in the total.
15578   unsigned NumNamedMembers = 0;
15579   if (Record) {
15580     for (const auto *I : Record->decls()) {
15581       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15582         if (IFD->getDeclName())
15583           ++NumNamedMembers;
15584     }
15585   }
15586 
15587   // Verify that all the fields are okay.
15588   SmallVector<FieldDecl*, 32> RecFields;
15589 
15590   bool ObjCFieldLifetimeErrReported = false;
15591   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15592        i != end; ++i) {
15593     FieldDecl *FD = cast<FieldDecl>(*i);
15594 
15595     // Get the type for the field.
15596     const Type *FDTy = FD->getType().getTypePtr();
15597 
15598     if (!FD->isAnonymousStructOrUnion()) {
15599       // Remember all fields written by the user.
15600       RecFields.push_back(FD);
15601     }
15602 
15603     // If the field is already invalid for some reason, don't emit more
15604     // diagnostics about it.
15605     if (FD->isInvalidDecl()) {
15606       EnclosingDecl->setInvalidDecl();
15607       continue;
15608     }
15609 
15610     // C99 6.7.2.1p2:
15611     //   A structure or union shall not contain a member with
15612     //   incomplete or function type (hence, a structure shall not
15613     //   contain an instance of itself, but may contain a pointer to
15614     //   an instance of itself), except that the last member of a
15615     //   structure with more than one named member may have incomplete
15616     //   array type; such a structure (and any union containing,
15617     //   possibly recursively, a member that is such a structure)
15618     //   shall not be a member of a structure or an element of an
15619     //   array.
15620     bool IsLastField = (i + 1 == Fields.end());
15621     if (FDTy->isFunctionType()) {
15622       // Field declared as a function.
15623       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15624         << FD->getDeclName();
15625       FD->setInvalidDecl();
15626       EnclosingDecl->setInvalidDecl();
15627       continue;
15628     } else if (FDTy->isIncompleteArrayType() &&
15629                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15630       if (Record) {
15631         // Flexible array member.
15632         // Microsoft and g++ is more permissive regarding flexible array.
15633         // It will accept flexible array in union and also
15634         // as the sole element of a struct/class.
15635         unsigned DiagID = 0;
15636         if (!Record->isUnion() && !IsLastField) {
15637           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15638             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15639           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15640           FD->setInvalidDecl();
15641           EnclosingDecl->setInvalidDecl();
15642           continue;
15643         } else if (Record->isUnion())
15644           DiagID = getLangOpts().MicrosoftExt
15645                        ? diag::ext_flexible_array_union_ms
15646                        : getLangOpts().CPlusPlus
15647                              ? diag::ext_flexible_array_union_gnu
15648                              : diag::err_flexible_array_union;
15649         else if (NumNamedMembers < 1)
15650           DiagID = getLangOpts().MicrosoftExt
15651                        ? diag::ext_flexible_array_empty_aggregate_ms
15652                        : getLangOpts().CPlusPlus
15653                              ? diag::ext_flexible_array_empty_aggregate_gnu
15654                              : diag::err_flexible_array_empty_aggregate;
15655 
15656         if (DiagID)
15657           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15658                                           << Record->getTagKind();
15659         // While the layout of types that contain virtual bases is not specified
15660         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15661         // virtual bases after the derived members.  This would make a flexible
15662         // array member declared at the end of an object not adjacent to the end
15663         // of the type.
15664         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15665           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15666               << FD->getDeclName() << Record->getTagKind();
15667         if (!getLangOpts().C99)
15668           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15669             << FD->getDeclName() << Record->getTagKind();
15670 
15671         // If the element type has a non-trivial destructor, we would not
15672         // implicitly destroy the elements, so disallow it for now.
15673         //
15674         // FIXME: GCC allows this. We should probably either implicitly delete
15675         // the destructor of the containing class, or just allow this.
15676         QualType BaseElem = Context.getBaseElementType(FD->getType());
15677         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15678           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15679             << FD->getDeclName() << FD->getType();
15680           FD->setInvalidDecl();
15681           EnclosingDecl->setInvalidDecl();
15682           continue;
15683         }
15684         // Okay, we have a legal flexible array member at the end of the struct.
15685         Record->setHasFlexibleArrayMember(true);
15686       } else {
15687         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15688         // unless they are followed by another ivar. That check is done
15689         // elsewhere, after synthesized ivars are known.
15690       }
15691     } else if (!FDTy->isDependentType() &&
15692                RequireCompleteType(FD->getLocation(), FD->getType(),
15693                                    diag::err_field_incomplete)) {
15694       // Incomplete type
15695       FD->setInvalidDecl();
15696       EnclosingDecl->setInvalidDecl();
15697       continue;
15698     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15699       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15700         // A type which contains a flexible array member is considered to be a
15701         // flexible array member.
15702         Record->setHasFlexibleArrayMember(true);
15703         if (!Record->isUnion()) {
15704           // If this is a struct/class and this is not the last element, reject
15705           // it.  Note that GCC supports variable sized arrays in the middle of
15706           // structures.
15707           if (!IsLastField)
15708             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15709               << FD->getDeclName() << FD->getType();
15710           else {
15711             // We support flexible arrays at the end of structs in
15712             // other structs as an extension.
15713             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15714               << FD->getDeclName();
15715           }
15716         }
15717       }
15718       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15719           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15720                                  diag::err_abstract_type_in_decl,
15721                                  AbstractIvarType)) {
15722         // Ivars can not have abstract class types
15723         FD->setInvalidDecl();
15724       }
15725       if (Record && FDTTy->getDecl()->hasObjectMember())
15726         Record->setHasObjectMember(true);
15727       if (Record && FDTTy->getDecl()->hasVolatileMember())
15728         Record->setHasVolatileMember(true);
15729     } else if (FDTy->isObjCObjectType()) {
15730       /// A field cannot be an Objective-c object
15731       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15732         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15733       QualType T = Context.getObjCObjectPointerType(FD->getType());
15734       FD->setType(T);
15735     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15736                Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15737       // It's an error in ARC or Weak if a field has lifetime.
15738       // We don't want to report this in a system header, though,
15739       // so we just make the field unavailable.
15740       // FIXME: that's really not sufficient; we need to make the type
15741       // itself invalid to, say, initialize or copy.
15742       QualType T = FD->getType();
15743       if (T.hasNonTrivialObjCLifetime()) {
15744         SourceLocation loc = FD->getLocation();
15745         if (getSourceManager().isInSystemHeader(loc)) {
15746           if (!FD->hasAttr<UnavailableAttr>()) {
15747             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15748                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15749           }
15750         } else {
15751           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15752             << T->isBlockPointerType() << Record->getTagKind();
15753         }
15754         ObjCFieldLifetimeErrReported = true;
15755       }
15756     } else if (getLangOpts().ObjC1 &&
15757                getLangOpts().getGC() != LangOptions::NonGC &&
15758                Record && !Record->hasObjectMember()) {
15759       if (FD->getType()->isObjCObjectPointerType() ||
15760           FD->getType().isObjCGCStrong())
15761         Record->setHasObjectMember(true);
15762       else if (Context.getAsArrayType(FD->getType())) {
15763         QualType BaseType = Context.getBaseElementType(FD->getType());
15764         if (BaseType->isRecordType() &&
15765             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15766           Record->setHasObjectMember(true);
15767         else if (BaseType->isObjCObjectPointerType() ||
15768                  BaseType.isObjCGCStrong())
15769                Record->setHasObjectMember(true);
15770       }
15771     }
15772 
15773     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15774       QualType FT = FD->getType();
15775       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15776         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15777       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15778       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15779         Record->setNonTrivialToPrimitiveCopy(true);
15780       if (FT.isDestructedType()) {
15781         Record->setNonTrivialToPrimitiveDestroy(true);
15782         Record->setParamDestroyedInCallee(true);
15783       }
15784 
15785       if (const auto *RT = FT->getAs<RecordType>()) {
15786         if (RT->getDecl()->getArgPassingRestrictions() ==
15787             RecordDecl::APK_CanNeverPassInRegs)
15788           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15789       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15790         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15791     }
15792 
15793     if (Record && FD->getType().isVolatileQualified())
15794       Record->setHasVolatileMember(true);
15795     // Keep track of the number of named members.
15796     if (FD->getIdentifier())
15797       ++NumNamedMembers;
15798   }
15799 
15800   // Okay, we successfully defined 'Record'.
15801   if (Record) {
15802     bool Completed = false;
15803     if (CXXRecord) {
15804       if (!CXXRecord->isInvalidDecl()) {
15805         // Set access bits correctly on the directly-declared conversions.
15806         for (CXXRecordDecl::conversion_iterator
15807                I = CXXRecord->conversion_begin(),
15808                E = CXXRecord->conversion_end(); I != E; ++I)
15809           I.setAccess((*I)->getAccess());
15810       }
15811 
15812       if (!CXXRecord->isDependentType()) {
15813         if (CXXRecord->hasUserDeclaredDestructor()) {
15814           // Adjust user-defined destructor exception spec.
15815           if (getLangOpts().CPlusPlus11)
15816             AdjustDestructorExceptionSpec(CXXRecord,
15817                                           CXXRecord->getDestructor());
15818         }
15819 
15820         // Add any implicitly-declared members to this class.
15821         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15822 
15823         if (!CXXRecord->isInvalidDecl()) {
15824           // If we have virtual base classes, we may end up finding multiple
15825           // final overriders for a given virtual function. Check for this
15826           // problem now.
15827           if (CXXRecord->getNumVBases()) {
15828             CXXFinalOverriderMap FinalOverriders;
15829             CXXRecord->getFinalOverriders(FinalOverriders);
15830 
15831             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15832                                              MEnd = FinalOverriders.end();
15833                  M != MEnd; ++M) {
15834               for (OverridingMethods::iterator SO = M->second.begin(),
15835                                             SOEnd = M->second.end();
15836                    SO != SOEnd; ++SO) {
15837                 assert(SO->second.size() > 0 &&
15838                        "Virtual function without overriding functions?");
15839                 if (SO->second.size() == 1)
15840                   continue;
15841 
15842                 // C++ [class.virtual]p2:
15843                 //   In a derived class, if a virtual member function of a base
15844                 //   class subobject has more than one final overrider the
15845                 //   program is ill-formed.
15846                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15847                   << (const NamedDecl *)M->first << Record;
15848                 Diag(M->first->getLocation(),
15849                      diag::note_overridden_virtual_function);
15850                 for (OverridingMethods::overriding_iterator
15851                           OM = SO->second.begin(),
15852                        OMEnd = SO->second.end();
15853                      OM != OMEnd; ++OM)
15854                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15855                     << (const NamedDecl *)M->first << OM->Method->getParent();
15856 
15857                 Record->setInvalidDecl();
15858               }
15859             }
15860             CXXRecord->completeDefinition(&FinalOverriders);
15861             Completed = true;
15862           }
15863         }
15864       }
15865     }
15866 
15867     if (!Completed)
15868       Record->completeDefinition();
15869 
15870     // Handle attributes before checking the layout.
15871     ProcessDeclAttributeList(S, Record, Attrs);
15872 
15873     // We may have deferred checking for a deleted destructor. Check now.
15874     if (CXXRecord) {
15875       auto *Dtor = CXXRecord->getDestructor();
15876       if (Dtor && Dtor->isImplicit() &&
15877           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15878         CXXRecord->setImplicitDestructorIsDeleted();
15879         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15880       }
15881     }
15882 
15883     if (Record->hasAttrs()) {
15884       CheckAlignasUnderalignment(Record);
15885 
15886       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15887         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15888                                            IA->getRange(), IA->getBestCase(),
15889                                            IA->getSemanticSpelling());
15890     }
15891 
15892     // Check if the structure/union declaration is a type that can have zero
15893     // size in C. For C this is a language extension, for C++ it may cause
15894     // compatibility problems.
15895     bool CheckForZeroSize;
15896     if (!getLangOpts().CPlusPlus) {
15897       CheckForZeroSize = true;
15898     } else {
15899       // For C++ filter out types that cannot be referenced in C code.
15900       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15901       CheckForZeroSize =
15902           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15903           !CXXRecord->isDependentType() &&
15904           CXXRecord->isCLike();
15905     }
15906     if (CheckForZeroSize) {
15907       bool ZeroSize = true;
15908       bool IsEmpty = true;
15909       unsigned NonBitFields = 0;
15910       for (RecordDecl::field_iterator I = Record->field_begin(),
15911                                       E = Record->field_end();
15912            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15913         IsEmpty = false;
15914         if (I->isUnnamedBitfield()) {
15915           if (!I->isZeroLengthBitField(Context))
15916             ZeroSize = false;
15917         } else {
15918           ++NonBitFields;
15919           QualType FieldType = I->getType();
15920           if (FieldType->isIncompleteType() ||
15921               !Context.getTypeSizeInChars(FieldType).isZero())
15922             ZeroSize = false;
15923         }
15924       }
15925 
15926       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15927       // allowed in C++, but warn if its declaration is inside
15928       // extern "C" block.
15929       if (ZeroSize) {
15930         Diag(RecLoc, getLangOpts().CPlusPlus ?
15931                          diag::warn_zero_size_struct_union_in_extern_c :
15932                          diag::warn_zero_size_struct_union_compat)
15933           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15934       }
15935 
15936       // Structs without named members are extension in C (C99 6.7.2.1p7),
15937       // but are accepted by GCC.
15938       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15939         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15940                                diag::ext_no_named_members_in_struct_union)
15941           << Record->isUnion();
15942       }
15943     }
15944   } else {
15945     ObjCIvarDecl **ClsFields =
15946       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15947     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15948       ID->setEndOfDefinitionLoc(RBrac);
15949       // Add ivar's to class's DeclContext.
15950       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15951         ClsFields[i]->setLexicalDeclContext(ID);
15952         ID->addDecl(ClsFields[i]);
15953       }
15954       // Must enforce the rule that ivars in the base classes may not be
15955       // duplicates.
15956       if (ID->getSuperClass())
15957         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15958     } else if (ObjCImplementationDecl *IMPDecl =
15959                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15960       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15961       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15962         // Ivar declared in @implementation never belongs to the implementation.
15963         // Only it is in implementation's lexical context.
15964         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15965       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15966       IMPDecl->setIvarLBraceLoc(LBrac);
15967       IMPDecl->setIvarRBraceLoc(RBrac);
15968     } else if (ObjCCategoryDecl *CDecl =
15969                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15970       // case of ivars in class extension; all other cases have been
15971       // reported as errors elsewhere.
15972       // FIXME. Class extension does not have a LocEnd field.
15973       // CDecl->setLocEnd(RBrac);
15974       // Add ivar's to class extension's DeclContext.
15975       // Diagnose redeclaration of private ivars.
15976       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15977       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15978         if (IDecl) {
15979           if (const ObjCIvarDecl *ClsIvar =
15980               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15981             Diag(ClsFields[i]->getLocation(),
15982                  diag::err_duplicate_ivar_declaration);
15983             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15984             continue;
15985           }
15986           for (const auto *Ext : IDecl->known_extensions()) {
15987             if (const ObjCIvarDecl *ClsExtIvar
15988                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15989               Diag(ClsFields[i]->getLocation(),
15990                    diag::err_duplicate_ivar_declaration);
15991               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15992               continue;
15993             }
15994           }
15995         }
15996         ClsFields[i]->setLexicalDeclContext(CDecl);
15997         CDecl->addDecl(ClsFields[i]);
15998       }
15999       CDecl->setIvarLBraceLoc(LBrac);
16000       CDecl->setIvarRBraceLoc(RBrac);
16001     }
16002   }
16003 }
16004 
16005 /// Determine whether the given integral value is representable within
16006 /// the given type T.
16007 static bool isRepresentableIntegerValue(ASTContext &Context,
16008                                         llvm::APSInt &Value,
16009                                         QualType T) {
16010   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16011          "Integral type required!");
16012   unsigned BitWidth = Context.getIntWidth(T);
16013 
16014   if (Value.isUnsigned() || Value.isNonNegative()) {
16015     if (T->isSignedIntegerOrEnumerationType())
16016       --BitWidth;
16017     return Value.getActiveBits() <= BitWidth;
16018   }
16019   return Value.getMinSignedBits() <= BitWidth;
16020 }
16021 
16022 // Given an integral type, return the next larger integral type
16023 // (or a NULL type of no such type exists).
16024 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16025   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16026   // enum checking below.
16027   assert((T->isIntegralType(Context) ||
16028          T->isEnumeralType()) && "Integral type required!");
16029   const unsigned NumTypes = 4;
16030   QualType SignedIntegralTypes[NumTypes] = {
16031     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16032   };
16033   QualType UnsignedIntegralTypes[NumTypes] = {
16034     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16035     Context.UnsignedLongLongTy
16036   };
16037 
16038   unsigned BitWidth = Context.getTypeSize(T);
16039   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16040                                                         : UnsignedIntegralTypes;
16041   for (unsigned I = 0; I != NumTypes; ++I)
16042     if (Context.getTypeSize(Types[I]) > BitWidth)
16043       return Types[I];
16044 
16045   return QualType();
16046 }
16047 
16048 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16049                                           EnumConstantDecl *LastEnumConst,
16050                                           SourceLocation IdLoc,
16051                                           IdentifierInfo *Id,
16052                                           Expr *Val) {
16053   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16054   llvm::APSInt EnumVal(IntWidth);
16055   QualType EltTy;
16056 
16057   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16058     Val = nullptr;
16059 
16060   if (Val)
16061     Val = DefaultLvalueConversion(Val).get();
16062 
16063   if (Val) {
16064     if (Enum->isDependentType() || Val->isTypeDependent())
16065       EltTy = Context.DependentTy;
16066     else {
16067       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16068           !getLangOpts().MSVCCompat) {
16069         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16070         // constant-expression in the enumerator-definition shall be a converted
16071         // constant expression of the underlying type.
16072         EltTy = Enum->getIntegerType();
16073         ExprResult Converted =
16074           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16075                                            CCEK_Enumerator);
16076         if (Converted.isInvalid())
16077           Val = nullptr;
16078         else
16079           Val = Converted.get();
16080       } else if (!Val->isValueDependent() &&
16081                  !(Val = VerifyIntegerConstantExpression(Val,
16082                                                          &EnumVal).get())) {
16083         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16084       } else {
16085         if (Enum->isComplete()) {
16086           EltTy = Enum->getIntegerType();
16087 
16088           // In Obj-C and Microsoft mode, require the enumeration value to be
16089           // representable in the underlying type of the enumeration. In C++11,
16090           // we perform a non-narrowing conversion as part of converted constant
16091           // expression checking.
16092           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16093             if (getLangOpts().MSVCCompat) {
16094               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16095               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16096             } else
16097               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16098           } else
16099             Val = ImpCastExprToType(Val, EltTy,
16100                                     EltTy->isBooleanType() ?
16101                                     CK_IntegralToBoolean : CK_IntegralCast)
16102                     .get();
16103         } else if (getLangOpts().CPlusPlus) {
16104           // C++11 [dcl.enum]p5:
16105           //   If the underlying type is not fixed, the type of each enumerator
16106           //   is the type of its initializing value:
16107           //     - If an initializer is specified for an enumerator, the
16108           //       initializing value has the same type as the expression.
16109           EltTy = Val->getType();
16110         } else {
16111           // C99 6.7.2.2p2:
16112           //   The expression that defines the value of an enumeration constant
16113           //   shall be an integer constant expression that has a value
16114           //   representable as an int.
16115 
16116           // Complain if the value is not representable in an int.
16117           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16118             Diag(IdLoc, diag::ext_enum_value_not_int)
16119               << EnumVal.toString(10) << Val->getSourceRange()
16120               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16121           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16122             // Force the type of the expression to 'int'.
16123             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16124           }
16125           EltTy = Val->getType();
16126         }
16127       }
16128     }
16129   }
16130 
16131   if (!Val) {
16132     if (Enum->isDependentType())
16133       EltTy = Context.DependentTy;
16134     else if (!LastEnumConst) {
16135       // C++0x [dcl.enum]p5:
16136       //   If the underlying type is not fixed, the type of each enumerator
16137       //   is the type of its initializing value:
16138       //     - If no initializer is specified for the first enumerator, the
16139       //       initializing value has an unspecified integral type.
16140       //
16141       // GCC uses 'int' for its unspecified integral type, as does
16142       // C99 6.7.2.2p3.
16143       if (Enum->isFixed()) {
16144         EltTy = Enum->getIntegerType();
16145       }
16146       else {
16147         EltTy = Context.IntTy;
16148       }
16149     } else {
16150       // Assign the last value + 1.
16151       EnumVal = LastEnumConst->getInitVal();
16152       ++EnumVal;
16153       EltTy = LastEnumConst->getType();
16154 
16155       // Check for overflow on increment.
16156       if (EnumVal < LastEnumConst->getInitVal()) {
16157         // C++0x [dcl.enum]p5:
16158         //   If the underlying type is not fixed, the type of each enumerator
16159         //   is the type of its initializing value:
16160         //
16161         //     - Otherwise the type of the initializing value is the same as
16162         //       the type of the initializing value of the preceding enumerator
16163         //       unless the incremented value is not representable in that type,
16164         //       in which case the type is an unspecified integral type
16165         //       sufficient to contain the incremented value. If no such type
16166         //       exists, the program is ill-formed.
16167         QualType T = getNextLargerIntegralType(Context, EltTy);
16168         if (T.isNull() || Enum->isFixed()) {
16169           // There is no integral type larger enough to represent this
16170           // value. Complain, then allow the value to wrap around.
16171           EnumVal = LastEnumConst->getInitVal();
16172           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16173           ++EnumVal;
16174           if (Enum->isFixed())
16175             // When the underlying type is fixed, this is ill-formed.
16176             Diag(IdLoc, diag::err_enumerator_wrapped)
16177               << EnumVal.toString(10)
16178               << EltTy;
16179           else
16180             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16181               << EnumVal.toString(10);
16182         } else {
16183           EltTy = T;
16184         }
16185 
16186         // Retrieve the last enumerator's value, extent that type to the
16187         // type that is supposed to be large enough to represent the incremented
16188         // value, then increment.
16189         EnumVal = LastEnumConst->getInitVal();
16190         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16191         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16192         ++EnumVal;
16193 
16194         // If we're not in C++, diagnose the overflow of enumerator values,
16195         // which in C99 means that the enumerator value is not representable in
16196         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16197         // permits enumerator values that are representable in some larger
16198         // integral type.
16199         if (!getLangOpts().CPlusPlus && !T.isNull())
16200           Diag(IdLoc, diag::warn_enum_value_overflow);
16201       } else if (!getLangOpts().CPlusPlus &&
16202                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16203         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16204         Diag(IdLoc, diag::ext_enum_value_not_int)
16205           << EnumVal.toString(10) << 1;
16206       }
16207     }
16208   }
16209 
16210   if (!EltTy->isDependentType()) {
16211     // Make the enumerator value match the signedness and size of the
16212     // enumerator's type.
16213     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16214     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16215   }
16216 
16217   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16218                                   Val, EnumVal);
16219 }
16220 
16221 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16222                                                 SourceLocation IILoc) {
16223   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16224       !getLangOpts().CPlusPlus)
16225     return SkipBodyInfo();
16226 
16227   // We have an anonymous enum definition. Look up the first enumerator to
16228   // determine if we should merge the definition with an existing one and
16229   // skip the body.
16230   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16231                                          forRedeclarationInCurContext());
16232   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16233   if (!PrevECD)
16234     return SkipBodyInfo();
16235 
16236   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16237   NamedDecl *Hidden;
16238   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16239     SkipBodyInfo Skip;
16240     Skip.Previous = Hidden;
16241     return Skip;
16242   }
16243 
16244   return SkipBodyInfo();
16245 }
16246 
16247 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16248                               SourceLocation IdLoc, IdentifierInfo *Id,
16249                               const ParsedAttributesView &Attrs,
16250                               SourceLocation EqualLoc, Expr *Val) {
16251   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16252   EnumConstantDecl *LastEnumConst =
16253     cast_or_null<EnumConstantDecl>(lastEnumConst);
16254 
16255   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16256   // we find one that is.
16257   S = getNonFieldDeclScope(S);
16258 
16259   // Verify that there isn't already something declared with this name in this
16260   // scope.
16261   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
16262                                          ForVisibleRedeclaration);
16263   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16264     // Maybe we will complain about the shadowed template parameter.
16265     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16266     // Just pretend that we didn't see the previous declaration.
16267     PrevDecl = nullptr;
16268   }
16269 
16270   // C++ [class.mem]p15:
16271   // If T is the name of a class, then each of the following shall have a name
16272   // different from T:
16273   // - every enumerator of every member of class T that is an unscoped
16274   // enumerated type
16275   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16276     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16277                             DeclarationNameInfo(Id, IdLoc));
16278 
16279   EnumConstantDecl *New =
16280     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16281   if (!New)
16282     return nullptr;
16283 
16284   if (PrevDecl) {
16285     // When in C++, we may get a TagDecl with the same name; in this case the
16286     // enum constant will 'hide' the tag.
16287     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16288            "Received TagDecl when not in C++!");
16289     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16290       if (isa<EnumConstantDecl>(PrevDecl))
16291         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16292       else
16293         Diag(IdLoc, diag::err_redefinition) << Id;
16294       notePreviousDefinition(PrevDecl, IdLoc);
16295       return nullptr;
16296     }
16297   }
16298 
16299   // Process attributes.
16300   ProcessDeclAttributeList(S, New, Attrs);
16301   AddPragmaAttributes(S, New);
16302 
16303   // Register this decl in the current scope stack.
16304   New->setAccess(TheEnumDecl->getAccess());
16305   PushOnScopeChains(New, S);
16306 
16307   ActOnDocumentableDecl(New);
16308 
16309   return New;
16310 }
16311 
16312 // Returns true when the enum initial expression does not trigger the
16313 // duplicate enum warning.  A few common cases are exempted as follows:
16314 // Element2 = Element1
16315 // Element2 = Element1 + 1
16316 // Element2 = Element1 - 1
16317 // Where Element2 and Element1 are from the same enum.
16318 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16319   Expr *InitExpr = ECD->getInitExpr();
16320   if (!InitExpr)
16321     return true;
16322   InitExpr = InitExpr->IgnoreImpCasts();
16323 
16324   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16325     if (!BO->isAdditiveOp())
16326       return true;
16327     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16328     if (!IL)
16329       return true;
16330     if (IL->getValue() != 1)
16331       return true;
16332 
16333     InitExpr = BO->getLHS();
16334   }
16335 
16336   // This checks if the elements are from the same enum.
16337   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16338   if (!DRE)
16339     return true;
16340 
16341   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16342   if (!EnumConstant)
16343     return true;
16344 
16345   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16346       Enum)
16347     return true;
16348 
16349   return false;
16350 }
16351 
16352 // Emits a warning when an element is implicitly set a value that
16353 // a previous element has already been set to.
16354 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16355                                         EnumDecl *Enum, QualType EnumType) {
16356   // Avoid anonymous enums
16357   if (!Enum->getIdentifier())
16358     return;
16359 
16360   // Only check for small enums.
16361   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16362     return;
16363 
16364   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16365     return;
16366 
16367   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16368   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16369 
16370   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16371   typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
16372 
16373   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16374   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16375     llvm::APSInt Val = D->getInitVal();
16376     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16377   };
16378 
16379   DuplicatesVector DupVector;
16380   ValueToVectorMap EnumMap;
16381 
16382   // Populate the EnumMap with all values represented by enum constants without
16383   // an initializer.
16384   for (auto *Element : Elements) {
16385     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16386 
16387     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16388     // this constant.  Skip this enum since it may be ill-formed.
16389     if (!ECD) {
16390       return;
16391     }
16392 
16393     // Constants with initalizers are handled in the next loop.
16394     if (ECD->getInitExpr())
16395       continue;
16396 
16397     // Duplicate values are handled in the next loop.
16398     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16399   }
16400 
16401   if (EnumMap.size() == 0)
16402     return;
16403 
16404   // Create vectors for any values that has duplicates.
16405   for (auto *Element : Elements) {
16406     // The last loop returned if any constant was null.
16407     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16408     if (!ValidDuplicateEnum(ECD, Enum))
16409       continue;
16410 
16411     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16412     if (Iter == EnumMap.end())
16413       continue;
16414 
16415     DeclOrVector& Entry = Iter->second;
16416     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16417       // Ensure constants are different.
16418       if (D == ECD)
16419         continue;
16420 
16421       // Create new vector and push values onto it.
16422       auto Vec = llvm::make_unique<ECDVector>();
16423       Vec->push_back(D);
16424       Vec->push_back(ECD);
16425 
16426       // Update entry to point to the duplicates vector.
16427       Entry = Vec.get();
16428 
16429       // Store the vector somewhere we can consult later for quick emission of
16430       // diagnostics.
16431       DupVector.emplace_back(std::move(Vec));
16432       continue;
16433     }
16434 
16435     ECDVector *Vec = Entry.get<ECDVector*>();
16436     // Make sure constants are not added more than once.
16437     if (*Vec->begin() == ECD)
16438       continue;
16439 
16440     Vec->push_back(ECD);
16441   }
16442 
16443   // Emit diagnostics.
16444   for (const auto &Vec : DupVector) {
16445     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16446 
16447     // Emit warning for one enum constant.
16448     auto *FirstECD = Vec->front();
16449     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16450       << FirstECD << FirstECD->getInitVal().toString(10)
16451       << FirstECD->getSourceRange();
16452 
16453     // Emit one note for each of the remaining enum constants with
16454     // the same value.
16455     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16456       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16457         << ECD << ECD->getInitVal().toString(10)
16458         << ECD->getSourceRange();
16459   }
16460 }
16461 
16462 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16463                              bool AllowMask) const {
16464   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16465   assert(ED->isCompleteDefinition() && "expected enum definition");
16466 
16467   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16468   llvm::APInt &FlagBits = R.first->second;
16469 
16470   if (R.second) {
16471     for (auto *E : ED->enumerators()) {
16472       const auto &EVal = E->getInitVal();
16473       // Only single-bit enumerators introduce new flag values.
16474       if (EVal.isPowerOf2())
16475         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16476     }
16477   }
16478 
16479   // A value is in a flag enum if either its bits are a subset of the enum's
16480   // flag bits (the first condition) or we are allowing masks and the same is
16481   // true of its complement (the second condition). When masks are allowed, we
16482   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16483   //
16484   // While it's true that any value could be used as a mask, the assumption is
16485   // that a mask will have all of the insignificant bits set. Anything else is
16486   // likely a logic error.
16487   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16488   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16489 }
16490 
16491 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16492                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16493                          const ParsedAttributesView &Attrs) {
16494   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16495   QualType EnumType = Context.getTypeDeclType(Enum);
16496 
16497   ProcessDeclAttributeList(S, Enum, Attrs);
16498 
16499   if (Enum->isDependentType()) {
16500     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16501       EnumConstantDecl *ECD =
16502         cast_or_null<EnumConstantDecl>(Elements[i]);
16503       if (!ECD) continue;
16504 
16505       ECD->setType(EnumType);
16506     }
16507 
16508     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16509     return;
16510   }
16511 
16512   // TODO: If the result value doesn't fit in an int, it must be a long or long
16513   // long value.  ISO C does not support this, but GCC does as an extension,
16514   // emit a warning.
16515   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16516   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16517   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16518 
16519   // Verify that all the values are okay, compute the size of the values, and
16520   // reverse the list.
16521   unsigned NumNegativeBits = 0;
16522   unsigned NumPositiveBits = 0;
16523 
16524   // Keep track of whether all elements have type int.
16525   bool AllElementsInt = true;
16526 
16527   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16528     EnumConstantDecl *ECD =
16529       cast_or_null<EnumConstantDecl>(Elements[i]);
16530     if (!ECD) continue;  // Already issued a diagnostic.
16531 
16532     const llvm::APSInt &InitVal = ECD->getInitVal();
16533 
16534     // Keep track of the size of positive and negative values.
16535     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16536       NumPositiveBits = std::max(NumPositiveBits,
16537                                  (unsigned)InitVal.getActiveBits());
16538     else
16539       NumNegativeBits = std::max(NumNegativeBits,
16540                                  (unsigned)InitVal.getMinSignedBits());
16541 
16542     // Keep track of whether every enum element has type int (very commmon).
16543     if (AllElementsInt)
16544       AllElementsInt = ECD->getType() == Context.IntTy;
16545   }
16546 
16547   // Figure out the type that should be used for this enum.
16548   QualType BestType;
16549   unsigned BestWidth;
16550 
16551   // C++0x N3000 [conv.prom]p3:
16552   //   An rvalue of an unscoped enumeration type whose underlying
16553   //   type is not fixed can be converted to an rvalue of the first
16554   //   of the following types that can represent all the values of
16555   //   the enumeration: int, unsigned int, long int, unsigned long
16556   //   int, long long int, or unsigned long long int.
16557   // C99 6.4.4.3p2:
16558   //   An identifier declared as an enumeration constant has type int.
16559   // The C99 rule is modified by a gcc extension
16560   QualType BestPromotionType;
16561 
16562   bool Packed = Enum->hasAttr<PackedAttr>();
16563   // -fshort-enums is the equivalent to specifying the packed attribute on all
16564   // enum definitions.
16565   if (LangOpts.ShortEnums)
16566     Packed = true;
16567 
16568   // If the enum already has a type because it is fixed or dictated by the
16569   // target, promote that type instead of analyzing the enumerators.
16570   if (Enum->isComplete()) {
16571     BestType = Enum->getIntegerType();
16572     if (BestType->isPromotableIntegerType())
16573       BestPromotionType = Context.getPromotedIntegerType(BestType);
16574     else
16575       BestPromotionType = BestType;
16576 
16577     BestWidth = Context.getIntWidth(BestType);
16578   }
16579   else if (NumNegativeBits) {
16580     // If there is a negative value, figure out the smallest integer type (of
16581     // int/long/longlong) that fits.
16582     // If it's packed, check also if it fits a char or a short.
16583     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16584       BestType = Context.SignedCharTy;
16585       BestWidth = CharWidth;
16586     } else if (Packed && NumNegativeBits <= ShortWidth &&
16587                NumPositiveBits < ShortWidth) {
16588       BestType = Context.ShortTy;
16589       BestWidth = ShortWidth;
16590     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16591       BestType = Context.IntTy;
16592       BestWidth = IntWidth;
16593     } else {
16594       BestWidth = Context.getTargetInfo().getLongWidth();
16595 
16596       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16597         BestType = Context.LongTy;
16598       } else {
16599         BestWidth = Context.getTargetInfo().getLongLongWidth();
16600 
16601         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16602           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16603         BestType = Context.LongLongTy;
16604       }
16605     }
16606     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16607   } else {
16608     // If there is no negative value, figure out the smallest type that fits
16609     // all of the enumerator values.
16610     // If it's packed, check also if it fits a char or a short.
16611     if (Packed && NumPositiveBits <= CharWidth) {
16612       BestType = Context.UnsignedCharTy;
16613       BestPromotionType = Context.IntTy;
16614       BestWidth = CharWidth;
16615     } else if (Packed && NumPositiveBits <= ShortWidth) {
16616       BestType = Context.UnsignedShortTy;
16617       BestPromotionType = Context.IntTy;
16618       BestWidth = ShortWidth;
16619     } else if (NumPositiveBits <= IntWidth) {
16620       BestType = Context.UnsignedIntTy;
16621       BestWidth = IntWidth;
16622       BestPromotionType
16623         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16624                            ? Context.UnsignedIntTy : Context.IntTy;
16625     } else if (NumPositiveBits <=
16626                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16627       BestType = Context.UnsignedLongTy;
16628       BestPromotionType
16629         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16630                            ? Context.UnsignedLongTy : Context.LongTy;
16631     } else {
16632       BestWidth = Context.getTargetInfo().getLongLongWidth();
16633       assert(NumPositiveBits <= BestWidth &&
16634              "How could an initializer get larger than ULL?");
16635       BestType = Context.UnsignedLongLongTy;
16636       BestPromotionType
16637         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16638                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16639     }
16640   }
16641 
16642   // Loop over all of the enumerator constants, changing their types to match
16643   // the type of the enum if needed.
16644   for (auto *D : Elements) {
16645     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16646     if (!ECD) continue;  // Already issued a diagnostic.
16647 
16648     // Standard C says the enumerators have int type, but we allow, as an
16649     // extension, the enumerators to be larger than int size.  If each
16650     // enumerator value fits in an int, type it as an int, otherwise type it the
16651     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16652     // that X has type 'int', not 'unsigned'.
16653 
16654     // Determine whether the value fits into an int.
16655     llvm::APSInt InitVal = ECD->getInitVal();
16656 
16657     // If it fits into an integer type, force it.  Otherwise force it to match
16658     // the enum decl type.
16659     QualType NewTy;
16660     unsigned NewWidth;
16661     bool NewSign;
16662     if (!getLangOpts().CPlusPlus &&
16663         !Enum->isFixed() &&
16664         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16665       NewTy = Context.IntTy;
16666       NewWidth = IntWidth;
16667       NewSign = true;
16668     } else if (ECD->getType() == BestType) {
16669       // Already the right type!
16670       if (getLangOpts().CPlusPlus)
16671         // C++ [dcl.enum]p4: Following the closing brace of an
16672         // enum-specifier, each enumerator has the type of its
16673         // enumeration.
16674         ECD->setType(EnumType);
16675       continue;
16676     } else {
16677       NewTy = BestType;
16678       NewWidth = BestWidth;
16679       NewSign = BestType->isSignedIntegerOrEnumerationType();
16680     }
16681 
16682     // Adjust the APSInt value.
16683     InitVal = InitVal.extOrTrunc(NewWidth);
16684     InitVal.setIsSigned(NewSign);
16685     ECD->setInitVal(InitVal);
16686 
16687     // Adjust the Expr initializer and type.
16688     if (ECD->getInitExpr() &&
16689         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16690       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16691                                                 CK_IntegralCast,
16692                                                 ECD->getInitExpr(),
16693                                                 /*base paths*/ nullptr,
16694                                                 VK_RValue));
16695     if (getLangOpts().CPlusPlus)
16696       // C++ [dcl.enum]p4: Following the closing brace of an
16697       // enum-specifier, each enumerator has the type of its
16698       // enumeration.
16699       ECD->setType(EnumType);
16700     else
16701       ECD->setType(NewTy);
16702   }
16703 
16704   Enum->completeDefinition(BestType, BestPromotionType,
16705                            NumPositiveBits, NumNegativeBits);
16706 
16707   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16708 
16709   if (Enum->isClosedFlag()) {
16710     for (Decl *D : Elements) {
16711       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16712       if (!ECD) continue;  // Already issued a diagnostic.
16713 
16714       llvm::APSInt InitVal = ECD->getInitVal();
16715       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16716           !IsValueInFlagEnum(Enum, InitVal, true))
16717         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16718           << ECD << Enum;
16719     }
16720   }
16721 
16722   // Now that the enum type is defined, ensure it's not been underaligned.
16723   if (Enum->hasAttrs())
16724     CheckAlignasUnderalignment(Enum);
16725 }
16726 
16727 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16728                                   SourceLocation StartLoc,
16729                                   SourceLocation EndLoc) {
16730   StringLiteral *AsmString = cast<StringLiteral>(expr);
16731 
16732   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16733                                                    AsmString, StartLoc,
16734                                                    EndLoc);
16735   CurContext->addDecl(New);
16736   return New;
16737 }
16738 
16739 static void checkModuleImportContext(Sema &S, Module *M,
16740                                      SourceLocation ImportLoc, DeclContext *DC,
16741                                      bool FromInclude = false) {
16742   SourceLocation ExternCLoc;
16743 
16744   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16745     switch (LSD->getLanguage()) {
16746     case LinkageSpecDecl::lang_c:
16747       if (ExternCLoc.isInvalid())
16748         ExternCLoc = LSD->getBeginLoc();
16749       break;
16750     case LinkageSpecDecl::lang_cxx:
16751       break;
16752     }
16753     DC = LSD->getParent();
16754   }
16755 
16756   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16757     DC = DC->getParent();
16758 
16759   if (!isa<TranslationUnitDecl>(DC)) {
16760     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16761                           ? diag::ext_module_import_not_at_top_level_noop
16762                           : diag::err_module_import_not_at_top_level_fatal)
16763         << M->getFullModuleName() << DC;
16764     S.Diag(cast<Decl>(DC)->getBeginLoc(),
16765            diag::note_module_import_not_at_top_level)
16766         << DC;
16767   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16768     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16769       << M->getFullModuleName();
16770     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16771   }
16772 }
16773 
16774 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16775                                            SourceLocation ModuleLoc,
16776                                            ModuleDeclKind MDK,
16777                                            ModuleIdPath Path) {
16778   assert(getLangOpts().ModulesTS &&
16779          "should only have module decl in modules TS");
16780 
16781   // A module implementation unit requires that we are not compiling a module
16782   // of any kind. A module interface unit requires that we are not compiling a
16783   // module map.
16784   switch (getLangOpts().getCompilingModule()) {
16785   case LangOptions::CMK_None:
16786     // It's OK to compile a module interface as a normal translation unit.
16787     break;
16788 
16789   case LangOptions::CMK_ModuleInterface:
16790     if (MDK != ModuleDeclKind::Implementation)
16791       break;
16792 
16793     // We were asked to compile a module interface unit but this is a module
16794     // implementation unit. That indicates the 'export' is missing.
16795     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16796       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16797     MDK = ModuleDeclKind::Interface;
16798     break;
16799 
16800   case LangOptions::CMK_ModuleMap:
16801     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16802     return nullptr;
16803   }
16804 
16805   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16806 
16807   // FIXME: Most of this work should be done by the preprocessor rather than
16808   // here, in order to support macro import.
16809 
16810   // Only one module-declaration is permitted per source file.
16811   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16812     Diag(ModuleLoc, diag::err_module_redeclaration);
16813     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16814          diag::note_prev_module_declaration);
16815     return nullptr;
16816   }
16817 
16818   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16819   // modules, the dots here are just another character that can appear in a
16820   // module name.
16821   std::string ModuleName;
16822   for (auto &Piece : Path) {
16823     if (!ModuleName.empty())
16824       ModuleName += ".";
16825     ModuleName += Piece.first->getName();
16826   }
16827 
16828   // If a module name was explicitly specified on the command line, it must be
16829   // correct.
16830   if (!getLangOpts().CurrentModule.empty() &&
16831       getLangOpts().CurrentModule != ModuleName) {
16832     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16833         << SourceRange(Path.front().second, Path.back().second)
16834         << getLangOpts().CurrentModule;
16835     return nullptr;
16836   }
16837   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16838 
16839   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16840   Module *Mod;
16841 
16842   switch (MDK) {
16843   case ModuleDeclKind::Interface: {
16844     // We can't have parsed or imported a definition of this module or parsed a
16845     // module map defining it already.
16846     if (auto *M = Map.findModule(ModuleName)) {
16847       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16848       if (M->DefinitionLoc.isValid())
16849         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16850       else if (const auto *FE = M->getASTFile())
16851         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16852             << FE->getName();
16853       Mod = M;
16854       break;
16855     }
16856 
16857     // Create a Module for the module that we're defining.
16858     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16859                                            ModuleScopes.front().Module);
16860     assert(Mod && "module creation should not fail");
16861     break;
16862   }
16863 
16864   case ModuleDeclKind::Partition:
16865     // FIXME: Check we are in a submodule of the named module.
16866     return nullptr;
16867 
16868   case ModuleDeclKind::Implementation:
16869     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16870         PP.getIdentifierInfo(ModuleName), Path[0].second);
16871     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16872                                        /*IsIncludeDirective=*/false);
16873     if (!Mod) {
16874       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16875       // Create an empty module interface unit for error recovery.
16876       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16877                                              ModuleScopes.front().Module);
16878     }
16879     break;
16880   }
16881 
16882   // Switch from the global module to the named module.
16883   ModuleScopes.back().Module = Mod;
16884   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16885   VisibleModules.setVisible(Mod, ModuleLoc);
16886 
16887   // From now on, we have an owning module for all declarations we see.
16888   // However, those declarations are module-private unless explicitly
16889   // exported.
16890   auto *TU = Context.getTranslationUnitDecl();
16891   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16892   TU->setLocalOwningModule(Mod);
16893 
16894   // FIXME: Create a ModuleDecl.
16895   return nullptr;
16896 }
16897 
16898 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16899                                    SourceLocation ImportLoc,
16900                                    ModuleIdPath Path) {
16901   Module *Mod =
16902       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16903                                    /*IsIncludeDirective=*/false);
16904   if (!Mod)
16905     return true;
16906 
16907   VisibleModules.setVisible(Mod, ImportLoc);
16908 
16909   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16910 
16911   // FIXME: we should support importing a submodule within a different submodule
16912   // of the same top-level module. Until we do, make it an error rather than
16913   // silently ignoring the import.
16914   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16915   // warn on a redundant import of the current module?
16916   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16917       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16918     Diag(ImportLoc, getLangOpts().isCompilingModule()
16919                         ? diag::err_module_self_import
16920                         : diag::err_module_import_in_implementation)
16921         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16922 
16923   SmallVector<SourceLocation, 2> IdentifierLocs;
16924   Module *ModCheck = Mod;
16925   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16926     // If we've run out of module parents, just drop the remaining identifiers.
16927     // We need the length to be consistent.
16928     if (!ModCheck)
16929       break;
16930     ModCheck = ModCheck->Parent;
16931 
16932     IdentifierLocs.push_back(Path[I].second);
16933   }
16934 
16935   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16936                                           Mod, IdentifierLocs);
16937   if (!ModuleScopes.empty())
16938     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16939   CurContext->addDecl(Import);
16940 
16941   // Re-export the module if needed.
16942   if (Import->isExported() &&
16943       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16944     getCurrentModule()->Exports.emplace_back(Mod, false);
16945 
16946   return Import;
16947 }
16948 
16949 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16950   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16951   BuildModuleInclude(DirectiveLoc, Mod);
16952 }
16953 
16954 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16955   // Determine whether we're in the #include buffer for a module. The #includes
16956   // in that buffer do not qualify as module imports; they're just an
16957   // implementation detail of us building the module.
16958   //
16959   // FIXME: Should we even get ActOnModuleInclude calls for those?
16960   bool IsInModuleIncludes =
16961       TUKind == TU_Module &&
16962       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16963 
16964   bool ShouldAddImport = !IsInModuleIncludes;
16965 
16966   // If this module import was due to an inclusion directive, create an
16967   // implicit import declaration to capture it in the AST.
16968   if (ShouldAddImport) {
16969     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16970     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16971                                                      DirectiveLoc, Mod,
16972                                                      DirectiveLoc);
16973     if (!ModuleScopes.empty())
16974       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16975     TU->addDecl(ImportD);
16976     Consumer.HandleImplicitImportDecl(ImportD);
16977   }
16978 
16979   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16980   VisibleModules.setVisible(Mod, DirectiveLoc);
16981 }
16982 
16983 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16984   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16985 
16986   ModuleScopes.push_back({});
16987   ModuleScopes.back().Module = Mod;
16988   if (getLangOpts().ModulesLocalVisibility)
16989     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16990 
16991   VisibleModules.setVisible(Mod, DirectiveLoc);
16992 
16993   // The enclosing context is now part of this module.
16994   // FIXME: Consider creating a child DeclContext to hold the entities
16995   // lexically within the module.
16996   if (getLangOpts().trackLocalOwningModule()) {
16997     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16998       cast<Decl>(DC)->setModuleOwnershipKind(
16999           getLangOpts().ModulesLocalVisibility
17000               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17001               : Decl::ModuleOwnershipKind::Visible);
17002       cast<Decl>(DC)->setLocalOwningModule(Mod);
17003     }
17004   }
17005 }
17006 
17007 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17008   if (getLangOpts().ModulesLocalVisibility) {
17009     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17010     // Leaving a module hides namespace names, so our visible namespace cache
17011     // is now out of date.
17012     VisibleNamespaceCache.clear();
17013   }
17014 
17015   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17016          "left the wrong module scope");
17017   ModuleScopes.pop_back();
17018 
17019   // We got to the end of processing a local module. Create an
17020   // ImportDecl as we would for an imported module.
17021   FileID File = getSourceManager().getFileID(EomLoc);
17022   SourceLocation DirectiveLoc;
17023   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17024     // We reached the end of a #included module header. Use the #include loc.
17025     assert(File != getSourceManager().getMainFileID() &&
17026            "end of submodule in main source file");
17027     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17028   } else {
17029     // We reached an EOM pragma. Use the pragma location.
17030     DirectiveLoc = EomLoc;
17031   }
17032   BuildModuleInclude(DirectiveLoc, Mod);
17033 
17034   // Any further declarations are in whatever module we returned to.
17035   if (getLangOpts().trackLocalOwningModule()) {
17036     // The parser guarantees that this is the same context that we entered
17037     // the module within.
17038     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17039       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17040       if (!getCurrentModule())
17041         cast<Decl>(DC)->setModuleOwnershipKind(
17042             Decl::ModuleOwnershipKind::Unowned);
17043     }
17044   }
17045 }
17046 
17047 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17048                                                       Module *Mod) {
17049   // Bail if we're not allowed to implicitly import a module here.
17050   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17051       VisibleModules.isVisible(Mod))
17052     return;
17053 
17054   // Create the implicit import declaration.
17055   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17056   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17057                                                    Loc, Mod, Loc);
17058   TU->addDecl(ImportD);
17059   Consumer.HandleImplicitImportDecl(ImportD);
17060 
17061   // Make the module visible.
17062   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17063   VisibleModules.setVisible(Mod, Loc);
17064 }
17065 
17066 /// We have parsed the start of an export declaration, including the '{'
17067 /// (if present).
17068 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17069                                  SourceLocation LBraceLoc) {
17070   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17071 
17072   // C++ Modules TS draft:
17073   //   An export-declaration shall appear in the purview of a module other than
17074   //   the global module.
17075   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17076     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17077 
17078   //   An export-declaration [...] shall not contain more than one
17079   //   export keyword.
17080   //
17081   // The intent here is that an export-declaration cannot appear within another
17082   // export-declaration.
17083   if (D->isExported())
17084     Diag(ExportLoc, diag::err_export_within_export);
17085 
17086   CurContext->addDecl(D);
17087   PushDeclContext(S, D);
17088   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17089   return D;
17090 }
17091 
17092 /// Complete the definition of an export declaration.
17093 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17094   auto *ED = cast<ExportDecl>(D);
17095   if (RBraceLoc.isValid())
17096     ED->setRBraceLoc(RBraceLoc);
17097 
17098   // FIXME: Diagnose export of internal-linkage declaration (including
17099   // anonymous namespace).
17100 
17101   PopDeclContext();
17102   return D;
17103 }
17104 
17105 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17106                                       IdentifierInfo* AliasName,
17107                                       SourceLocation PragmaLoc,
17108                                       SourceLocation NameLoc,
17109                                       SourceLocation AliasNameLoc) {
17110   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17111                                          LookupOrdinaryName);
17112   AsmLabelAttr *Attr =
17113       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17114 
17115   // If a declaration that:
17116   // 1) declares a function or a variable
17117   // 2) has external linkage
17118   // already exists, add a label attribute to it.
17119   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17120     if (isDeclExternC(PrevDecl))
17121       PrevDecl->addAttr(Attr);
17122     else
17123       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17124           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17125   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17126   } else
17127     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17128 }
17129 
17130 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17131                              SourceLocation PragmaLoc,
17132                              SourceLocation NameLoc) {
17133   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17134 
17135   if (PrevDecl) {
17136     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17137   } else {
17138     (void)WeakUndeclaredIdentifiers.insert(
17139       std::pair<IdentifierInfo*,WeakInfo>
17140         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17141   }
17142 }
17143 
17144 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17145                                 IdentifierInfo* AliasName,
17146                                 SourceLocation PragmaLoc,
17147                                 SourceLocation NameLoc,
17148                                 SourceLocation AliasNameLoc) {
17149   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17150                                     LookupOrdinaryName);
17151   WeakInfo W = WeakInfo(Name, NameLoc);
17152 
17153   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17154     if (!PrevDecl->hasAttr<AliasAttr>())
17155       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17156         DeclApplyPragmaWeak(TUScope, ND, W);
17157   } else {
17158     (void)WeakUndeclaredIdentifiers.insert(
17159       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17160   }
17161 }
17162 
17163 Decl *Sema::getObjCDeclContext() const {
17164   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17165 }
17166