1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/CommentDiagnostic.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/Basic/Builtins.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaInternal.h"
43 #include "clang/Sema/Template.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Triple.h"
46 #include <algorithm>
47 #include <cstring>
48 #include <functional>
49 
50 using namespace clang;
51 using namespace sema;
52 
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58 
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
67                         bool AllowTemplates = false,
68                         bool AllowNonTemplates = true)
69        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
71      WantExpressionKeywords = false;
72      WantCXXNamedCasts = false;
73      WantRemainingKeywords = false;
74   }
75 
76   bool ValidateCandidate(const TypoCorrection &candidate) override {
77     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78       if (!AllowInvalidDecl && ND->isInvalidDecl())
79         return false;
80 
81       if (getAsTypeTemplateDecl(ND))
82         return AllowTemplates;
83 
84       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
85       if (!IsType)
86         return false;
87 
88       if (AllowNonTemplates)
89         return true;
90 
91       // An injected-class-name of a class template (specialization) is valid
92       // as a template or as a non-template.
93       if (AllowTemplates) {
94         auto *RD = dyn_cast<CXXRecordDecl>(ND);
95         if (!RD || !RD->isInjectedClassName())
96           return false;
97         RD = cast<CXXRecordDecl>(RD->getDeclContext());
98         return RD->getDescribedClassTemplate() ||
99                isa<ClassTemplateSpecializationDecl>(RD);
100       }
101 
102       return false;
103     }
104 
105     return !WantClassName && candidate.isKeyword();
106   }
107 
108  private:
109   bool AllowInvalidDecl;
110   bool WantClassName;
111   bool AllowTemplates;
112   bool AllowNonTemplates;
113 };
114 
115 } // end anonymous namespace
116 
117 /// Determine whether the token kind starts a simple-type-specifier.
118 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
119   switch (Kind) {
120   // FIXME: Take into account the current language when deciding whether a
121   // token kind is a valid type specifier
122   case tok::kw_short:
123   case tok::kw_long:
124   case tok::kw___int64:
125   case tok::kw___int128:
126   case tok::kw_signed:
127   case tok::kw_unsigned:
128   case tok::kw_void:
129   case tok::kw_char:
130   case tok::kw_int:
131   case tok::kw_half:
132   case tok::kw_float:
133   case tok::kw_double:
134   case tok::kw__Float16:
135   case tok::kw___float128:
136   case tok::kw_wchar_t:
137   case tok::kw_bool:
138   case tok::kw___underlying_type:
139   case tok::kw___auto_type:
140     return true;
141 
142   case tok::annot_typename:
143   case tok::kw_char16_t:
144   case tok::kw_char32_t:
145   case tok::kw_typeof:
146   case tok::annot_decltype:
147   case tok::kw_decltype:
148     return getLangOpts().CPlusPlus;
149 
150   case tok::kw_char8_t:
151     return getLangOpts().Char8;
152 
153   default:
154     break;
155   }
156 
157   return false;
158 }
159 
160 namespace {
161 enum class UnqualifiedTypeNameLookupResult {
162   NotFound,
163   FoundNonType,
164   FoundType
165 };
166 } // end anonymous namespace
167 
168 /// Tries to perform unqualified lookup of the type decls in bases for
169 /// dependent class.
170 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
171 /// type decl, \a FoundType if only type decls are found.
172 static UnqualifiedTypeNameLookupResult
173 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
174                                 SourceLocation NameLoc,
175                                 const CXXRecordDecl *RD) {
176   if (!RD->hasDefinition())
177     return UnqualifiedTypeNameLookupResult::NotFound;
178   // Look for type decls in base classes.
179   UnqualifiedTypeNameLookupResult FoundTypeDecl =
180       UnqualifiedTypeNameLookupResult::NotFound;
181   for (const auto &Base : RD->bases()) {
182     const CXXRecordDecl *BaseRD = nullptr;
183     if (auto *BaseTT = Base.getType()->getAs<TagType>())
184       BaseRD = BaseTT->getAsCXXRecordDecl();
185     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
186       // Look for type decls in dependent base classes that have known primary
187       // templates.
188       if (!TST || !TST->isDependentType())
189         continue;
190       auto *TD = TST->getTemplateName().getAsTemplateDecl();
191       if (!TD)
192         continue;
193       if (auto *BasePrimaryTemplate =
194           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
195         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
196           BaseRD = BasePrimaryTemplate;
197         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
198           if (const ClassTemplatePartialSpecializationDecl *PS =
199                   CTD->findPartialSpecialization(Base.getType()))
200             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
201               BaseRD = PS;
202         }
203       }
204     }
205     if (BaseRD) {
206       for (NamedDecl *ND : BaseRD->lookup(&II)) {
207         if (!isa<TypeDecl>(ND))
208           return UnqualifiedTypeNameLookupResult::FoundNonType;
209         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
210       }
211       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
212         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
213         case UnqualifiedTypeNameLookupResult::FoundNonType:
214           return UnqualifiedTypeNameLookupResult::FoundNonType;
215         case UnqualifiedTypeNameLookupResult::FoundType:
216           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
217           break;
218         case UnqualifiedTypeNameLookupResult::NotFound:
219           break;
220         }
221       }
222     }
223   }
224 
225   return FoundTypeDecl;
226 }
227 
228 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
229                                                       const IdentifierInfo &II,
230                                                       SourceLocation NameLoc) {
231   // Lookup in the parent class template context, if any.
232   const CXXRecordDecl *RD = nullptr;
233   UnqualifiedTypeNameLookupResult FoundTypeDecl =
234       UnqualifiedTypeNameLookupResult::NotFound;
235   for (DeclContext *DC = S.CurContext;
236        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
237        DC = DC->getParent()) {
238     // Look for type decls in dependent base classes that have known primary
239     // templates.
240     RD = dyn_cast<CXXRecordDecl>(DC);
241     if (RD && RD->getDescribedClassTemplate())
242       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
243   }
244   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
245     return nullptr;
246 
247   // We found some types in dependent base classes.  Recover as if the user
248   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
249   // lookup during template instantiation.
250   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
251 
252   ASTContext &Context = S.Context;
253   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
254                                           cast<Type>(Context.getRecordType(RD)));
255   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
256 
257   CXXScopeSpec SS;
258   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
259 
260   TypeLocBuilder Builder;
261   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
262   DepTL.setNameLoc(NameLoc);
263   DepTL.setElaboratedKeywordLoc(SourceLocation());
264   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
265   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
266 }
267 
268 /// If the identifier refers to a type name within this scope,
269 /// return the declaration of that type.
270 ///
271 /// This routine performs ordinary name lookup of the identifier II
272 /// within the given scope, with optional C++ scope specifier SS, to
273 /// determine whether the name refers to a type. If so, returns an
274 /// opaque pointer (actually a QualType) corresponding to that
275 /// type. Otherwise, returns NULL.
276 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
277                              Scope *S, CXXScopeSpec *SS,
278                              bool isClassName, bool HasTrailingDot,
279                              ParsedType ObjectTypePtr,
280                              bool IsCtorOrDtorName,
281                              bool WantNontrivialTypeSourceInfo,
282                              bool IsClassTemplateDeductionContext,
283                              IdentifierInfo **CorrectedII) {
284   // FIXME: Consider allowing this outside C++1z mode as an extension.
285   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
286                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
287                               !isClassName && !HasTrailingDot;
288 
289   // Determine where we will perform name lookup.
290   DeclContext *LookupCtx = nullptr;
291   if (ObjectTypePtr) {
292     QualType ObjectType = ObjectTypePtr.get();
293     if (ObjectType->isRecordType())
294       LookupCtx = computeDeclContext(ObjectType);
295   } else if (SS && SS->isNotEmpty()) {
296     LookupCtx = computeDeclContext(*SS, false);
297 
298     if (!LookupCtx) {
299       if (isDependentScopeSpecifier(*SS)) {
300         // C++ [temp.res]p3:
301         //   A qualified-id that refers to a type and in which the
302         //   nested-name-specifier depends on a template-parameter (14.6.2)
303         //   shall be prefixed by the keyword typename to indicate that the
304         //   qualified-id denotes a type, forming an
305         //   elaborated-type-specifier (7.1.5.3).
306         //
307         // We therefore do not perform any name lookup if the result would
308         // refer to a member of an unknown specialization.
309         if (!isClassName && !IsCtorOrDtorName)
310           return nullptr;
311 
312         // We know from the grammar that this name refers to a type,
313         // so build a dependent node to describe the type.
314         if (WantNontrivialTypeSourceInfo)
315           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
316 
317         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
318         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
319                                        II, NameLoc);
320         return ParsedType::make(T);
321       }
322 
323       return nullptr;
324     }
325 
326     if (!LookupCtx->isDependentContext() &&
327         RequireCompleteDeclContext(*SS, LookupCtx))
328       return nullptr;
329   }
330 
331   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
332   // lookup for class-names.
333   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
334                                       LookupOrdinaryName;
335   LookupResult Result(*this, &II, NameLoc, Kind);
336   if (LookupCtx) {
337     // Perform "qualified" name lookup into the declaration context we
338     // computed, which is either the type of the base of a member access
339     // expression or the declaration context associated with a prior
340     // nested-name-specifier.
341     LookupQualifiedName(Result, LookupCtx);
342 
343     if (ObjectTypePtr && Result.empty()) {
344       // C++ [basic.lookup.classref]p3:
345       //   If the unqualified-id is ~type-name, the type-name is looked up
346       //   in the context of the entire postfix-expression. If the type T of
347       //   the object expression is of a class type C, the type-name is also
348       //   looked up in the scope of class C. At least one of the lookups shall
349       //   find a name that refers to (possibly cv-qualified) T.
350       LookupName(Result, S);
351     }
352   } else {
353     // Perform unqualified name lookup.
354     LookupName(Result, S);
355 
356     // For unqualified lookup in a class template in MSVC mode, look into
357     // dependent base classes where the primary class template is known.
358     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
359       if (ParsedType TypeInBase =
360               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
361         return TypeInBase;
362     }
363   }
364 
365   NamedDecl *IIDecl = nullptr;
366   switch (Result.getResultKind()) {
367   case LookupResult::NotFound:
368   case LookupResult::NotFoundInCurrentInstantiation:
369     if (CorrectedII) {
370       TypoCorrection Correction =
371           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
372                       llvm::make_unique<TypeNameValidatorCCC>(
373                           true, isClassName, AllowDeducedTemplate),
374                       CTK_ErrorRecovery);
375       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
376       TemplateTy Template;
377       bool MemberOfUnknownSpecialization;
378       UnqualifiedId TemplateName;
379       TemplateName.setIdentifier(NewII, NameLoc);
380       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
381       CXXScopeSpec NewSS, *NewSSPtr = SS;
382       if (SS && NNS) {
383         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
384         NewSSPtr = &NewSS;
385       }
386       if (Correction && (NNS || NewII != &II) &&
387           // Ignore a correction to a template type as the to-be-corrected
388           // identifier is not a template (typo correction for template names
389           // is handled elsewhere).
390           !(getLangOpts().CPlusPlus && NewSSPtr &&
391             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
392                            Template, MemberOfUnknownSpecialization))) {
393         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
394                                     isClassName, HasTrailingDot, ObjectTypePtr,
395                                     IsCtorOrDtorName,
396                                     WantNontrivialTypeSourceInfo,
397                                     IsClassTemplateDeductionContext);
398         if (Ty) {
399           diagnoseTypo(Correction,
400                        PDiag(diag::err_unknown_type_or_class_name_suggest)
401                          << Result.getLookupName() << isClassName);
402           if (SS && NNS)
403             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
404           *CorrectedII = NewII;
405           return Ty;
406         }
407       }
408     }
409     // If typo correction failed or was not performed, fall through
410     LLVM_FALLTHROUGH;
411   case LookupResult::FoundOverloaded:
412   case LookupResult::FoundUnresolvedValue:
413     Result.suppressDiagnostics();
414     return nullptr;
415 
416   case LookupResult::Ambiguous:
417     // Recover from type-hiding ambiguities by hiding the type.  We'll
418     // do the lookup again when looking for an object, and we can
419     // diagnose the error then.  If we don't do this, then the error
420     // about hiding the type will be immediately followed by an error
421     // that only makes sense if the identifier was treated like a type.
422     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
423       Result.suppressDiagnostics();
424       return nullptr;
425     }
426 
427     // Look to see if we have a type anywhere in the list of results.
428     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
429          Res != ResEnd; ++Res) {
430       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
431           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
432         if (!IIDecl ||
433             (*Res)->getLocation().getRawEncoding() <
434               IIDecl->getLocation().getRawEncoding())
435           IIDecl = *Res;
436       }
437     }
438 
439     if (!IIDecl) {
440       // None of the entities we found is a type, so there is no way
441       // to even assume that the result is a type. In this case, don't
442       // complain about the ambiguity. The parser will either try to
443       // perform this lookup again (e.g., as an object name), which
444       // will produce the ambiguity, or will complain that it expected
445       // a type name.
446       Result.suppressDiagnostics();
447       return nullptr;
448     }
449 
450     // We found a type within the ambiguous lookup; diagnose the
451     // ambiguity and then return that type. This might be the right
452     // answer, or it might not be, but it suppresses any attempt to
453     // perform the name lookup again.
454     break;
455 
456   case LookupResult::Found:
457     IIDecl = Result.getFoundDecl();
458     break;
459   }
460 
461   assert(IIDecl && "Didn't find decl");
462 
463   QualType T;
464   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
465     // C++ [class.qual]p2: A lookup that would find the injected-class-name
466     // instead names the constructors of the class, except when naming a class.
467     // This is ill-formed when we're not actually forming a ctor or dtor name.
468     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
469     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
470     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
471         FoundRD->isInjectedClassName() &&
472         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
473       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
474           << &II << /*Type*/1;
475 
476     DiagnoseUseOfDecl(IIDecl, NameLoc);
477 
478     T = Context.getTypeDeclType(TD);
479     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
480   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
481     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
482     if (!HasTrailingDot)
483       T = Context.getObjCInterfaceType(IDecl);
484   } else if (AllowDeducedTemplate) {
485     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
486       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
487                                                        QualType(), false);
488   }
489 
490   if (T.isNull()) {
491     // If it's not plausibly a type, suppress diagnostics.
492     Result.suppressDiagnostics();
493     return nullptr;
494   }
495 
496   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
497   // constructor or destructor name (in such a case, the scope specifier
498   // will be attached to the enclosing Expr or Decl node).
499   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
500       !isa<ObjCInterfaceDecl>(IIDecl)) {
501     if (WantNontrivialTypeSourceInfo) {
502       // Construct a type with type-source information.
503       TypeLocBuilder Builder;
504       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
505 
506       T = getElaboratedType(ETK_None, *SS, T);
507       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
508       ElabTL.setElaboratedKeywordLoc(SourceLocation());
509       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
510       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
511     } else {
512       T = getElaboratedType(ETK_None, *SS, T);
513     }
514   }
515 
516   return ParsedType::make(T);
517 }
518 
519 // Builds a fake NNS for the given decl context.
520 static NestedNameSpecifier *
521 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
522   for (;; DC = DC->getLookupParent()) {
523     DC = DC->getPrimaryContext();
524     auto *ND = dyn_cast<NamespaceDecl>(DC);
525     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
526       return NestedNameSpecifier::Create(Context, nullptr, ND);
527     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
528       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
529                                          RD->getTypeForDecl());
530     else if (isa<TranslationUnitDecl>(DC))
531       return NestedNameSpecifier::GlobalSpecifier(Context);
532   }
533   llvm_unreachable("something isn't in TU scope?");
534 }
535 
536 /// Find the parent class with dependent bases of the innermost enclosing method
537 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
538 /// up allowing unqualified dependent type names at class-level, which MSVC
539 /// correctly rejects.
540 static const CXXRecordDecl *
541 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
542   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
543     DC = DC->getPrimaryContext();
544     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
545       if (MD->getParent()->hasAnyDependentBases())
546         return MD->getParent();
547   }
548   return nullptr;
549 }
550 
551 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
552                                           SourceLocation NameLoc,
553                                           bool IsTemplateTypeArg) {
554   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
555 
556   NestedNameSpecifier *NNS = nullptr;
557   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
558     // If we weren't able to parse a default template argument, delay lookup
559     // until instantiation time by making a non-dependent DependentTypeName. We
560     // pretend we saw a NestedNameSpecifier referring to the current scope, and
561     // lookup is retried.
562     // FIXME: This hurts our diagnostic quality, since we get errors like "no
563     // type named 'Foo' in 'current_namespace'" when the user didn't write any
564     // name specifiers.
565     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
566     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
567   } else if (const CXXRecordDecl *RD =
568                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
569     // Build a DependentNameType that will perform lookup into RD at
570     // instantiation time.
571     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
572                                       RD->getTypeForDecl());
573 
574     // Diagnose that this identifier was undeclared, and retry the lookup during
575     // template instantiation.
576     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
577                                                                       << RD;
578   } else {
579     // This is not a situation that we should recover from.
580     return ParsedType();
581   }
582 
583   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
584 
585   // Build type location information.  We synthesized the qualifier, so we have
586   // to build a fake NestedNameSpecifierLoc.
587   NestedNameSpecifierLocBuilder NNSLocBuilder;
588   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
589   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
590 
591   TypeLocBuilder Builder;
592   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
593   DepTL.setNameLoc(NameLoc);
594   DepTL.setElaboratedKeywordLoc(SourceLocation());
595   DepTL.setQualifierLoc(QualifierLoc);
596   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
597 }
598 
599 /// isTagName() - This method is called *for error recovery purposes only*
600 /// to determine if the specified name is a valid tag name ("struct foo").  If
601 /// so, this returns the TST for the tag corresponding to it (TST_enum,
602 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
603 /// cases in C where the user forgot to specify the tag.
604 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
605   // Do a tag name lookup in this scope.
606   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
607   LookupName(R, S, false);
608   R.suppressDiagnostics();
609   if (R.getResultKind() == LookupResult::Found)
610     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
611       switch (TD->getTagKind()) {
612       case TTK_Struct: return DeclSpec::TST_struct;
613       case TTK_Interface: return DeclSpec::TST_interface;
614       case TTK_Union:  return DeclSpec::TST_union;
615       case TTK_Class:  return DeclSpec::TST_class;
616       case TTK_Enum:   return DeclSpec::TST_enum;
617       }
618     }
619 
620   return DeclSpec::TST_unspecified;
621 }
622 
623 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
624 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
625 /// then downgrade the missing typename error to a warning.
626 /// This is needed for MSVC compatibility; Example:
627 /// @code
628 /// template<class T> class A {
629 /// public:
630 ///   typedef int TYPE;
631 /// };
632 /// template<class T> class B : public A<T> {
633 /// public:
634 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
635 /// };
636 /// @endcode
637 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
638   if (CurContext->isRecord()) {
639     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
640       return true;
641 
642     const Type *Ty = SS->getScopeRep()->getAsType();
643 
644     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
645     for (const auto &Base : RD->bases())
646       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
647         return true;
648     return S->isFunctionPrototypeScope();
649   }
650   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
651 }
652 
653 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
654                                    SourceLocation IILoc,
655                                    Scope *S,
656                                    CXXScopeSpec *SS,
657                                    ParsedType &SuggestedType,
658                                    bool IsTemplateName) {
659   // Don't report typename errors for editor placeholders.
660   if (II->isEditorPlaceholder())
661     return;
662   // We don't have anything to suggest (yet).
663   SuggestedType = nullptr;
664 
665   // There may have been a typo in the name of the type. Look up typo
666   // results, in case we have something that we can suggest.
667   if (TypoCorrection Corrected =
668           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
669                       llvm::make_unique<TypeNameValidatorCCC>(
670                           false, false, IsTemplateName, !IsTemplateName),
671                       CTK_ErrorRecovery)) {
672     // FIXME: Support error recovery for the template-name case.
673     bool CanRecover = !IsTemplateName;
674     if (Corrected.isKeyword()) {
675       // We corrected to a keyword.
676       diagnoseTypo(Corrected,
677                    PDiag(IsTemplateName ? diag::err_no_template_suggest
678                                         : diag::err_unknown_typename_suggest)
679                        << II);
680       II = Corrected.getCorrectionAsIdentifierInfo();
681     } else {
682       // We found a similarly-named type or interface; suggest that.
683       if (!SS || !SS->isSet()) {
684         diagnoseTypo(Corrected,
685                      PDiag(IsTemplateName ? diag::err_no_template_suggest
686                                           : diag::err_unknown_typename_suggest)
687                          << II, CanRecover);
688       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
689         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
690         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
691                                 II->getName().equals(CorrectedStr);
692         diagnoseTypo(Corrected,
693                      PDiag(IsTemplateName
694                                ? diag::err_no_member_template_suggest
695                                : diag::err_unknown_nested_typename_suggest)
696                          << II << DC << DroppedSpecifier << SS->getRange(),
697                      CanRecover);
698       } else {
699         llvm_unreachable("could not have corrected a typo here");
700       }
701 
702       if (!CanRecover)
703         return;
704 
705       CXXScopeSpec tmpSS;
706       if (Corrected.getCorrectionSpecifier())
707         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
708                           SourceRange(IILoc));
709       // FIXME: Support class template argument deduction here.
710       SuggestedType =
711           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
712                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
713                       /*IsCtorOrDtorName=*/false,
714                       /*NonTrivialTypeSourceInfo=*/true);
715     }
716     return;
717   }
718 
719   if (getLangOpts().CPlusPlus && !IsTemplateName) {
720     // See if II is a class template that the user forgot to pass arguments to.
721     UnqualifiedId Name;
722     Name.setIdentifier(II, IILoc);
723     CXXScopeSpec EmptySS;
724     TemplateTy TemplateResult;
725     bool MemberOfUnknownSpecialization;
726     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
727                        Name, nullptr, true, TemplateResult,
728                        MemberOfUnknownSpecialization) == TNK_Type_template) {
729       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
730       return;
731     }
732   }
733 
734   // FIXME: Should we move the logic that tries to recover from a missing tag
735   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
736 
737   if (!SS || (!SS->isSet() && !SS->isInvalid()))
738     Diag(IILoc, IsTemplateName ? diag::err_no_template
739                                : diag::err_unknown_typename)
740         << II;
741   else if (DeclContext *DC = computeDeclContext(*SS, false))
742     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
743                                : diag::err_typename_nested_not_found)
744         << II << DC << SS->getRange();
745   else if (isDependentScopeSpecifier(*SS)) {
746     unsigned DiagID = diag::err_typename_missing;
747     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
748       DiagID = diag::ext_typename_missing;
749 
750     Diag(SS->getRange().getBegin(), DiagID)
751       << SS->getScopeRep() << II->getName()
752       << SourceRange(SS->getRange().getBegin(), IILoc)
753       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
754     SuggestedType = ActOnTypenameType(S, SourceLocation(),
755                                       *SS, *II, IILoc).get();
756   } else {
757     assert(SS && SS->isInvalid() &&
758            "Invalid scope specifier has already been diagnosed");
759   }
760 }
761 
762 /// Determine whether the given result set contains either a type name
763 /// or
764 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
765   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
766                        NextToken.is(tok::less);
767 
768   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
769     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
770       return true;
771 
772     if (CheckTemplate && isa<TemplateDecl>(*I))
773       return true;
774   }
775 
776   return false;
777 }
778 
779 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
780                                     Scope *S, CXXScopeSpec &SS,
781                                     IdentifierInfo *&Name,
782                                     SourceLocation NameLoc) {
783   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
784   SemaRef.LookupParsedName(R, S, &SS);
785   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
786     StringRef FixItTagName;
787     switch (Tag->getTagKind()) {
788       case TTK_Class:
789         FixItTagName = "class ";
790         break;
791 
792       case TTK_Enum:
793         FixItTagName = "enum ";
794         break;
795 
796       case TTK_Struct:
797         FixItTagName = "struct ";
798         break;
799 
800       case TTK_Interface:
801         FixItTagName = "__interface ";
802         break;
803 
804       case TTK_Union:
805         FixItTagName = "union ";
806         break;
807     }
808 
809     StringRef TagName = FixItTagName.drop_back();
810     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
811       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
812       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
813 
814     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
815          I != IEnd; ++I)
816       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
817         << Name << TagName;
818 
819     // Replace lookup results with just the tag decl.
820     Result.clear(Sema::LookupTagName);
821     SemaRef.LookupParsedName(Result, S, &SS);
822     return true;
823   }
824 
825   return false;
826 }
827 
828 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
829 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
830                                   QualType T, SourceLocation NameLoc) {
831   ASTContext &Context = S.Context;
832 
833   TypeLocBuilder Builder;
834   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
835 
836   T = S.getElaboratedType(ETK_None, SS, T);
837   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
838   ElabTL.setElaboratedKeywordLoc(SourceLocation());
839   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
840   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
841 }
842 
843 Sema::NameClassification
844 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
845                    SourceLocation NameLoc, const Token &NextToken,
846                    bool IsAddressOfOperand,
847                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
848   DeclarationNameInfo NameInfo(Name, NameLoc);
849   ObjCMethodDecl *CurMethod = getCurMethodDecl();
850 
851   if (NextToken.is(tok::coloncolon)) {
852     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
853     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
854   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
855              isCurrentClassName(*Name, S, &SS)) {
856     // Per [class.qual]p2, this names the constructors of SS, not the
857     // injected-class-name. We don't have a classification for that.
858     // There's not much point caching this result, since the parser
859     // will reject it later.
860     return NameClassification::Unknown();
861   }
862 
863   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
864   LookupParsedName(Result, S, &SS, !CurMethod);
865 
866   // For unqualified lookup in a class template in MSVC mode, look into
867   // dependent base classes where the primary class template is known.
868   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
869     if (ParsedType TypeInBase =
870             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
871       return TypeInBase;
872   }
873 
874   // Perform lookup for Objective-C instance variables (including automatically
875   // synthesized instance variables), if we're in an Objective-C method.
876   // FIXME: This lookup really, really needs to be folded in to the normal
877   // unqualified lookup mechanism.
878   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
879     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
880     if (E.get() || E.isInvalid())
881       return E;
882   }
883 
884   bool SecondTry = false;
885   bool IsFilteredTemplateName = false;
886 
887 Corrected:
888   switch (Result.getResultKind()) {
889   case LookupResult::NotFound:
890     // If an unqualified-id is followed by a '(', then we have a function
891     // call.
892     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
893       // In C++, this is an ADL-only call.
894       // FIXME: Reference?
895       if (getLangOpts().CPlusPlus)
896         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
897 
898       // C90 6.3.2.2:
899       //   If the expression that precedes the parenthesized argument list in a
900       //   function call consists solely of an identifier, and if no
901       //   declaration is visible for this identifier, the identifier is
902       //   implicitly declared exactly as if, in the innermost block containing
903       //   the function call, the declaration
904       //
905       //     extern int identifier ();
906       //
907       //   appeared.
908       //
909       // We also allow this in C99 as an extension.
910       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
911         Result.addDecl(D);
912         Result.resolveKind();
913         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
914       }
915     }
916 
917     // In C, we first see whether there is a tag type by the same name, in
918     // which case it's likely that the user just forgot to write "enum",
919     // "struct", or "union".
920     if (!getLangOpts().CPlusPlus && !SecondTry &&
921         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
922       break;
923     }
924 
925     // Perform typo correction to determine if there is another name that is
926     // close to this name.
927     if (!SecondTry && CCC) {
928       SecondTry = true;
929       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
930                                                  Result.getLookupKind(), S,
931                                                  &SS, std::move(CCC),
932                                                  CTK_ErrorRecovery)) {
933         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
934         unsigned QualifiedDiag = diag::err_no_member_suggest;
935 
936         NamedDecl *FirstDecl = Corrected.getFoundDecl();
937         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
938         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
939             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
940           UnqualifiedDiag = diag::err_no_template_suggest;
941           QualifiedDiag = diag::err_no_member_template_suggest;
942         } else if (UnderlyingFirstDecl &&
943                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
944                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
945                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
946           UnqualifiedDiag = diag::err_unknown_typename_suggest;
947           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
948         }
949 
950         if (SS.isEmpty()) {
951           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
952         } else {// FIXME: is this even reachable? Test it.
953           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
954           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
955                                   Name->getName().equals(CorrectedStr);
956           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
957                                     << Name << computeDeclContext(SS, false)
958                                     << DroppedSpecifier << SS.getRange());
959         }
960 
961         // Update the name, so that the caller has the new name.
962         Name = Corrected.getCorrectionAsIdentifierInfo();
963 
964         // Typo correction corrected to a keyword.
965         if (Corrected.isKeyword())
966           return Name;
967 
968         // Also update the LookupResult...
969         // FIXME: This should probably go away at some point
970         Result.clear();
971         Result.setLookupName(Corrected.getCorrection());
972         if (FirstDecl)
973           Result.addDecl(FirstDecl);
974 
975         // If we found an Objective-C instance variable, let
976         // LookupInObjCMethod build the appropriate expression to
977         // reference the ivar.
978         // FIXME: This is a gross hack.
979         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
980           Result.clear();
981           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
982           return E;
983         }
984 
985         goto Corrected;
986       }
987     }
988 
989     // We failed to correct; just fall through and let the parser deal with it.
990     Result.suppressDiagnostics();
991     return NameClassification::Unknown();
992 
993   case LookupResult::NotFoundInCurrentInstantiation: {
994     // We performed name lookup into the current instantiation, and there were
995     // dependent bases, so we treat this result the same way as any other
996     // dependent nested-name-specifier.
997 
998     // C++ [temp.res]p2:
999     //   A name used in a template declaration or definition and that is
1000     //   dependent on a template-parameter is assumed not to name a type
1001     //   unless the applicable name lookup finds a type name or the name is
1002     //   qualified by the keyword typename.
1003     //
1004     // FIXME: If the next token is '<', we might want to ask the parser to
1005     // perform some heroics to see if we actually have a
1006     // template-argument-list, which would indicate a missing 'template'
1007     // keyword here.
1008     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1009                                       NameInfo, IsAddressOfOperand,
1010                                       /*TemplateArgs=*/nullptr);
1011   }
1012 
1013   case LookupResult::Found:
1014   case LookupResult::FoundOverloaded:
1015   case LookupResult::FoundUnresolvedValue:
1016     break;
1017 
1018   case LookupResult::Ambiguous:
1019     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1020         hasAnyAcceptableTemplateNames(Result)) {
1021       // C++ [temp.local]p3:
1022       //   A lookup that finds an injected-class-name (10.2) can result in an
1023       //   ambiguity in certain cases (for example, if it is found in more than
1024       //   one base class). If all of the injected-class-names that are found
1025       //   refer to specializations of the same class template, and if the name
1026       //   is followed by a template-argument-list, the reference refers to the
1027       //   class template itself and not a specialization thereof, and is not
1028       //   ambiguous.
1029       //
1030       // This filtering can make an ambiguous result into an unambiguous one,
1031       // so try again after filtering out template names.
1032       FilterAcceptableTemplateNames(Result);
1033       if (!Result.isAmbiguous()) {
1034         IsFilteredTemplateName = true;
1035         break;
1036       }
1037     }
1038 
1039     // Diagnose the ambiguity and return an error.
1040     return NameClassification::Error();
1041   }
1042 
1043   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1044       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1045     // C++ [temp.names]p3:
1046     //   After name lookup (3.4) finds that a name is a template-name or that
1047     //   an operator-function-id or a literal- operator-id refers to a set of
1048     //   overloaded functions any member of which is a function template if
1049     //   this is followed by a <, the < is always taken as the delimiter of a
1050     //   template-argument-list and never as the less-than operator.
1051     if (!IsFilteredTemplateName)
1052       FilterAcceptableTemplateNames(Result);
1053 
1054     if (!Result.empty()) {
1055       bool IsFunctionTemplate;
1056       bool IsVarTemplate;
1057       TemplateName Template;
1058       if (Result.end() - Result.begin() > 1) {
1059         IsFunctionTemplate = true;
1060         Template = Context.getOverloadedTemplateName(Result.begin(),
1061                                                      Result.end());
1062       } else {
1063         TemplateDecl *TD
1064           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1065         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1066         IsVarTemplate = isa<VarTemplateDecl>(TD);
1067 
1068         if (SS.isSet() && !SS.isInvalid())
1069           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1070                                                     /*TemplateKeyword=*/false,
1071                                                       TD);
1072         else
1073           Template = TemplateName(TD);
1074       }
1075 
1076       if (IsFunctionTemplate) {
1077         // Function templates always go through overload resolution, at which
1078         // point we'll perform the various checks (e.g., accessibility) we need
1079         // to based on which function we selected.
1080         Result.suppressDiagnostics();
1081 
1082         return NameClassification::FunctionTemplate(Template);
1083       }
1084 
1085       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1086                            : NameClassification::TypeTemplate(Template);
1087     }
1088   }
1089 
1090   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1091   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1092     DiagnoseUseOfDecl(Type, NameLoc);
1093     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1094     QualType T = Context.getTypeDeclType(Type);
1095     if (SS.isNotEmpty())
1096       return buildNestedType(*this, SS, T, NameLoc);
1097     return ParsedType::make(T);
1098   }
1099 
1100   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1101   if (!Class) {
1102     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1103     if (ObjCCompatibleAliasDecl *Alias =
1104             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1105       Class = Alias->getClassInterface();
1106   }
1107 
1108   if (Class) {
1109     DiagnoseUseOfDecl(Class, NameLoc);
1110 
1111     if (NextToken.is(tok::period)) {
1112       // Interface. <something> is parsed as a property reference expression.
1113       // Just return "unknown" as a fall-through for now.
1114       Result.suppressDiagnostics();
1115       return NameClassification::Unknown();
1116     }
1117 
1118     QualType T = Context.getObjCInterfaceType(Class);
1119     return ParsedType::make(T);
1120   }
1121 
1122   // We can have a type template here if we're classifying a template argument.
1123   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1124       !isa<VarTemplateDecl>(FirstDecl))
1125     return NameClassification::TypeTemplate(
1126         TemplateName(cast<TemplateDecl>(FirstDecl)));
1127 
1128   // Check for a tag type hidden by a non-type decl in a few cases where it
1129   // seems likely a type is wanted instead of the non-type that was found.
1130   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1131   if ((NextToken.is(tok::identifier) ||
1132        (NextIsOp &&
1133         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1134       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1135     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1136     DiagnoseUseOfDecl(Type, NameLoc);
1137     QualType T = Context.getTypeDeclType(Type);
1138     if (SS.isNotEmpty())
1139       return buildNestedType(*this, SS, T, NameLoc);
1140     return ParsedType::make(T);
1141   }
1142 
1143   if (FirstDecl->isCXXClassMember())
1144     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1145                                            nullptr, S);
1146 
1147   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1148   return BuildDeclarationNameExpr(SS, Result, ADL);
1149 }
1150 
1151 Sema::TemplateNameKindForDiagnostics
1152 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1153   auto *TD = Name.getAsTemplateDecl();
1154   if (!TD)
1155     return TemplateNameKindForDiagnostics::DependentTemplate;
1156   if (isa<ClassTemplateDecl>(TD))
1157     return TemplateNameKindForDiagnostics::ClassTemplate;
1158   if (isa<FunctionTemplateDecl>(TD))
1159     return TemplateNameKindForDiagnostics::FunctionTemplate;
1160   if (isa<VarTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::VarTemplate;
1162   if (isa<TypeAliasTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::AliasTemplate;
1164   if (isa<TemplateTemplateParmDecl>(TD))
1165     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1166   return TemplateNameKindForDiagnostics::DependentTemplate;
1167 }
1168 
1169 // Determines the context to return to after temporarily entering a
1170 // context.  This depends in an unnecessarily complicated way on the
1171 // exact ordering of callbacks from the parser.
1172 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1173 
1174   // Functions defined inline within classes aren't parsed until we've
1175   // finished parsing the top-level class, so the top-level class is
1176   // the context we'll need to return to.
1177   // A Lambda call operator whose parent is a class must not be treated
1178   // as an inline member function.  A Lambda can be used legally
1179   // either as an in-class member initializer or a default argument.  These
1180   // are parsed once the class has been marked complete and so the containing
1181   // context would be the nested class (when the lambda is defined in one);
1182   // If the class is not complete, then the lambda is being used in an
1183   // ill-formed fashion (such as to specify the width of a bit-field, or
1184   // in an array-bound) - in which case we still want to return the
1185   // lexically containing DC (which could be a nested class).
1186   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1187     DC = DC->getLexicalParent();
1188 
1189     // A function not defined within a class will always return to its
1190     // lexical context.
1191     if (!isa<CXXRecordDecl>(DC))
1192       return DC;
1193 
1194     // A C++ inline method/friend is parsed *after* the topmost class
1195     // it was declared in is fully parsed ("complete");  the topmost
1196     // class is the context we need to return to.
1197     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1198       DC = RD;
1199 
1200     // Return the declaration context of the topmost class the inline method is
1201     // declared in.
1202     return DC;
1203   }
1204 
1205   return DC->getLexicalParent();
1206 }
1207 
1208 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1209   assert(getContainingDC(DC) == CurContext &&
1210       "The next DeclContext should be lexically contained in the current one.");
1211   CurContext = DC;
1212   S->setEntity(DC);
1213 }
1214 
1215 void Sema::PopDeclContext() {
1216   assert(CurContext && "DeclContext imbalance!");
1217 
1218   CurContext = getContainingDC(CurContext);
1219   assert(CurContext && "Popped translation unit!");
1220 }
1221 
1222 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1223                                                                     Decl *D) {
1224   // Unlike PushDeclContext, the context to which we return is not necessarily
1225   // the containing DC of TD, because the new context will be some pre-existing
1226   // TagDecl definition instead of a fresh one.
1227   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1228   CurContext = cast<TagDecl>(D)->getDefinition();
1229   assert(CurContext && "skipping definition of undefined tag");
1230   // Start lookups from the parent of the current context; we don't want to look
1231   // into the pre-existing complete definition.
1232   S->setEntity(CurContext->getLookupParent());
1233   return Result;
1234 }
1235 
1236 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1237   CurContext = static_cast<decltype(CurContext)>(Context);
1238 }
1239 
1240 /// EnterDeclaratorContext - Used when we must lookup names in the context
1241 /// of a declarator's nested name specifier.
1242 ///
1243 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1244   // C++0x [basic.lookup.unqual]p13:
1245   //   A name used in the definition of a static data member of class
1246   //   X (after the qualified-id of the static member) is looked up as
1247   //   if the name was used in a member function of X.
1248   // C++0x [basic.lookup.unqual]p14:
1249   //   If a variable member of a namespace is defined outside of the
1250   //   scope of its namespace then any name used in the definition of
1251   //   the variable member (after the declarator-id) is looked up as
1252   //   if the definition of the variable member occurred in its
1253   //   namespace.
1254   // Both of these imply that we should push a scope whose context
1255   // is the semantic context of the declaration.  We can't use
1256   // PushDeclContext here because that context is not necessarily
1257   // lexically contained in the current context.  Fortunately,
1258   // the containing scope should have the appropriate information.
1259 
1260   assert(!S->getEntity() && "scope already has entity");
1261 
1262 #ifndef NDEBUG
1263   Scope *Ancestor = S->getParent();
1264   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1265   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1266 #endif
1267 
1268   CurContext = DC;
1269   S->setEntity(DC);
1270 }
1271 
1272 void Sema::ExitDeclaratorContext(Scope *S) {
1273   assert(S->getEntity() == CurContext && "Context imbalance!");
1274 
1275   // Switch back to the lexical context.  The safety of this is
1276   // enforced by an assert in EnterDeclaratorContext.
1277   Scope *Ancestor = S->getParent();
1278   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1279   CurContext = Ancestor->getEntity();
1280 
1281   // We don't need to do anything with the scope, which is going to
1282   // disappear.
1283 }
1284 
1285 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1286   // We assume that the caller has already called
1287   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1288   FunctionDecl *FD = D->getAsFunction();
1289   if (!FD)
1290     return;
1291 
1292   // Same implementation as PushDeclContext, but enters the context
1293   // from the lexical parent, rather than the top-level class.
1294   assert(CurContext == FD->getLexicalParent() &&
1295     "The next DeclContext should be lexically contained in the current one.");
1296   CurContext = FD;
1297   S->setEntity(CurContext);
1298 
1299   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1300     ParmVarDecl *Param = FD->getParamDecl(P);
1301     // If the parameter has an identifier, then add it to the scope
1302     if (Param->getIdentifier()) {
1303       S->AddDecl(Param);
1304       IdResolver.AddDecl(Param);
1305     }
1306   }
1307 }
1308 
1309 void Sema::ActOnExitFunctionContext() {
1310   // Same implementation as PopDeclContext, but returns to the lexical parent,
1311   // rather than the top-level class.
1312   assert(CurContext && "DeclContext imbalance!");
1313   CurContext = CurContext->getLexicalParent();
1314   assert(CurContext && "Popped translation unit!");
1315 }
1316 
1317 /// Determine whether we allow overloading of the function
1318 /// PrevDecl with another declaration.
1319 ///
1320 /// This routine determines whether overloading is possible, not
1321 /// whether some new function is actually an overload. It will return
1322 /// true in C++ (where we can always provide overloads) or, as an
1323 /// extension, in C when the previous function is already an
1324 /// overloaded function declaration or has the "overloadable"
1325 /// attribute.
1326 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1327                                        ASTContext &Context,
1328                                        const FunctionDecl *New) {
1329   if (Context.getLangOpts().CPlusPlus)
1330     return true;
1331 
1332   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1333     return true;
1334 
1335   return Previous.getResultKind() == LookupResult::Found &&
1336          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1337           New->hasAttr<OverloadableAttr>());
1338 }
1339 
1340 /// Add this decl to the scope shadowed decl chains.
1341 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1342   // Move up the scope chain until we find the nearest enclosing
1343   // non-transparent context. The declaration will be introduced into this
1344   // scope.
1345   while (S->getEntity() && S->getEntity()->isTransparentContext())
1346     S = S->getParent();
1347 
1348   // Add scoped declarations into their context, so that they can be
1349   // found later. Declarations without a context won't be inserted
1350   // into any context.
1351   if (AddToContext)
1352     CurContext->addDecl(D);
1353 
1354   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1355   // are function-local declarations.
1356   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1357       !D->getDeclContext()->getRedeclContext()->Equals(
1358         D->getLexicalDeclContext()->getRedeclContext()) &&
1359       !D->getLexicalDeclContext()->isFunctionOrMethod())
1360     return;
1361 
1362   // Template instantiations should also not be pushed into scope.
1363   if (isa<FunctionDecl>(D) &&
1364       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1365     return;
1366 
1367   // If this replaces anything in the current scope,
1368   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1369                                IEnd = IdResolver.end();
1370   for (; I != IEnd; ++I) {
1371     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1372       S->RemoveDecl(*I);
1373       IdResolver.RemoveDecl(*I);
1374 
1375       // Should only need to replace one decl.
1376       break;
1377     }
1378   }
1379 
1380   S->AddDecl(D);
1381 
1382   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1383     // Implicitly-generated labels may end up getting generated in an order that
1384     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1385     // the label at the appropriate place in the identifier chain.
1386     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1387       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1388       if (IDC == CurContext) {
1389         if (!S->isDeclScope(*I))
1390           continue;
1391       } else if (IDC->Encloses(CurContext))
1392         break;
1393     }
1394 
1395     IdResolver.InsertDeclAfter(I, D);
1396   } else {
1397     IdResolver.AddDecl(D);
1398   }
1399 }
1400 
1401 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1402   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1403     TUScope->AddDecl(D);
1404 }
1405 
1406 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1407                          bool AllowInlineNamespace) {
1408   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1409 }
1410 
1411 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1412   DeclContext *TargetDC = DC->getPrimaryContext();
1413   do {
1414     if (DeclContext *ScopeDC = S->getEntity())
1415       if (ScopeDC->getPrimaryContext() == TargetDC)
1416         return S;
1417   } while ((S = S->getParent()));
1418 
1419   return nullptr;
1420 }
1421 
1422 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1423                                             DeclContext*,
1424                                             ASTContext&);
1425 
1426 /// Filters out lookup results that don't fall within the given scope
1427 /// as determined by isDeclInScope.
1428 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1429                                 bool ConsiderLinkage,
1430                                 bool AllowInlineNamespace) {
1431   LookupResult::Filter F = R.makeFilter();
1432   while (F.hasNext()) {
1433     NamedDecl *D = F.next();
1434 
1435     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1436       continue;
1437 
1438     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1439       continue;
1440 
1441     F.erase();
1442   }
1443 
1444   F.done();
1445 }
1446 
1447 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1448 /// have compatible owning modules.
1449 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1450   // FIXME: The Modules TS is not clear about how friend declarations are
1451   // to be treated. It's not meaningful to have different owning modules for
1452   // linkage in redeclarations of the same entity, so for now allow the
1453   // redeclaration and change the owning modules to match.
1454   if (New->getFriendObjectKind() &&
1455       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1456     New->setLocalOwningModule(Old->getOwningModule());
1457     makeMergedDefinitionVisible(New);
1458     return false;
1459   }
1460 
1461   Module *NewM = New->getOwningModule();
1462   Module *OldM = Old->getOwningModule();
1463   if (NewM == OldM)
1464     return false;
1465 
1466   // FIXME: Check proclaimed-ownership-declarations here too.
1467   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1468   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1469   if (NewIsModuleInterface || OldIsModuleInterface) {
1470     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1471     //   if a declaration of D [...] appears in the purview of a module, all
1472     //   other such declarations shall appear in the purview of the same module
1473     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1474       << New
1475       << NewIsModuleInterface
1476       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1477       << OldIsModuleInterface
1478       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1479     Diag(Old->getLocation(), diag::note_previous_declaration);
1480     New->setInvalidDecl();
1481     return true;
1482   }
1483 
1484   return false;
1485 }
1486 
1487 static bool isUsingDecl(NamedDecl *D) {
1488   return isa<UsingShadowDecl>(D) ||
1489          isa<UnresolvedUsingTypenameDecl>(D) ||
1490          isa<UnresolvedUsingValueDecl>(D);
1491 }
1492 
1493 /// Removes using shadow declarations from the lookup results.
1494 static void RemoveUsingDecls(LookupResult &R) {
1495   LookupResult::Filter F = R.makeFilter();
1496   while (F.hasNext())
1497     if (isUsingDecl(F.next()))
1498       F.erase();
1499 
1500   F.done();
1501 }
1502 
1503 /// Check for this common pattern:
1504 /// @code
1505 /// class S {
1506 ///   S(const S&); // DO NOT IMPLEMENT
1507 ///   void operator=(const S&); // DO NOT IMPLEMENT
1508 /// };
1509 /// @endcode
1510 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1511   // FIXME: Should check for private access too but access is set after we get
1512   // the decl here.
1513   if (D->doesThisDeclarationHaveABody())
1514     return false;
1515 
1516   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1517     return CD->isCopyConstructor();
1518   return D->isCopyAssignmentOperator();
1519 }
1520 
1521 // We need this to handle
1522 //
1523 // typedef struct {
1524 //   void *foo() { return 0; }
1525 // } A;
1526 //
1527 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1528 // for example. If 'A', foo will have external linkage. If we have '*A',
1529 // foo will have no linkage. Since we can't know until we get to the end
1530 // of the typedef, this function finds out if D might have non-external linkage.
1531 // Callers should verify at the end of the TU if it D has external linkage or
1532 // not.
1533 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1534   const DeclContext *DC = D->getDeclContext();
1535   while (!DC->isTranslationUnit()) {
1536     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1537       if (!RD->hasNameForLinkage())
1538         return true;
1539     }
1540     DC = DC->getParent();
1541   }
1542 
1543   return !D->isExternallyVisible();
1544 }
1545 
1546 // FIXME: This needs to be refactored; some other isInMainFile users want
1547 // these semantics.
1548 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1549   if (S.TUKind != TU_Complete)
1550     return false;
1551   return S.SourceMgr.isInMainFile(Loc);
1552 }
1553 
1554 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1555   assert(D);
1556 
1557   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1558     return false;
1559 
1560   // Ignore all entities declared within templates, and out-of-line definitions
1561   // of members of class templates.
1562   if (D->getDeclContext()->isDependentContext() ||
1563       D->getLexicalDeclContext()->isDependentContext())
1564     return false;
1565 
1566   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1567     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1568       return false;
1569     // A non-out-of-line declaration of a member specialization was implicitly
1570     // instantiated; it's the out-of-line declaration that we're interested in.
1571     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1572         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1573       return false;
1574 
1575     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1576       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1577         return false;
1578     } else {
1579       // 'static inline' functions are defined in headers; don't warn.
1580       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1581         return false;
1582     }
1583 
1584     if (FD->doesThisDeclarationHaveABody() &&
1585         Context.DeclMustBeEmitted(FD))
1586       return false;
1587   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1588     // Constants and utility variables are defined in headers with internal
1589     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1590     // like "inline".)
1591     if (!isMainFileLoc(*this, VD->getLocation()))
1592       return false;
1593 
1594     if (Context.DeclMustBeEmitted(VD))
1595       return false;
1596 
1597     if (VD->isStaticDataMember() &&
1598         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1599       return false;
1600     if (VD->isStaticDataMember() &&
1601         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1602         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1603       return false;
1604 
1605     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1606       return false;
1607   } else {
1608     return false;
1609   }
1610 
1611   // Only warn for unused decls internal to the translation unit.
1612   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1613   // for inline functions defined in the main source file, for instance.
1614   return mightHaveNonExternalLinkage(D);
1615 }
1616 
1617 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1618   if (!D)
1619     return;
1620 
1621   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1622     const FunctionDecl *First = FD->getFirstDecl();
1623     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1624       return; // First should already be in the vector.
1625   }
1626 
1627   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1628     const VarDecl *First = VD->getFirstDecl();
1629     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1630       return; // First should already be in the vector.
1631   }
1632 
1633   if (ShouldWarnIfUnusedFileScopedDecl(D))
1634     UnusedFileScopedDecls.push_back(D);
1635 }
1636 
1637 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1638   if (D->isInvalidDecl())
1639     return false;
1640 
1641   bool Referenced = false;
1642   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1643     // For a decomposition declaration, warn if none of the bindings are
1644     // referenced, instead of if the variable itself is referenced (which
1645     // it is, by the bindings' expressions).
1646     for (auto *BD : DD->bindings()) {
1647       if (BD->isReferenced()) {
1648         Referenced = true;
1649         break;
1650       }
1651     }
1652   } else if (!D->getDeclName()) {
1653     return false;
1654   } else if (D->isReferenced() || D->isUsed()) {
1655     Referenced = true;
1656   }
1657 
1658   if (Referenced || D->hasAttr<UnusedAttr>() ||
1659       D->hasAttr<ObjCPreciseLifetimeAttr>())
1660     return false;
1661 
1662   if (isa<LabelDecl>(D))
1663     return true;
1664 
1665   // Except for labels, we only care about unused decls that are local to
1666   // functions.
1667   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1668   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1669     // For dependent types, the diagnostic is deferred.
1670     WithinFunction =
1671         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1672   if (!WithinFunction)
1673     return false;
1674 
1675   if (isa<TypedefNameDecl>(D))
1676     return true;
1677 
1678   // White-list anything that isn't a local variable.
1679   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1680     return false;
1681 
1682   // Types of valid local variables should be complete, so this should succeed.
1683   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1684 
1685     // White-list anything with an __attribute__((unused)) type.
1686     const auto *Ty = VD->getType().getTypePtr();
1687 
1688     // Only look at the outermost level of typedef.
1689     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1690       if (TT->getDecl()->hasAttr<UnusedAttr>())
1691         return false;
1692     }
1693 
1694     // If we failed to complete the type for some reason, or if the type is
1695     // dependent, don't diagnose the variable.
1696     if (Ty->isIncompleteType() || Ty->isDependentType())
1697       return false;
1698 
1699     // Look at the element type to ensure that the warning behaviour is
1700     // consistent for both scalars and arrays.
1701     Ty = Ty->getBaseElementTypeUnsafe();
1702 
1703     if (const TagType *TT = Ty->getAs<TagType>()) {
1704       const TagDecl *Tag = TT->getDecl();
1705       if (Tag->hasAttr<UnusedAttr>())
1706         return false;
1707 
1708       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1709         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1710           return false;
1711 
1712         if (const Expr *Init = VD->getInit()) {
1713           if (const ExprWithCleanups *Cleanups =
1714                   dyn_cast<ExprWithCleanups>(Init))
1715             Init = Cleanups->getSubExpr();
1716           const CXXConstructExpr *Construct =
1717             dyn_cast<CXXConstructExpr>(Init);
1718           if (Construct && !Construct->isElidable()) {
1719             CXXConstructorDecl *CD = Construct->getConstructor();
1720             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1721                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1722               return false;
1723           }
1724         }
1725       }
1726     }
1727 
1728     // TODO: __attribute__((unused)) templates?
1729   }
1730 
1731   return true;
1732 }
1733 
1734 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1735                                      FixItHint &Hint) {
1736   if (isa<LabelDecl>(D)) {
1737     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1738         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1739         true);
1740     if (AfterColon.isInvalid())
1741       return;
1742     Hint = FixItHint::CreateRemoval(
1743         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1744   }
1745 }
1746 
1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1748   if (D->getTypeForDecl()->isDependentType())
1749     return;
1750 
1751   for (auto *TmpD : D->decls()) {
1752     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1753       DiagnoseUnusedDecl(T);
1754     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1755       DiagnoseUnusedNestedTypedefs(R);
1756   }
1757 }
1758 
1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1760 /// unless they are marked attr(unused).
1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1762   if (!ShouldDiagnoseUnusedDecl(D))
1763     return;
1764 
1765   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1766     // typedefs can be referenced later on, so the diagnostics are emitted
1767     // at end-of-translation-unit.
1768     UnusedLocalTypedefNameCandidates.insert(TD);
1769     return;
1770   }
1771 
1772   FixItHint Hint;
1773   GenerateFixForUnusedDecl(D, Context, Hint);
1774 
1775   unsigned DiagID;
1776   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1777     DiagID = diag::warn_unused_exception_param;
1778   else if (isa<LabelDecl>(D))
1779     DiagID = diag::warn_unused_label;
1780   else
1781     DiagID = diag::warn_unused_variable;
1782 
1783   Diag(D->getLocation(), DiagID) << D << Hint;
1784 }
1785 
1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1787   // Verify that we have no forward references left.  If so, there was a goto
1788   // or address of a label taken, but no definition of it.  Label fwd
1789   // definitions are indicated with a null substmt which is also not a resolved
1790   // MS inline assembly label name.
1791   bool Diagnose = false;
1792   if (L->isMSAsmLabel())
1793     Diagnose = !L->isResolvedMSAsmLabel();
1794   else
1795     Diagnose = L->getStmt() == nullptr;
1796   if (Diagnose)
1797     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1798 }
1799 
1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1801   S->mergeNRVOIntoParent();
1802 
1803   if (S->decl_empty()) return;
1804   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1805          "Scope shouldn't contain decls!");
1806 
1807   for (auto *TmpD : S->decls()) {
1808     assert(TmpD && "This decl didn't get pushed??");
1809 
1810     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1811     NamedDecl *D = cast<NamedDecl>(TmpD);
1812 
1813     // Diagnose unused variables in this scope.
1814     if (!S->hasUnrecoverableErrorOccurred()) {
1815       DiagnoseUnusedDecl(D);
1816       if (const auto *RD = dyn_cast<RecordDecl>(D))
1817         DiagnoseUnusedNestedTypedefs(RD);
1818     }
1819 
1820     if (!D->getDeclName()) continue;
1821 
1822     // If this was a forward reference to a label, verify it was defined.
1823     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1824       CheckPoppedLabel(LD, *this);
1825 
1826     // Remove this name from our lexical scope, and warn on it if we haven't
1827     // already.
1828     IdResolver.RemoveDecl(D);
1829     auto ShadowI = ShadowingDecls.find(D);
1830     if (ShadowI != ShadowingDecls.end()) {
1831       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1832         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1833             << D << FD << FD->getParent();
1834         Diag(FD->getLocation(), diag::note_previous_declaration);
1835       }
1836       ShadowingDecls.erase(ShadowI);
1837     }
1838   }
1839 }
1840 
1841 /// Look for an Objective-C class in the translation unit.
1842 ///
1843 /// \param Id The name of the Objective-C class we're looking for. If
1844 /// typo-correction fixes this name, the Id will be updated
1845 /// to the fixed name.
1846 ///
1847 /// \param IdLoc The location of the name in the translation unit.
1848 ///
1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1850 /// if there is no class with the given name.
1851 ///
1852 /// \returns The declaration of the named Objective-C class, or NULL if the
1853 /// class could not be found.
1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1855                                               SourceLocation IdLoc,
1856                                               bool DoTypoCorrection) {
1857   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1858   // creation from this context.
1859   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1860 
1861   if (!IDecl && DoTypoCorrection) {
1862     // Perform typo correction at the given location, but only if we
1863     // find an Objective-C class name.
1864     if (TypoCorrection C = CorrectTypo(
1865             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1866             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1867             CTK_ErrorRecovery)) {
1868       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1869       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1870       Id = IDecl->getIdentifier();
1871     }
1872   }
1873   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1874   // This routine must always return a class definition, if any.
1875   if (Def && Def->getDefinition())
1876       Def = Def->getDefinition();
1877   return Def;
1878 }
1879 
1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1881 /// from S, where a non-field would be declared. This routine copes
1882 /// with the difference between C and C++ scoping rules in structs and
1883 /// unions. For example, the following code is well-formed in C but
1884 /// ill-formed in C++:
1885 /// @code
1886 /// struct S6 {
1887 ///   enum { BAR } e;
1888 /// };
1889 ///
1890 /// void test_S6() {
1891 ///   struct S6 a;
1892 ///   a.e = BAR;
1893 /// }
1894 /// @endcode
1895 /// For the declaration of BAR, this routine will return a different
1896 /// scope. The scope S will be the scope of the unnamed enumeration
1897 /// within S6. In C++, this routine will return the scope associated
1898 /// with S6, because the enumeration's scope is a transparent
1899 /// context but structures can contain non-field names. In C, this
1900 /// routine will return the translation unit scope, since the
1901 /// enumeration's scope is a transparent context and structures cannot
1902 /// contain non-field names.
1903 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1904   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1905          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1906          (S->isClassScope() && !getLangOpts().CPlusPlus))
1907     S = S->getParent();
1908   return S;
1909 }
1910 
1911 /// Looks up the declaration of "struct objc_super" and
1912 /// saves it for later use in building builtin declaration of
1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1914 /// pre-existing declaration exists no action takes place.
1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1916                                         IdentifierInfo *II) {
1917   if (!II->isStr("objc_msgSendSuper"))
1918     return;
1919   ASTContext &Context = ThisSema.Context;
1920 
1921   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1922                       SourceLocation(), Sema::LookupTagName);
1923   ThisSema.LookupName(Result, S);
1924   if (Result.getResultKind() == LookupResult::Found)
1925     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1926       Context.setObjCSuperType(Context.getTagDeclType(TD));
1927 }
1928 
1929 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1930                                ASTContext::GetBuiltinTypeError Error) {
1931   switch (Error) {
1932   case ASTContext::GE_None:
1933     return "";
1934   case ASTContext::GE_Missing_type:
1935     return BuiltinInfo.getHeaderName(ID);
1936   case ASTContext::GE_Missing_stdio:
1937     return "stdio.h";
1938   case ASTContext::GE_Missing_setjmp:
1939     return "setjmp.h";
1940   case ASTContext::GE_Missing_ucontext:
1941     return "ucontext.h";
1942   }
1943   llvm_unreachable("unhandled error kind");
1944 }
1945 
1946 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1947 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1948 /// if we're creating this built-in in anticipation of redeclaring the
1949 /// built-in.
1950 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1951                                      Scope *S, bool ForRedeclaration,
1952                                      SourceLocation Loc) {
1953   LookupPredefedObjCSuperType(*this, S, II);
1954 
1955   ASTContext::GetBuiltinTypeError Error;
1956   QualType R = Context.GetBuiltinType(ID, Error);
1957   if (Error) {
1958     if (ForRedeclaration)
1959       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1960           << getHeaderName(Context.BuiltinInfo, ID, Error)
1961           << Context.BuiltinInfo.getName(ID);
1962     return nullptr;
1963   }
1964 
1965   if (!ForRedeclaration &&
1966       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1967        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1968     Diag(Loc, diag::ext_implicit_lib_function_decl)
1969         << Context.BuiltinInfo.getName(ID) << R;
1970     if (Context.BuiltinInfo.getHeaderName(ID) &&
1971         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1972       Diag(Loc, diag::note_include_header_or_declare)
1973           << Context.BuiltinInfo.getHeaderName(ID)
1974           << Context.BuiltinInfo.getName(ID);
1975   }
1976 
1977   if (R.isNull())
1978     return nullptr;
1979 
1980   DeclContext *Parent = Context.getTranslationUnitDecl();
1981   if (getLangOpts().CPlusPlus) {
1982     LinkageSpecDecl *CLinkageDecl =
1983         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1984                                 LinkageSpecDecl::lang_c, false);
1985     CLinkageDecl->setImplicit();
1986     Parent->addDecl(CLinkageDecl);
1987     Parent = CLinkageDecl;
1988   }
1989 
1990   FunctionDecl *New = FunctionDecl::Create(Context,
1991                                            Parent,
1992                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1993                                            SC_Extern,
1994                                            false,
1995                                            R->isFunctionProtoType());
1996   New->setImplicit();
1997 
1998   // Create Decl objects for each parameter, adding them to the
1999   // FunctionDecl.
2000   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2001     SmallVector<ParmVarDecl*, 16> Params;
2002     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2003       ParmVarDecl *parm =
2004           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2005                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2006                               SC_None, nullptr);
2007       parm->setScopeInfo(0, i);
2008       Params.push_back(parm);
2009     }
2010     New->setParams(Params);
2011   }
2012 
2013   AddKnownFunctionAttributes(New);
2014   RegisterLocallyScopedExternCDecl(New, S);
2015 
2016   // TUScope is the translation-unit scope to insert this function into.
2017   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2018   // relate Scopes to DeclContexts, and probably eliminate CurContext
2019   // entirely, but we're not there yet.
2020   DeclContext *SavedContext = CurContext;
2021   CurContext = Parent;
2022   PushOnScopeChains(New, TUScope);
2023   CurContext = SavedContext;
2024   return New;
2025 }
2026 
2027 /// Typedef declarations don't have linkage, but they still denote the same
2028 /// entity if their types are the same.
2029 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2030 /// isSameEntity.
2031 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2032                                                      TypedefNameDecl *Decl,
2033                                                      LookupResult &Previous) {
2034   // This is only interesting when modules are enabled.
2035   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2036     return;
2037 
2038   // Empty sets are uninteresting.
2039   if (Previous.empty())
2040     return;
2041 
2042   LookupResult::Filter Filter = Previous.makeFilter();
2043   while (Filter.hasNext()) {
2044     NamedDecl *Old = Filter.next();
2045 
2046     // Non-hidden declarations are never ignored.
2047     if (S.isVisible(Old))
2048       continue;
2049 
2050     // Declarations of the same entity are not ignored, even if they have
2051     // different linkages.
2052     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2053       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2054                                 Decl->getUnderlyingType()))
2055         continue;
2056 
2057       // If both declarations give a tag declaration a typedef name for linkage
2058       // purposes, then they declare the same entity.
2059       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2060           Decl->getAnonDeclWithTypedefName())
2061         continue;
2062     }
2063 
2064     Filter.erase();
2065   }
2066 
2067   Filter.done();
2068 }
2069 
2070 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2071   QualType OldType;
2072   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2073     OldType = OldTypedef->getUnderlyingType();
2074   else
2075     OldType = Context.getTypeDeclType(Old);
2076   QualType NewType = New->getUnderlyingType();
2077 
2078   if (NewType->isVariablyModifiedType()) {
2079     // Must not redefine a typedef with a variably-modified type.
2080     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2081     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2082       << Kind << NewType;
2083     if (Old->getLocation().isValid())
2084       notePreviousDefinition(Old, New->getLocation());
2085     New->setInvalidDecl();
2086     return true;
2087   }
2088 
2089   if (OldType != NewType &&
2090       !OldType->isDependentType() &&
2091       !NewType->isDependentType() &&
2092       !Context.hasSameType(OldType, NewType)) {
2093     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2094     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2095       << Kind << NewType << OldType;
2096     if (Old->getLocation().isValid())
2097       notePreviousDefinition(Old, New->getLocation());
2098     New->setInvalidDecl();
2099     return true;
2100   }
2101   return false;
2102 }
2103 
2104 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2105 /// same name and scope as a previous declaration 'Old'.  Figure out
2106 /// how to resolve this situation, merging decls or emitting
2107 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2108 ///
2109 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2110                                 LookupResult &OldDecls) {
2111   // If the new decl is known invalid already, don't bother doing any
2112   // merging checks.
2113   if (New->isInvalidDecl()) return;
2114 
2115   // Allow multiple definitions for ObjC built-in typedefs.
2116   // FIXME: Verify the underlying types are equivalent!
2117   if (getLangOpts().ObjC) {
2118     const IdentifierInfo *TypeID = New->getIdentifier();
2119     switch (TypeID->getLength()) {
2120     default: break;
2121     case 2:
2122       {
2123         if (!TypeID->isStr("id"))
2124           break;
2125         QualType T = New->getUnderlyingType();
2126         if (!T->isPointerType())
2127           break;
2128         if (!T->isVoidPointerType()) {
2129           QualType PT = T->getAs<PointerType>()->getPointeeType();
2130           if (!PT->isStructureType())
2131             break;
2132         }
2133         Context.setObjCIdRedefinitionType(T);
2134         // Install the built-in type for 'id', ignoring the current definition.
2135         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2136         return;
2137       }
2138     case 5:
2139       if (!TypeID->isStr("Class"))
2140         break;
2141       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2142       // Install the built-in type for 'Class', ignoring the current definition.
2143       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2144       return;
2145     case 3:
2146       if (!TypeID->isStr("SEL"))
2147         break;
2148       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2149       // Install the built-in type for 'SEL', ignoring the current definition.
2150       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2151       return;
2152     }
2153     // Fall through - the typedef name was not a builtin type.
2154   }
2155 
2156   // Verify the old decl was also a type.
2157   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2158   if (!Old) {
2159     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2160       << New->getDeclName();
2161 
2162     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2163     if (OldD->getLocation().isValid())
2164       notePreviousDefinition(OldD, New->getLocation());
2165 
2166     return New->setInvalidDecl();
2167   }
2168 
2169   // If the old declaration is invalid, just give up here.
2170   if (Old->isInvalidDecl())
2171     return New->setInvalidDecl();
2172 
2173   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2174     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2175     auto *NewTag = New->getAnonDeclWithTypedefName();
2176     NamedDecl *Hidden = nullptr;
2177     if (OldTag && NewTag &&
2178         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2179         !hasVisibleDefinition(OldTag, &Hidden)) {
2180       // There is a definition of this tag, but it is not visible. Use it
2181       // instead of our tag.
2182       New->setTypeForDecl(OldTD->getTypeForDecl());
2183       if (OldTD->isModed())
2184         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2185                                     OldTD->getUnderlyingType());
2186       else
2187         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2188 
2189       // Make the old tag definition visible.
2190       makeMergedDefinitionVisible(Hidden);
2191 
2192       // If this was an unscoped enumeration, yank all of its enumerators
2193       // out of the scope.
2194       if (isa<EnumDecl>(NewTag)) {
2195         Scope *EnumScope = getNonFieldDeclScope(S);
2196         for (auto *D : NewTag->decls()) {
2197           auto *ED = cast<EnumConstantDecl>(D);
2198           assert(EnumScope->isDeclScope(ED));
2199           EnumScope->RemoveDecl(ED);
2200           IdResolver.RemoveDecl(ED);
2201           ED->getLexicalDeclContext()->removeDecl(ED);
2202         }
2203       }
2204     }
2205   }
2206 
2207   // If the typedef types are not identical, reject them in all languages and
2208   // with any extensions enabled.
2209   if (isIncompatibleTypedef(Old, New))
2210     return;
2211 
2212   // The types match.  Link up the redeclaration chain and merge attributes if
2213   // the old declaration was a typedef.
2214   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2215     New->setPreviousDecl(Typedef);
2216     mergeDeclAttributes(New, Old);
2217   }
2218 
2219   if (getLangOpts().MicrosoftExt)
2220     return;
2221 
2222   if (getLangOpts().CPlusPlus) {
2223     // C++ [dcl.typedef]p2:
2224     //   In a given non-class scope, a typedef specifier can be used to
2225     //   redefine the name of any type declared in that scope to refer
2226     //   to the type to which it already refers.
2227     if (!isa<CXXRecordDecl>(CurContext))
2228       return;
2229 
2230     // C++0x [dcl.typedef]p4:
2231     //   In a given class scope, a typedef specifier can be used to redefine
2232     //   any class-name declared in that scope that is not also a typedef-name
2233     //   to refer to the type to which it already refers.
2234     //
2235     // This wording came in via DR424, which was a correction to the
2236     // wording in DR56, which accidentally banned code like:
2237     //
2238     //   struct S {
2239     //     typedef struct A { } A;
2240     //   };
2241     //
2242     // in the C++03 standard. We implement the C++0x semantics, which
2243     // allow the above but disallow
2244     //
2245     //   struct S {
2246     //     typedef int I;
2247     //     typedef int I;
2248     //   };
2249     //
2250     // since that was the intent of DR56.
2251     if (!isa<TypedefNameDecl>(Old))
2252       return;
2253 
2254     Diag(New->getLocation(), diag::err_redefinition)
2255       << New->getDeclName();
2256     notePreviousDefinition(Old, New->getLocation());
2257     return New->setInvalidDecl();
2258   }
2259 
2260   // Modules always permit redefinition of typedefs, as does C11.
2261   if (getLangOpts().Modules || getLangOpts().C11)
2262     return;
2263 
2264   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2265   // is normally mapped to an error, but can be controlled with
2266   // -Wtypedef-redefinition.  If either the original or the redefinition is
2267   // in a system header, don't emit this for compatibility with GCC.
2268   if (getDiagnostics().getSuppressSystemWarnings() &&
2269       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2270       (Old->isImplicit() ||
2271        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2272        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2273     return;
2274 
2275   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2276     << New->getDeclName();
2277   notePreviousDefinition(Old, New->getLocation());
2278 }
2279 
2280 /// DeclhasAttr - returns true if decl Declaration already has the target
2281 /// attribute.
2282 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2283   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2284   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2285   for (const auto *i : D->attrs())
2286     if (i->getKind() == A->getKind()) {
2287       if (Ann) {
2288         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2289           return true;
2290         continue;
2291       }
2292       // FIXME: Don't hardcode this check
2293       if (OA && isa<OwnershipAttr>(i))
2294         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2295       return true;
2296     }
2297 
2298   return false;
2299 }
2300 
2301 static bool isAttributeTargetADefinition(Decl *D) {
2302   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2303     return VD->isThisDeclarationADefinition();
2304   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2305     return TD->isCompleteDefinition() || TD->isBeingDefined();
2306   return true;
2307 }
2308 
2309 /// Merge alignment attributes from \p Old to \p New, taking into account the
2310 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2311 ///
2312 /// \return \c true if any attributes were added to \p New.
2313 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2314   // Look for alignas attributes on Old, and pick out whichever attribute
2315   // specifies the strictest alignment requirement.
2316   AlignedAttr *OldAlignasAttr = nullptr;
2317   AlignedAttr *OldStrictestAlignAttr = nullptr;
2318   unsigned OldAlign = 0;
2319   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2320     // FIXME: We have no way of representing inherited dependent alignments
2321     // in a case like:
2322     //   template<int A, int B> struct alignas(A) X;
2323     //   template<int A, int B> struct alignas(B) X {};
2324     // For now, we just ignore any alignas attributes which are not on the
2325     // definition in such a case.
2326     if (I->isAlignmentDependent())
2327       return false;
2328 
2329     if (I->isAlignas())
2330       OldAlignasAttr = I;
2331 
2332     unsigned Align = I->getAlignment(S.Context);
2333     if (Align > OldAlign) {
2334       OldAlign = Align;
2335       OldStrictestAlignAttr = I;
2336     }
2337   }
2338 
2339   // Look for alignas attributes on New.
2340   AlignedAttr *NewAlignasAttr = nullptr;
2341   unsigned NewAlign = 0;
2342   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2343     if (I->isAlignmentDependent())
2344       return false;
2345 
2346     if (I->isAlignas())
2347       NewAlignasAttr = I;
2348 
2349     unsigned Align = I->getAlignment(S.Context);
2350     if (Align > NewAlign)
2351       NewAlign = Align;
2352   }
2353 
2354   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2355     // Both declarations have 'alignas' attributes. We require them to match.
2356     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2357     // fall short. (If two declarations both have alignas, they must both match
2358     // every definition, and so must match each other if there is a definition.)
2359 
2360     // If either declaration only contains 'alignas(0)' specifiers, then it
2361     // specifies the natural alignment for the type.
2362     if (OldAlign == 0 || NewAlign == 0) {
2363       QualType Ty;
2364       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2365         Ty = VD->getType();
2366       else
2367         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2368 
2369       if (OldAlign == 0)
2370         OldAlign = S.Context.getTypeAlign(Ty);
2371       if (NewAlign == 0)
2372         NewAlign = S.Context.getTypeAlign(Ty);
2373     }
2374 
2375     if (OldAlign != NewAlign) {
2376       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2377         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2378         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2379       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2380     }
2381   }
2382 
2383   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2384     // C++11 [dcl.align]p6:
2385     //   if any declaration of an entity has an alignment-specifier,
2386     //   every defining declaration of that entity shall specify an
2387     //   equivalent alignment.
2388     // C11 6.7.5/7:
2389     //   If the definition of an object does not have an alignment
2390     //   specifier, any other declaration of that object shall also
2391     //   have no alignment specifier.
2392     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2393       << OldAlignasAttr;
2394     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2395       << OldAlignasAttr;
2396   }
2397 
2398   bool AnyAdded = false;
2399 
2400   // Ensure we have an attribute representing the strictest alignment.
2401   if (OldAlign > NewAlign) {
2402     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2403     Clone->setInherited(true);
2404     New->addAttr(Clone);
2405     AnyAdded = true;
2406   }
2407 
2408   // Ensure we have an alignas attribute if the old declaration had one.
2409   if (OldAlignasAttr && !NewAlignasAttr &&
2410       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2411     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2412     Clone->setInherited(true);
2413     New->addAttr(Clone);
2414     AnyAdded = true;
2415   }
2416 
2417   return AnyAdded;
2418 }
2419 
2420 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2421                                const InheritableAttr *Attr,
2422                                Sema::AvailabilityMergeKind AMK) {
2423   // This function copies an attribute Attr from a previous declaration to the
2424   // new declaration D if the new declaration doesn't itself have that attribute
2425   // yet or if that attribute allows duplicates.
2426   // If you're adding a new attribute that requires logic different from
2427   // "use explicit attribute on decl if present, else use attribute from
2428   // previous decl", for example if the attribute needs to be consistent
2429   // between redeclarations, you need to call a custom merge function here.
2430   InheritableAttr *NewAttr = nullptr;
2431   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2432   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2433     NewAttr = S.mergeAvailabilityAttr(
2434         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2435         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2436         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2437         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2438   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2439     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2440                                     AttrSpellingListIndex);
2441   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2442     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2443                                         AttrSpellingListIndex);
2444   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2445     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2446                                    AttrSpellingListIndex);
2447   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2448     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2449                                    AttrSpellingListIndex);
2450   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2451     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2452                                 FA->getFormatIdx(), FA->getFirstArg(),
2453                                 AttrSpellingListIndex);
2454   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2455     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2456                                  AttrSpellingListIndex);
2457   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2458     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2459                                  AttrSpellingListIndex);
2460   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2461     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2462                                        AttrSpellingListIndex,
2463                                        IA->getSemanticSpelling());
2464   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2465     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2466                                       &S.Context.Idents.get(AA->getSpelling()),
2467                                       AttrSpellingListIndex);
2468   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2469            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2470             isa<CUDAGlobalAttr>(Attr))) {
2471     // CUDA target attributes are part of function signature for
2472     // overloading purposes and must not be merged.
2473     return false;
2474   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2475     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2476   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2477     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2478   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2479     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2480   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2481     NewAttr = S.mergeCommonAttr(D, *CommonA);
2482   else if (isa<AlignedAttr>(Attr))
2483     // AlignedAttrs are handled separately, because we need to handle all
2484     // such attributes on a declaration at the same time.
2485     NewAttr = nullptr;
2486   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2487            (AMK == Sema::AMK_Override ||
2488             AMK == Sema::AMK_ProtocolImplementation))
2489     NewAttr = nullptr;
2490   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2491     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2492                               UA->getGuid());
2493   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2494     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2495   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2496     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2497   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2498     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2499 
2500   if (NewAttr) {
2501     NewAttr->setInherited(true);
2502     D->addAttr(NewAttr);
2503     if (isa<MSInheritanceAttr>(NewAttr))
2504       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2505     return true;
2506   }
2507 
2508   return false;
2509 }
2510 
2511 static const NamedDecl *getDefinition(const Decl *D) {
2512   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2513     return TD->getDefinition();
2514   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2515     const VarDecl *Def = VD->getDefinition();
2516     if (Def)
2517       return Def;
2518     return VD->getActingDefinition();
2519   }
2520   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2521     return FD->getDefinition();
2522   return nullptr;
2523 }
2524 
2525 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2526   for (const auto *Attribute : D->attrs())
2527     if (Attribute->getKind() == Kind)
2528       return true;
2529   return false;
2530 }
2531 
2532 /// checkNewAttributesAfterDef - If we already have a definition, check that
2533 /// there are no new attributes in this declaration.
2534 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2535   if (!New->hasAttrs())
2536     return;
2537 
2538   const NamedDecl *Def = getDefinition(Old);
2539   if (!Def || Def == New)
2540     return;
2541 
2542   AttrVec &NewAttributes = New->getAttrs();
2543   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2544     const Attr *NewAttribute = NewAttributes[I];
2545 
2546     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2547       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2548         Sema::SkipBodyInfo SkipBody;
2549         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2550 
2551         // If we're skipping this definition, drop the "alias" attribute.
2552         if (SkipBody.ShouldSkip) {
2553           NewAttributes.erase(NewAttributes.begin() + I);
2554           --E;
2555           continue;
2556         }
2557       } else {
2558         VarDecl *VD = cast<VarDecl>(New);
2559         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2560                                 VarDecl::TentativeDefinition
2561                             ? diag::err_alias_after_tentative
2562                             : diag::err_redefinition;
2563         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2564         if (Diag == diag::err_redefinition)
2565           S.notePreviousDefinition(Def, VD->getLocation());
2566         else
2567           S.Diag(Def->getLocation(), diag::note_previous_definition);
2568         VD->setInvalidDecl();
2569       }
2570       ++I;
2571       continue;
2572     }
2573 
2574     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2575       // Tentative definitions are only interesting for the alias check above.
2576       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2577         ++I;
2578         continue;
2579       }
2580     }
2581 
2582     if (hasAttribute(Def, NewAttribute->getKind())) {
2583       ++I;
2584       continue; // regular attr merging will take care of validating this.
2585     }
2586 
2587     if (isa<C11NoReturnAttr>(NewAttribute)) {
2588       // C's _Noreturn is allowed to be added to a function after it is defined.
2589       ++I;
2590       continue;
2591     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2592       if (AA->isAlignas()) {
2593         // C++11 [dcl.align]p6:
2594         //   if any declaration of an entity has an alignment-specifier,
2595         //   every defining declaration of that entity shall specify an
2596         //   equivalent alignment.
2597         // C11 6.7.5/7:
2598         //   If the definition of an object does not have an alignment
2599         //   specifier, any other declaration of that object shall also
2600         //   have no alignment specifier.
2601         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2602           << AA;
2603         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2604           << AA;
2605         NewAttributes.erase(NewAttributes.begin() + I);
2606         --E;
2607         continue;
2608       }
2609     }
2610 
2611     S.Diag(NewAttribute->getLocation(),
2612            diag::warn_attribute_precede_definition);
2613     S.Diag(Def->getLocation(), diag::note_previous_definition);
2614     NewAttributes.erase(NewAttributes.begin() + I);
2615     --E;
2616   }
2617 }
2618 
2619 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2620 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2621                                AvailabilityMergeKind AMK) {
2622   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2623     UsedAttr *NewAttr = OldAttr->clone(Context);
2624     NewAttr->setInherited(true);
2625     New->addAttr(NewAttr);
2626   }
2627 
2628   if (!Old->hasAttrs() && !New->hasAttrs())
2629     return;
2630 
2631   // Attributes declared post-definition are currently ignored.
2632   checkNewAttributesAfterDef(*this, New, Old);
2633 
2634   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2635     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2636       if (OldA->getLabel() != NewA->getLabel()) {
2637         // This redeclaration changes __asm__ label.
2638         Diag(New->getLocation(), diag::err_different_asm_label);
2639         Diag(OldA->getLocation(), diag::note_previous_declaration);
2640       }
2641     } else if (Old->isUsed()) {
2642       // This redeclaration adds an __asm__ label to a declaration that has
2643       // already been ODR-used.
2644       Diag(New->getLocation(), diag::err_late_asm_label_name)
2645         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2646     }
2647   }
2648 
2649   // Re-declaration cannot add abi_tag's.
2650   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2651     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2652       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2653         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2654                       NewTag) == OldAbiTagAttr->tags_end()) {
2655           Diag(NewAbiTagAttr->getLocation(),
2656                diag::err_new_abi_tag_on_redeclaration)
2657               << NewTag;
2658           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2659         }
2660       }
2661     } else {
2662       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2663       Diag(Old->getLocation(), diag::note_previous_declaration);
2664     }
2665   }
2666 
2667   // This redeclaration adds a section attribute.
2668   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2669     if (auto *VD = dyn_cast<VarDecl>(New)) {
2670       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2671         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2672         Diag(Old->getLocation(), diag::note_previous_declaration);
2673       }
2674     }
2675   }
2676 
2677   // Redeclaration adds code-seg attribute.
2678   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2679   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2680       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2681     Diag(New->getLocation(), diag::warn_mismatched_section)
2682          << 0 /*codeseg*/;
2683     Diag(Old->getLocation(), diag::note_previous_declaration);
2684   }
2685 
2686   if (!Old->hasAttrs())
2687     return;
2688 
2689   bool foundAny = New->hasAttrs();
2690 
2691   // Ensure that any moving of objects within the allocated map is done before
2692   // we process them.
2693   if (!foundAny) New->setAttrs(AttrVec());
2694 
2695   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2696     // Ignore deprecated/unavailable/availability attributes if requested.
2697     AvailabilityMergeKind LocalAMK = AMK_None;
2698     if (isa<DeprecatedAttr>(I) ||
2699         isa<UnavailableAttr>(I) ||
2700         isa<AvailabilityAttr>(I)) {
2701       switch (AMK) {
2702       case AMK_None:
2703         continue;
2704 
2705       case AMK_Redeclaration:
2706       case AMK_Override:
2707       case AMK_ProtocolImplementation:
2708         LocalAMK = AMK;
2709         break;
2710       }
2711     }
2712 
2713     // Already handled.
2714     if (isa<UsedAttr>(I))
2715       continue;
2716 
2717     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2718       foundAny = true;
2719   }
2720 
2721   if (mergeAlignedAttrs(*this, New, Old))
2722     foundAny = true;
2723 
2724   if (!foundAny) New->dropAttrs();
2725 }
2726 
2727 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2728 /// to the new one.
2729 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2730                                      const ParmVarDecl *oldDecl,
2731                                      Sema &S) {
2732   // C++11 [dcl.attr.depend]p2:
2733   //   The first declaration of a function shall specify the
2734   //   carries_dependency attribute for its declarator-id if any declaration
2735   //   of the function specifies the carries_dependency attribute.
2736   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2737   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2738     S.Diag(CDA->getLocation(),
2739            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2740     // Find the first declaration of the parameter.
2741     // FIXME: Should we build redeclaration chains for function parameters?
2742     const FunctionDecl *FirstFD =
2743       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2744     const ParmVarDecl *FirstVD =
2745       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2746     S.Diag(FirstVD->getLocation(),
2747            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2748   }
2749 
2750   if (!oldDecl->hasAttrs())
2751     return;
2752 
2753   bool foundAny = newDecl->hasAttrs();
2754 
2755   // Ensure that any moving of objects within the allocated map is
2756   // done before we process them.
2757   if (!foundAny) newDecl->setAttrs(AttrVec());
2758 
2759   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2760     if (!DeclHasAttr(newDecl, I)) {
2761       InheritableAttr *newAttr =
2762         cast<InheritableParamAttr>(I->clone(S.Context));
2763       newAttr->setInherited(true);
2764       newDecl->addAttr(newAttr);
2765       foundAny = true;
2766     }
2767   }
2768 
2769   if (!foundAny) newDecl->dropAttrs();
2770 }
2771 
2772 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2773                                 const ParmVarDecl *OldParam,
2774                                 Sema &S) {
2775   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2776     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2777       if (*Oldnullability != *Newnullability) {
2778         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2779           << DiagNullabilityKind(
2780                *Newnullability,
2781                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2782                 != 0))
2783           << DiagNullabilityKind(
2784                *Oldnullability,
2785                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2786                 != 0));
2787         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2788       }
2789     } else {
2790       QualType NewT = NewParam->getType();
2791       NewT = S.Context.getAttributedType(
2792                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2793                          NewT, NewT);
2794       NewParam->setType(NewT);
2795     }
2796   }
2797 }
2798 
2799 namespace {
2800 
2801 /// Used in MergeFunctionDecl to keep track of function parameters in
2802 /// C.
2803 struct GNUCompatibleParamWarning {
2804   ParmVarDecl *OldParm;
2805   ParmVarDecl *NewParm;
2806   QualType PromotedType;
2807 };
2808 
2809 } // end anonymous namespace
2810 
2811 /// getSpecialMember - get the special member enum for a method.
2812 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2813   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2814     if (Ctor->isDefaultConstructor())
2815       return Sema::CXXDefaultConstructor;
2816 
2817     if (Ctor->isCopyConstructor())
2818       return Sema::CXXCopyConstructor;
2819 
2820     if (Ctor->isMoveConstructor())
2821       return Sema::CXXMoveConstructor;
2822   } else if (isa<CXXDestructorDecl>(MD)) {
2823     return Sema::CXXDestructor;
2824   } else if (MD->isCopyAssignmentOperator()) {
2825     return Sema::CXXCopyAssignment;
2826   } else if (MD->isMoveAssignmentOperator()) {
2827     return Sema::CXXMoveAssignment;
2828   }
2829 
2830   return Sema::CXXInvalid;
2831 }
2832 
2833 // Determine whether the previous declaration was a definition, implicit
2834 // declaration, or a declaration.
2835 template <typename T>
2836 static std::pair<diag::kind, SourceLocation>
2837 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2838   diag::kind PrevDiag;
2839   SourceLocation OldLocation = Old->getLocation();
2840   if (Old->isThisDeclarationADefinition())
2841     PrevDiag = diag::note_previous_definition;
2842   else if (Old->isImplicit()) {
2843     PrevDiag = diag::note_previous_implicit_declaration;
2844     if (OldLocation.isInvalid())
2845       OldLocation = New->getLocation();
2846   } else
2847     PrevDiag = diag::note_previous_declaration;
2848   return std::make_pair(PrevDiag, OldLocation);
2849 }
2850 
2851 /// canRedefineFunction - checks if a function can be redefined. Currently,
2852 /// only extern inline functions can be redefined, and even then only in
2853 /// GNU89 mode.
2854 static bool canRedefineFunction(const FunctionDecl *FD,
2855                                 const LangOptions& LangOpts) {
2856   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2857           !LangOpts.CPlusPlus &&
2858           FD->isInlineSpecified() &&
2859           FD->getStorageClass() == SC_Extern);
2860 }
2861 
2862 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2863   const AttributedType *AT = T->getAs<AttributedType>();
2864   while (AT && !AT->isCallingConv())
2865     AT = AT->getModifiedType()->getAs<AttributedType>();
2866   return AT;
2867 }
2868 
2869 template <typename T>
2870 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2871   const DeclContext *DC = Old->getDeclContext();
2872   if (DC->isRecord())
2873     return false;
2874 
2875   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2876   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2877     return true;
2878   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2879     return true;
2880   return false;
2881 }
2882 
2883 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2884 static bool isExternC(VarTemplateDecl *) { return false; }
2885 
2886 /// Check whether a redeclaration of an entity introduced by a
2887 /// using-declaration is valid, given that we know it's not an overload
2888 /// (nor a hidden tag declaration).
2889 template<typename ExpectedDecl>
2890 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2891                                    ExpectedDecl *New) {
2892   // C++11 [basic.scope.declarative]p4:
2893   //   Given a set of declarations in a single declarative region, each of
2894   //   which specifies the same unqualified name,
2895   //   -- they shall all refer to the same entity, or all refer to functions
2896   //      and function templates; or
2897   //   -- exactly one declaration shall declare a class name or enumeration
2898   //      name that is not a typedef name and the other declarations shall all
2899   //      refer to the same variable or enumerator, or all refer to functions
2900   //      and function templates; in this case the class name or enumeration
2901   //      name is hidden (3.3.10).
2902 
2903   // C++11 [namespace.udecl]p14:
2904   //   If a function declaration in namespace scope or block scope has the
2905   //   same name and the same parameter-type-list as a function introduced
2906   //   by a using-declaration, and the declarations do not declare the same
2907   //   function, the program is ill-formed.
2908 
2909   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2910   if (Old &&
2911       !Old->getDeclContext()->getRedeclContext()->Equals(
2912           New->getDeclContext()->getRedeclContext()) &&
2913       !(isExternC(Old) && isExternC(New)))
2914     Old = nullptr;
2915 
2916   if (!Old) {
2917     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2918     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2919     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2920     return true;
2921   }
2922   return false;
2923 }
2924 
2925 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2926                                             const FunctionDecl *B) {
2927   assert(A->getNumParams() == B->getNumParams());
2928 
2929   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2930     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2931     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2932     if (AttrA == AttrB)
2933       return true;
2934     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2935   };
2936 
2937   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2938 }
2939 
2940 /// If necessary, adjust the semantic declaration context for a qualified
2941 /// declaration to name the correct inline namespace within the qualifier.
2942 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2943                                                DeclaratorDecl *OldD) {
2944   // The only case where we need to update the DeclContext is when
2945   // redeclaration lookup for a qualified name finds a declaration
2946   // in an inline namespace within the context named by the qualifier:
2947   //
2948   //   inline namespace N { int f(); }
2949   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2950   //
2951   // For unqualified declarations, the semantic context *can* change
2952   // along the redeclaration chain (for local extern declarations,
2953   // extern "C" declarations, and friend declarations in particular).
2954   if (!NewD->getQualifier())
2955     return;
2956 
2957   // NewD is probably already in the right context.
2958   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2959   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2960   if (NamedDC->Equals(SemaDC))
2961     return;
2962 
2963   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2964           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2965          "unexpected context for redeclaration");
2966 
2967   auto *LexDC = NewD->getLexicalDeclContext();
2968   auto FixSemaDC = [=](NamedDecl *D) {
2969     if (!D)
2970       return;
2971     D->setDeclContext(SemaDC);
2972     D->setLexicalDeclContext(LexDC);
2973   };
2974 
2975   FixSemaDC(NewD);
2976   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2977     FixSemaDC(FD->getDescribedFunctionTemplate());
2978   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2979     FixSemaDC(VD->getDescribedVarTemplate());
2980 }
2981 
2982 /// MergeFunctionDecl - We just parsed a function 'New' from
2983 /// declarator D which has the same name and scope as a previous
2984 /// declaration 'Old'.  Figure out how to resolve this situation,
2985 /// merging decls or emitting diagnostics as appropriate.
2986 ///
2987 /// In C++, New and Old must be declarations that are not
2988 /// overloaded. Use IsOverload to determine whether New and Old are
2989 /// overloaded, and to select the Old declaration that New should be
2990 /// merged with.
2991 ///
2992 /// Returns true if there was an error, false otherwise.
2993 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2994                              Scope *S, bool MergeTypeWithOld) {
2995   // Verify the old decl was also a function.
2996   FunctionDecl *Old = OldD->getAsFunction();
2997   if (!Old) {
2998     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2999       if (New->getFriendObjectKind()) {
3000         Diag(New->getLocation(), diag::err_using_decl_friend);
3001         Diag(Shadow->getTargetDecl()->getLocation(),
3002              diag::note_using_decl_target);
3003         Diag(Shadow->getUsingDecl()->getLocation(),
3004              diag::note_using_decl) << 0;
3005         return true;
3006       }
3007 
3008       // Check whether the two declarations might declare the same function.
3009       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3010         return true;
3011       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3012     } else {
3013       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3014         << New->getDeclName();
3015       notePreviousDefinition(OldD, New->getLocation());
3016       return true;
3017     }
3018   }
3019 
3020   // If the old declaration is invalid, just give up here.
3021   if (Old->isInvalidDecl())
3022     return true;
3023 
3024   // Disallow redeclaration of some builtins.
3025   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3026     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3027     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3028         << Old << Old->getType();
3029     return true;
3030   }
3031 
3032   diag::kind PrevDiag;
3033   SourceLocation OldLocation;
3034   std::tie(PrevDiag, OldLocation) =
3035       getNoteDiagForInvalidRedeclaration(Old, New);
3036 
3037   // Don't complain about this if we're in GNU89 mode and the old function
3038   // is an extern inline function.
3039   // Don't complain about specializations. They are not supposed to have
3040   // storage classes.
3041   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3042       New->getStorageClass() == SC_Static &&
3043       Old->hasExternalFormalLinkage() &&
3044       !New->getTemplateSpecializationInfo() &&
3045       !canRedefineFunction(Old, getLangOpts())) {
3046     if (getLangOpts().MicrosoftExt) {
3047       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3048       Diag(OldLocation, PrevDiag);
3049     } else {
3050       Diag(New->getLocation(), diag::err_static_non_static) << New;
3051       Diag(OldLocation, PrevDiag);
3052       return true;
3053     }
3054   }
3055 
3056   if (New->hasAttr<InternalLinkageAttr>() &&
3057       !Old->hasAttr<InternalLinkageAttr>()) {
3058     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3059         << New->getDeclName();
3060     notePreviousDefinition(Old, New->getLocation());
3061     New->dropAttr<InternalLinkageAttr>();
3062   }
3063 
3064   if (CheckRedeclarationModuleOwnership(New, Old))
3065     return true;
3066 
3067   if (!getLangOpts().CPlusPlus) {
3068     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3069     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3070       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3071         << New << OldOvl;
3072 
3073       // Try our best to find a decl that actually has the overloadable
3074       // attribute for the note. In most cases (e.g. programs with only one
3075       // broken declaration/definition), this won't matter.
3076       //
3077       // FIXME: We could do this if we juggled some extra state in
3078       // OverloadableAttr, rather than just removing it.
3079       const Decl *DiagOld = Old;
3080       if (OldOvl) {
3081         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3082           const auto *A = D->getAttr<OverloadableAttr>();
3083           return A && !A->isImplicit();
3084         });
3085         // If we've implicitly added *all* of the overloadable attrs to this
3086         // chain, emitting a "previous redecl" note is pointless.
3087         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3088       }
3089 
3090       if (DiagOld)
3091         Diag(DiagOld->getLocation(),
3092              diag::note_attribute_overloadable_prev_overload)
3093           << OldOvl;
3094 
3095       if (OldOvl)
3096         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3097       else
3098         New->dropAttr<OverloadableAttr>();
3099     }
3100   }
3101 
3102   // If a function is first declared with a calling convention, but is later
3103   // declared or defined without one, all following decls assume the calling
3104   // convention of the first.
3105   //
3106   // It's OK if a function is first declared without a calling convention,
3107   // but is later declared or defined with the default calling convention.
3108   //
3109   // To test if either decl has an explicit calling convention, we look for
3110   // AttributedType sugar nodes on the type as written.  If they are missing or
3111   // were canonicalized away, we assume the calling convention was implicit.
3112   //
3113   // Note also that we DO NOT return at this point, because we still have
3114   // other tests to run.
3115   QualType OldQType = Context.getCanonicalType(Old->getType());
3116   QualType NewQType = Context.getCanonicalType(New->getType());
3117   const FunctionType *OldType = cast<FunctionType>(OldQType);
3118   const FunctionType *NewType = cast<FunctionType>(NewQType);
3119   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3120   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3121   bool RequiresAdjustment = false;
3122 
3123   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3124     FunctionDecl *First = Old->getFirstDecl();
3125     const FunctionType *FT =
3126         First->getType().getCanonicalType()->castAs<FunctionType>();
3127     FunctionType::ExtInfo FI = FT->getExtInfo();
3128     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3129     if (!NewCCExplicit) {
3130       // Inherit the CC from the previous declaration if it was specified
3131       // there but not here.
3132       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3133       RequiresAdjustment = true;
3134     } else {
3135       // Calling conventions aren't compatible, so complain.
3136       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3137       Diag(New->getLocation(), diag::err_cconv_change)
3138         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3139         << !FirstCCExplicit
3140         << (!FirstCCExplicit ? "" :
3141             FunctionType::getNameForCallConv(FI.getCC()));
3142 
3143       // Put the note on the first decl, since it is the one that matters.
3144       Diag(First->getLocation(), diag::note_previous_declaration);
3145       return true;
3146     }
3147   }
3148 
3149   // FIXME: diagnose the other way around?
3150   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3151     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3152     RequiresAdjustment = true;
3153   }
3154 
3155   // Merge regparm attribute.
3156   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3157       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3158     if (NewTypeInfo.getHasRegParm()) {
3159       Diag(New->getLocation(), diag::err_regparm_mismatch)
3160         << NewType->getRegParmType()
3161         << OldType->getRegParmType();
3162       Diag(OldLocation, diag::note_previous_declaration);
3163       return true;
3164     }
3165 
3166     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3167     RequiresAdjustment = true;
3168   }
3169 
3170   // Merge ns_returns_retained attribute.
3171   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3172     if (NewTypeInfo.getProducesResult()) {
3173       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3174           << "'ns_returns_retained'";
3175       Diag(OldLocation, diag::note_previous_declaration);
3176       return true;
3177     }
3178 
3179     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3180     RequiresAdjustment = true;
3181   }
3182 
3183   if (OldTypeInfo.getNoCallerSavedRegs() !=
3184       NewTypeInfo.getNoCallerSavedRegs()) {
3185     if (NewTypeInfo.getNoCallerSavedRegs()) {
3186       AnyX86NoCallerSavedRegistersAttr *Attr =
3187         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3188       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3189       Diag(OldLocation, diag::note_previous_declaration);
3190       return true;
3191     }
3192 
3193     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3194     RequiresAdjustment = true;
3195   }
3196 
3197   if (RequiresAdjustment) {
3198     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3199     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3200     New->setType(QualType(AdjustedType, 0));
3201     NewQType = Context.getCanonicalType(New->getType());
3202     NewType = cast<FunctionType>(NewQType);
3203   }
3204 
3205   // If this redeclaration makes the function inline, we may need to add it to
3206   // UndefinedButUsed.
3207   if (!Old->isInlined() && New->isInlined() &&
3208       !New->hasAttr<GNUInlineAttr>() &&
3209       !getLangOpts().GNUInline &&
3210       Old->isUsed(false) &&
3211       !Old->isDefined() && !New->isThisDeclarationADefinition())
3212     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3213                                            SourceLocation()));
3214 
3215   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3216   // about it.
3217   if (New->hasAttr<GNUInlineAttr>() &&
3218       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3219     UndefinedButUsed.erase(Old->getCanonicalDecl());
3220   }
3221 
3222   // If pass_object_size params don't match up perfectly, this isn't a valid
3223   // redeclaration.
3224   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3225       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3226     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3227         << New->getDeclName();
3228     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3229     return true;
3230   }
3231 
3232   if (getLangOpts().CPlusPlus) {
3233     // C++1z [over.load]p2
3234     //   Certain function declarations cannot be overloaded:
3235     //     -- Function declarations that differ only in the return type,
3236     //        the exception specification, or both cannot be overloaded.
3237 
3238     // Check the exception specifications match. This may recompute the type of
3239     // both Old and New if it resolved exception specifications, so grab the
3240     // types again after this. Because this updates the type, we do this before
3241     // any of the other checks below, which may update the "de facto" NewQType
3242     // but do not necessarily update the type of New.
3243     if (CheckEquivalentExceptionSpec(Old, New))
3244       return true;
3245     OldQType = Context.getCanonicalType(Old->getType());
3246     NewQType = Context.getCanonicalType(New->getType());
3247 
3248     // Go back to the type source info to compare the declared return types,
3249     // per C++1y [dcl.type.auto]p13:
3250     //   Redeclarations or specializations of a function or function template
3251     //   with a declared return type that uses a placeholder type shall also
3252     //   use that placeholder, not a deduced type.
3253     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3254     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3255     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3256         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3257                                        OldDeclaredReturnType)) {
3258       QualType ResQT;
3259       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3260           OldDeclaredReturnType->isObjCObjectPointerType())
3261         // FIXME: This does the wrong thing for a deduced return type.
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 the types are imprecise (due to dependent constructs in friends or
3427     // local extern declarations), it's OK if they differ. We'll check again
3428     // during instantiation.
3429     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3430       return false;
3431 
3432     // Fall through for conflicting redeclarations and redefinitions.
3433   }
3434 
3435   // C: Function types need to be compatible, not identical. This handles
3436   // duplicate function decls like "void f(int); void f(enum X);" properly.
3437   if (!getLangOpts().CPlusPlus &&
3438       Context.typesAreCompatible(OldQType, NewQType)) {
3439     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3440     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3441     const FunctionProtoType *OldProto = nullptr;
3442     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3443         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3444       // The old declaration provided a function prototype, but the
3445       // new declaration does not. Merge in the prototype.
3446       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3447       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3448       NewQType =
3449           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3450                                   OldProto->getExtProtoInfo());
3451       New->setType(NewQType);
3452       New->setHasInheritedPrototype();
3453 
3454       // Synthesize parameters with the same types.
3455       SmallVector<ParmVarDecl*, 16> Params;
3456       for (const auto &ParamType : OldProto->param_types()) {
3457         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3458                                                  SourceLocation(), nullptr,
3459                                                  ParamType, /*TInfo=*/nullptr,
3460                                                  SC_None, nullptr);
3461         Param->setScopeInfo(0, Params.size());
3462         Param->setImplicit();
3463         Params.push_back(Param);
3464       }
3465 
3466       New->setParams(Params);
3467     }
3468 
3469     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3470   }
3471 
3472   // GNU C permits a K&R definition to follow a prototype declaration
3473   // if the declared types of the parameters in the K&R definition
3474   // match the types in the prototype declaration, even when the
3475   // promoted types of the parameters from the K&R definition differ
3476   // from the types in the prototype. GCC then keeps the types from
3477   // the prototype.
3478   //
3479   // If a variadic prototype is followed by a non-variadic K&R definition,
3480   // the K&R definition becomes variadic.  This is sort of an edge case, but
3481   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3482   // C99 6.9.1p8.
3483   if (!getLangOpts().CPlusPlus &&
3484       Old->hasPrototype() && !New->hasPrototype() &&
3485       New->getType()->getAs<FunctionProtoType>() &&
3486       Old->getNumParams() == New->getNumParams()) {
3487     SmallVector<QualType, 16> ArgTypes;
3488     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3489     const FunctionProtoType *OldProto
3490       = Old->getType()->getAs<FunctionProtoType>();
3491     const FunctionProtoType *NewProto
3492       = New->getType()->getAs<FunctionProtoType>();
3493 
3494     // Determine whether this is the GNU C extension.
3495     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3496                                                NewProto->getReturnType());
3497     bool LooseCompatible = !MergedReturn.isNull();
3498     for (unsigned Idx = 0, End = Old->getNumParams();
3499          LooseCompatible && Idx != End; ++Idx) {
3500       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3501       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3502       if (Context.typesAreCompatible(OldParm->getType(),
3503                                      NewProto->getParamType(Idx))) {
3504         ArgTypes.push_back(NewParm->getType());
3505       } else if (Context.typesAreCompatible(OldParm->getType(),
3506                                             NewParm->getType(),
3507                                             /*CompareUnqualified=*/true)) {
3508         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3509                                            NewProto->getParamType(Idx) };
3510         Warnings.push_back(Warn);
3511         ArgTypes.push_back(NewParm->getType());
3512       } else
3513         LooseCompatible = false;
3514     }
3515 
3516     if (LooseCompatible) {
3517       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3518         Diag(Warnings[Warn].NewParm->getLocation(),
3519              diag::ext_param_promoted_not_compatible_with_prototype)
3520           << Warnings[Warn].PromotedType
3521           << Warnings[Warn].OldParm->getType();
3522         if (Warnings[Warn].OldParm->getLocation().isValid())
3523           Diag(Warnings[Warn].OldParm->getLocation(),
3524                diag::note_previous_declaration);
3525       }
3526 
3527       if (MergeTypeWithOld)
3528         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3529                                              OldProto->getExtProtoInfo()));
3530       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3531     }
3532 
3533     // Fall through to diagnose conflicting types.
3534   }
3535 
3536   // A function that has already been declared has been redeclared or
3537   // defined with a different type; show an appropriate diagnostic.
3538 
3539   // If the previous declaration was an implicitly-generated builtin
3540   // declaration, then at the very least we should use a specialized note.
3541   unsigned BuiltinID;
3542   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3543     // If it's actually a library-defined builtin function like 'malloc'
3544     // or 'printf', just warn about the incompatible redeclaration.
3545     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3546       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3547       Diag(OldLocation, diag::note_previous_builtin_declaration)
3548         << Old << Old->getType();
3549 
3550       // If this is a global redeclaration, just forget hereafter
3551       // about the "builtin-ness" of the function.
3552       //
3553       // Doing this for local extern declarations is problematic.  If
3554       // the builtin declaration remains visible, a second invalid
3555       // local declaration will produce a hard error; if it doesn't
3556       // remain visible, a single bogus local redeclaration (which is
3557       // actually only a warning) could break all the downstream code.
3558       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3559         New->getIdentifier()->revertBuiltin();
3560 
3561       return false;
3562     }
3563 
3564     PrevDiag = diag::note_previous_builtin_declaration;
3565   }
3566 
3567   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3568   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3569   return true;
3570 }
3571 
3572 /// Completes the merge of two function declarations that are
3573 /// known to be compatible.
3574 ///
3575 /// This routine handles the merging of attributes and other
3576 /// properties of function declarations from the old declaration to
3577 /// the new declaration, once we know that New is in fact a
3578 /// redeclaration of Old.
3579 ///
3580 /// \returns false
3581 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3582                                         Scope *S, bool MergeTypeWithOld) {
3583   // Merge the attributes
3584   mergeDeclAttributes(New, Old);
3585 
3586   // Merge "pure" flag.
3587   if (Old->isPure())
3588     New->setPure();
3589 
3590   // Merge "used" flag.
3591   if (Old->getMostRecentDecl()->isUsed(false))
3592     New->setIsUsed();
3593 
3594   // Merge attributes from the parameters.  These can mismatch with K&R
3595   // declarations.
3596   if (New->getNumParams() == Old->getNumParams())
3597       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3598         ParmVarDecl *NewParam = New->getParamDecl(i);
3599         ParmVarDecl *OldParam = Old->getParamDecl(i);
3600         mergeParamDeclAttributes(NewParam, OldParam, *this);
3601         mergeParamDeclTypes(NewParam, OldParam, *this);
3602       }
3603 
3604   if (getLangOpts().CPlusPlus)
3605     return MergeCXXFunctionDecl(New, Old, S);
3606 
3607   // Merge the function types so the we get the composite types for the return
3608   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3609   // was visible.
3610   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3611   if (!Merged.isNull() && MergeTypeWithOld)
3612     New->setType(Merged);
3613 
3614   return false;
3615 }
3616 
3617 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3618                                 ObjCMethodDecl *oldMethod) {
3619   // Merge the attributes, including deprecated/unavailable
3620   AvailabilityMergeKind MergeKind =
3621     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3622       ? AMK_ProtocolImplementation
3623       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3624                                                        : AMK_Override;
3625 
3626   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3627 
3628   // Merge attributes from the parameters.
3629   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3630                                        oe = oldMethod->param_end();
3631   for (ObjCMethodDecl::param_iterator
3632          ni = newMethod->param_begin(), ne = newMethod->param_end();
3633        ni != ne && oi != oe; ++ni, ++oi)
3634     mergeParamDeclAttributes(*ni, *oi, *this);
3635 
3636   CheckObjCMethodOverride(newMethod, oldMethod);
3637 }
3638 
3639 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3640   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3641 
3642   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3643          ? diag::err_redefinition_different_type
3644          : diag::err_redeclaration_different_type)
3645     << New->getDeclName() << New->getType() << Old->getType();
3646 
3647   diag::kind PrevDiag;
3648   SourceLocation OldLocation;
3649   std::tie(PrevDiag, OldLocation)
3650     = getNoteDiagForInvalidRedeclaration(Old, New);
3651   S.Diag(OldLocation, PrevDiag);
3652   New->setInvalidDecl();
3653 }
3654 
3655 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3656 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3657 /// emitting diagnostics as appropriate.
3658 ///
3659 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3660 /// to here in AddInitializerToDecl. We can't check them before the initializer
3661 /// is attached.
3662 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3663                              bool MergeTypeWithOld) {
3664   if (New->isInvalidDecl() || Old->isInvalidDecl())
3665     return;
3666 
3667   QualType MergedT;
3668   if (getLangOpts().CPlusPlus) {
3669     if (New->getType()->isUndeducedType()) {
3670       // We don't know what the new type is until the initializer is attached.
3671       return;
3672     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3673       // These could still be something that needs exception specs checked.
3674       return MergeVarDeclExceptionSpecs(New, Old);
3675     }
3676     // C++ [basic.link]p10:
3677     //   [...] the types specified by all declarations referring to a given
3678     //   object or function shall be identical, except that declarations for an
3679     //   array object can specify array types that differ by the presence or
3680     //   absence of a major array bound (8.3.4).
3681     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3682       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3683       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3684 
3685       // We are merging a variable declaration New into Old. If it has an array
3686       // bound, and that bound differs from Old's bound, we should diagnose the
3687       // mismatch.
3688       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3689         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3690              PrevVD = PrevVD->getPreviousDecl()) {
3691           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3692           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3693             continue;
3694 
3695           if (!Context.hasSameType(NewArray, PrevVDTy))
3696             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3697         }
3698       }
3699 
3700       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3701         if (Context.hasSameType(OldArray->getElementType(),
3702                                 NewArray->getElementType()))
3703           MergedT = New->getType();
3704       }
3705       // FIXME: Check visibility. New is hidden but has a complete type. If New
3706       // has no array bound, it should not inherit one from Old, if Old is not
3707       // visible.
3708       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3709         if (Context.hasSameType(OldArray->getElementType(),
3710                                 NewArray->getElementType()))
3711           MergedT = Old->getType();
3712       }
3713     }
3714     else if (New->getType()->isObjCObjectPointerType() &&
3715                Old->getType()->isObjCObjectPointerType()) {
3716       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3717                                               Old->getType());
3718     }
3719   } else {
3720     // C 6.2.7p2:
3721     //   All declarations that refer to the same object or function shall have
3722     //   compatible type.
3723     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3724   }
3725   if (MergedT.isNull()) {
3726     // It's OK if we couldn't merge types if either type is dependent, for a
3727     // block-scope variable. In other cases (static data members of class
3728     // templates, variable templates, ...), we require the types to be
3729     // equivalent.
3730     // FIXME: The C++ standard doesn't say anything about this.
3731     if ((New->getType()->isDependentType() ||
3732          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3733       // If the old type was dependent, we can't merge with it, so the new type
3734       // becomes dependent for now. We'll reproduce the original type when we
3735       // instantiate the TypeSourceInfo for the variable.
3736       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3737         New->setType(Context.DependentTy);
3738       return;
3739     }
3740     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3741   }
3742 
3743   // Don't actually update the type on the new declaration if the old
3744   // declaration was an extern declaration in a different scope.
3745   if (MergeTypeWithOld)
3746     New->setType(MergedT);
3747 }
3748 
3749 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3750                                   LookupResult &Previous) {
3751   // C11 6.2.7p4:
3752   //   For an identifier with internal or external linkage declared
3753   //   in a scope in which a prior declaration of that identifier is
3754   //   visible, if the prior declaration specifies internal or
3755   //   external linkage, the type of the identifier at the later
3756   //   declaration becomes the composite type.
3757   //
3758   // If the variable isn't visible, we do not merge with its type.
3759   if (Previous.isShadowed())
3760     return false;
3761 
3762   if (S.getLangOpts().CPlusPlus) {
3763     // C++11 [dcl.array]p3:
3764     //   If there is a preceding declaration of the entity in the same
3765     //   scope in which the bound was specified, an omitted array bound
3766     //   is taken to be the same as in that earlier declaration.
3767     return NewVD->isPreviousDeclInSameBlockScope() ||
3768            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3769             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3770   } else {
3771     // If the old declaration was function-local, don't merge with its
3772     // type unless we're in the same function.
3773     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3774            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3775   }
3776 }
3777 
3778 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3779 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3780 /// situation, merging decls or emitting diagnostics as appropriate.
3781 ///
3782 /// Tentative definition rules (C99 6.9.2p2) are checked by
3783 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3784 /// definitions here, since the initializer hasn't been attached.
3785 ///
3786 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3787   // If the new decl is already invalid, don't do any other checking.
3788   if (New->isInvalidDecl())
3789     return;
3790 
3791   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3792     return;
3793 
3794   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3795 
3796   // Verify the old decl was also a variable or variable template.
3797   VarDecl *Old = nullptr;
3798   VarTemplateDecl *OldTemplate = nullptr;
3799   if (Previous.isSingleResult()) {
3800     if (NewTemplate) {
3801       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3802       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3803 
3804       if (auto *Shadow =
3805               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3806         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3807           return New->setInvalidDecl();
3808     } else {
3809       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3810 
3811       if (auto *Shadow =
3812               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3813         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3814           return New->setInvalidDecl();
3815     }
3816   }
3817   if (!Old) {
3818     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3819         << New->getDeclName();
3820     notePreviousDefinition(Previous.getRepresentativeDecl(),
3821                            New->getLocation());
3822     return New->setInvalidDecl();
3823   }
3824 
3825   // Ensure the template parameters are compatible.
3826   if (NewTemplate &&
3827       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3828                                       OldTemplate->getTemplateParameters(),
3829                                       /*Complain=*/true, TPL_TemplateMatch))
3830     return New->setInvalidDecl();
3831 
3832   // C++ [class.mem]p1:
3833   //   A member shall not be declared twice in the member-specification [...]
3834   //
3835   // Here, we need only consider static data members.
3836   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3837     Diag(New->getLocation(), diag::err_duplicate_member)
3838       << New->getIdentifier();
3839     Diag(Old->getLocation(), diag::note_previous_declaration);
3840     New->setInvalidDecl();
3841   }
3842 
3843   mergeDeclAttributes(New, Old);
3844   // Warn if an already-declared variable is made a weak_import in a subsequent
3845   // declaration
3846   if (New->hasAttr<WeakImportAttr>() &&
3847       Old->getStorageClass() == SC_None &&
3848       !Old->hasAttr<WeakImportAttr>()) {
3849     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3850     notePreviousDefinition(Old, New->getLocation());
3851     // Remove weak_import attribute on new declaration.
3852     New->dropAttr<WeakImportAttr>();
3853   }
3854 
3855   if (New->hasAttr<InternalLinkageAttr>() &&
3856       !Old->hasAttr<InternalLinkageAttr>()) {
3857     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3858         << New->getDeclName();
3859     notePreviousDefinition(Old, New->getLocation());
3860     New->dropAttr<InternalLinkageAttr>();
3861   }
3862 
3863   // Merge the types.
3864   VarDecl *MostRecent = Old->getMostRecentDecl();
3865   if (MostRecent != Old) {
3866     MergeVarDeclTypes(New, MostRecent,
3867                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3868     if (New->isInvalidDecl())
3869       return;
3870   }
3871 
3872   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3873   if (New->isInvalidDecl())
3874     return;
3875 
3876   diag::kind PrevDiag;
3877   SourceLocation OldLocation;
3878   std::tie(PrevDiag, OldLocation) =
3879       getNoteDiagForInvalidRedeclaration(Old, New);
3880 
3881   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3882   if (New->getStorageClass() == SC_Static &&
3883       !New->isStaticDataMember() &&
3884       Old->hasExternalFormalLinkage()) {
3885     if (getLangOpts().MicrosoftExt) {
3886       Diag(New->getLocation(), diag::ext_static_non_static)
3887           << New->getDeclName();
3888       Diag(OldLocation, PrevDiag);
3889     } else {
3890       Diag(New->getLocation(), diag::err_static_non_static)
3891           << New->getDeclName();
3892       Diag(OldLocation, PrevDiag);
3893       return New->setInvalidDecl();
3894     }
3895   }
3896   // C99 6.2.2p4:
3897   //   For an identifier declared with the storage-class specifier
3898   //   extern in a scope in which a prior declaration of that
3899   //   identifier is visible,23) if the prior declaration specifies
3900   //   internal or external linkage, the linkage of the identifier at
3901   //   the later declaration is the same as the linkage specified at
3902   //   the prior declaration. If no prior declaration is visible, or
3903   //   if the prior declaration specifies no linkage, then the
3904   //   identifier has external linkage.
3905   if (New->hasExternalStorage() && Old->hasLinkage())
3906     /* Okay */;
3907   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3908            !New->isStaticDataMember() &&
3909            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3910     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3911     Diag(OldLocation, PrevDiag);
3912     return New->setInvalidDecl();
3913   }
3914 
3915   // Check if extern is followed by non-extern and vice-versa.
3916   if (New->hasExternalStorage() &&
3917       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3918     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3919     Diag(OldLocation, PrevDiag);
3920     return New->setInvalidDecl();
3921   }
3922   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3923       !New->hasExternalStorage()) {
3924     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3925     Diag(OldLocation, PrevDiag);
3926     return New->setInvalidDecl();
3927   }
3928 
3929   if (CheckRedeclarationModuleOwnership(New, Old))
3930     return;
3931 
3932   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3933 
3934   // FIXME: The test for external storage here seems wrong? We still
3935   // need to check for mismatches.
3936   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3937       // Don't complain about out-of-line definitions of static members.
3938       !(Old->getLexicalDeclContext()->isRecord() &&
3939         !New->getLexicalDeclContext()->isRecord())) {
3940     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3941     Diag(OldLocation, PrevDiag);
3942     return New->setInvalidDecl();
3943   }
3944 
3945   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3946     if (VarDecl *Def = Old->getDefinition()) {
3947       // C++1z [dcl.fcn.spec]p4:
3948       //   If the definition of a variable appears in a translation unit before
3949       //   its first declaration as inline, the program is ill-formed.
3950       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3951       Diag(Def->getLocation(), diag::note_previous_definition);
3952     }
3953   }
3954 
3955   // If this redeclaration makes the variable inline, we may need to add it to
3956   // UndefinedButUsed.
3957   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3958       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3959     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3960                                            SourceLocation()));
3961 
3962   if (New->getTLSKind() != Old->getTLSKind()) {
3963     if (!Old->getTLSKind()) {
3964       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3965       Diag(OldLocation, PrevDiag);
3966     } else if (!New->getTLSKind()) {
3967       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3968       Diag(OldLocation, PrevDiag);
3969     } else {
3970       // Do not allow redeclaration to change the variable between requiring
3971       // static and dynamic initialization.
3972       // FIXME: GCC allows this, but uses the TLS keyword on the first
3973       // declaration to determine the kind. Do we need to be compatible here?
3974       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3975         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3976       Diag(OldLocation, PrevDiag);
3977     }
3978   }
3979 
3980   // C++ doesn't have tentative definitions, so go right ahead and check here.
3981   if (getLangOpts().CPlusPlus &&
3982       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3983     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3984         Old->getCanonicalDecl()->isConstexpr()) {
3985       // This definition won't be a definition any more once it's been merged.
3986       Diag(New->getLocation(),
3987            diag::warn_deprecated_redundant_constexpr_static_def);
3988     } else if (VarDecl *Def = Old->getDefinition()) {
3989       if (checkVarDeclRedefinition(Def, New))
3990         return;
3991     }
3992   }
3993 
3994   if (haveIncompatibleLanguageLinkages(Old, New)) {
3995     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3996     Diag(OldLocation, PrevDiag);
3997     New->setInvalidDecl();
3998     return;
3999   }
4000 
4001   // Merge "used" flag.
4002   if (Old->getMostRecentDecl()->isUsed(false))
4003     New->setIsUsed();
4004 
4005   // Keep a chain of previous declarations.
4006   New->setPreviousDecl(Old);
4007   if (NewTemplate)
4008     NewTemplate->setPreviousDecl(OldTemplate);
4009   adjustDeclContextForDeclaratorDecl(New, Old);
4010 
4011   // Inherit access appropriately.
4012   New->setAccess(Old->getAccess());
4013   if (NewTemplate)
4014     NewTemplate->setAccess(New->getAccess());
4015 
4016   if (Old->isInline())
4017     New->setImplicitlyInline();
4018 }
4019 
4020 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4021   SourceManager &SrcMgr = getSourceManager();
4022   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4023   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4024   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4025   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4026   auto &HSI = PP.getHeaderSearchInfo();
4027   StringRef HdrFilename =
4028       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4029 
4030   auto noteFromModuleOrInclude = [&](Module *Mod,
4031                                      SourceLocation IncLoc) -> bool {
4032     // Redefinition errors with modules are common with non modular mapped
4033     // headers, example: a non-modular header H in module A that also gets
4034     // included directly in a TU. Pointing twice to the same header/definition
4035     // is confusing, try to get better diagnostics when modules is on.
4036     if (IncLoc.isValid()) {
4037       if (Mod) {
4038         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4039             << HdrFilename.str() << Mod->getFullModuleName();
4040         if (!Mod->DefinitionLoc.isInvalid())
4041           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4042               << Mod->getFullModuleName();
4043       } else {
4044         Diag(IncLoc, diag::note_redefinition_include_same_file)
4045             << HdrFilename.str();
4046       }
4047       return true;
4048     }
4049 
4050     return false;
4051   };
4052 
4053   // Is it the same file and same offset? Provide more information on why
4054   // this leads to a redefinition error.
4055   bool EmittedDiag = false;
4056   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4057     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4058     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4059     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4060     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4061 
4062     // If the header has no guards, emit a note suggesting one.
4063     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4064       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4065 
4066     if (EmittedDiag)
4067       return;
4068   }
4069 
4070   // Redefinition coming from different files or couldn't do better above.
4071   if (Old->getLocation().isValid())
4072     Diag(Old->getLocation(), diag::note_previous_definition);
4073 }
4074 
4075 /// We've just determined that \p Old and \p New both appear to be definitions
4076 /// of the same variable. Either diagnose or fix the problem.
4077 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4078   if (!hasVisibleDefinition(Old) &&
4079       (New->getFormalLinkage() == InternalLinkage ||
4080        New->isInline() ||
4081        New->getDescribedVarTemplate() ||
4082        New->getNumTemplateParameterLists() ||
4083        New->getDeclContext()->isDependentContext())) {
4084     // The previous definition is hidden, and multiple definitions are
4085     // permitted (in separate TUs). Demote this to a declaration.
4086     New->demoteThisDefinitionToDeclaration();
4087 
4088     // Make the canonical definition visible.
4089     if (auto *OldTD = Old->getDescribedVarTemplate())
4090       makeMergedDefinitionVisible(OldTD);
4091     makeMergedDefinitionVisible(Old);
4092     return false;
4093   } else {
4094     Diag(New->getLocation(), diag::err_redefinition) << New;
4095     notePreviousDefinition(Old, New->getLocation());
4096     New->setInvalidDecl();
4097     return true;
4098   }
4099 }
4100 
4101 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4102 /// no declarator (e.g. "struct foo;") is parsed.
4103 Decl *
4104 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4105                                  RecordDecl *&AnonRecord) {
4106   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4107                                     AnonRecord);
4108 }
4109 
4110 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4111 // disambiguate entities defined in different scopes.
4112 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4113 // compatibility.
4114 // We will pick our mangling number depending on which version of MSVC is being
4115 // targeted.
4116 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4117   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4118              ? S->getMSCurManglingNumber()
4119              : S->getMSLastManglingNumber();
4120 }
4121 
4122 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4123   if (!Context.getLangOpts().CPlusPlus)
4124     return;
4125 
4126   if (isa<CXXRecordDecl>(Tag->getParent())) {
4127     // If this tag is the direct child of a class, number it if
4128     // it is anonymous.
4129     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4130       return;
4131     MangleNumberingContext &MCtx =
4132         Context.getManglingNumberContext(Tag->getParent());
4133     Context.setManglingNumber(
4134         Tag, MCtx.getManglingNumber(
4135                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4136     return;
4137   }
4138 
4139   // If this tag isn't a direct child of a class, number it if it is local.
4140   Decl *ManglingContextDecl;
4141   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4142           Tag->getDeclContext(), ManglingContextDecl)) {
4143     Context.setManglingNumber(
4144         Tag, MCtx->getManglingNumber(
4145                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4146   }
4147 }
4148 
4149 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4150                                         TypedefNameDecl *NewTD) {
4151   if (TagFromDeclSpec->isInvalidDecl())
4152     return;
4153 
4154   // Do nothing if the tag already has a name for linkage purposes.
4155   if (TagFromDeclSpec->hasNameForLinkage())
4156     return;
4157 
4158   // A well-formed anonymous tag must always be a TUK_Definition.
4159   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4160 
4161   // The type must match the tag exactly;  no qualifiers allowed.
4162   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4163                            Context.getTagDeclType(TagFromDeclSpec))) {
4164     if (getLangOpts().CPlusPlus)
4165       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4166     return;
4167   }
4168 
4169   // If we've already computed linkage for the anonymous tag, then
4170   // adding a typedef name for the anonymous decl can change that
4171   // linkage, which might be a serious problem.  Diagnose this as
4172   // unsupported and ignore the typedef name.  TODO: we should
4173   // pursue this as a language defect and establish a formal rule
4174   // for how to handle it.
4175   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4176     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4177 
4178     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4179     tagLoc = getLocForEndOfToken(tagLoc);
4180 
4181     llvm::SmallString<40> textToInsert;
4182     textToInsert += ' ';
4183     textToInsert += NewTD->getIdentifier()->getName();
4184     Diag(tagLoc, diag::note_typedef_changes_linkage)
4185         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4186     return;
4187   }
4188 
4189   // Otherwise, set this is the anon-decl typedef for the tag.
4190   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4191 }
4192 
4193 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4194   switch (T) {
4195   case DeclSpec::TST_class:
4196     return 0;
4197   case DeclSpec::TST_struct:
4198     return 1;
4199   case DeclSpec::TST_interface:
4200     return 2;
4201   case DeclSpec::TST_union:
4202     return 3;
4203   case DeclSpec::TST_enum:
4204     return 4;
4205   default:
4206     llvm_unreachable("unexpected type specifier");
4207   }
4208 }
4209 
4210 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4211 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4212 /// parameters to cope with template friend declarations.
4213 Decl *
4214 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4215                                  MultiTemplateParamsArg TemplateParams,
4216                                  bool IsExplicitInstantiation,
4217                                  RecordDecl *&AnonRecord) {
4218   Decl *TagD = nullptr;
4219   TagDecl *Tag = nullptr;
4220   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4221       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4222       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4223       DS.getTypeSpecType() == DeclSpec::TST_union ||
4224       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4225     TagD = DS.getRepAsDecl();
4226 
4227     if (!TagD) // We probably had an error
4228       return nullptr;
4229 
4230     // Note that the above type specs guarantee that the
4231     // type rep is a Decl, whereas in many of the others
4232     // it's a Type.
4233     if (isa<TagDecl>(TagD))
4234       Tag = cast<TagDecl>(TagD);
4235     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4236       Tag = CTD->getTemplatedDecl();
4237   }
4238 
4239   if (Tag) {
4240     handleTagNumbering(Tag, S);
4241     Tag->setFreeStanding();
4242     if (Tag->isInvalidDecl())
4243       return Tag;
4244   }
4245 
4246   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4247     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4248     // or incomplete types shall not be restrict-qualified."
4249     if (TypeQuals & DeclSpec::TQ_restrict)
4250       Diag(DS.getRestrictSpecLoc(),
4251            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4252            << DS.getSourceRange();
4253   }
4254 
4255   if (DS.isInlineSpecified())
4256     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4257         << getLangOpts().CPlusPlus17;
4258 
4259   if (DS.isConstexprSpecified()) {
4260     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4261     // and definitions of functions and variables.
4262     if (Tag)
4263       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4264           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4265     else
4266       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4267     // Don't emit warnings after this error.
4268     return TagD;
4269   }
4270 
4271   DiagnoseFunctionSpecifiers(DS);
4272 
4273   if (DS.isFriendSpecified()) {
4274     // If we're dealing with a decl but not a TagDecl, assume that
4275     // whatever routines created it handled the friendship aspect.
4276     if (TagD && !Tag)
4277       return nullptr;
4278     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4279   }
4280 
4281   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4282   bool IsExplicitSpecialization =
4283     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4284   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4285       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4286       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4287     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4288     // nested-name-specifier unless it is an explicit instantiation
4289     // or an explicit specialization.
4290     //
4291     // FIXME: We allow class template partial specializations here too, per the
4292     // obvious intent of DR1819.
4293     //
4294     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4295     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4296         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4297     return nullptr;
4298   }
4299 
4300   // Track whether this decl-specifier declares anything.
4301   bool DeclaresAnything = true;
4302 
4303   // Handle anonymous struct definitions.
4304   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4305     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4306         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4307       if (getLangOpts().CPlusPlus ||
4308           Record->getDeclContext()->isRecord()) {
4309         // If CurContext is a DeclContext that can contain statements,
4310         // RecursiveASTVisitor won't visit the decls that
4311         // BuildAnonymousStructOrUnion() will put into CurContext.
4312         // Also store them here so that they can be part of the
4313         // DeclStmt that gets created in this case.
4314         // FIXME: Also return the IndirectFieldDecls created by
4315         // BuildAnonymousStructOr union, for the same reason?
4316         if (CurContext->isFunctionOrMethod())
4317           AnonRecord = Record;
4318         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4319                                            Context.getPrintingPolicy());
4320       }
4321 
4322       DeclaresAnything = false;
4323     }
4324   }
4325 
4326   // C11 6.7.2.1p2:
4327   //   A struct-declaration that does not declare an anonymous structure or
4328   //   anonymous union shall contain a struct-declarator-list.
4329   //
4330   // This rule also existed in C89 and C99; the grammar for struct-declaration
4331   // did not permit a struct-declaration without a struct-declarator-list.
4332   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4333       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4334     // Check for Microsoft C extension: anonymous struct/union member.
4335     // Handle 2 kinds of anonymous struct/union:
4336     //   struct STRUCT;
4337     //   union UNION;
4338     // and
4339     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4340     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4341     if ((Tag && Tag->getDeclName()) ||
4342         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4343       RecordDecl *Record = nullptr;
4344       if (Tag)
4345         Record = dyn_cast<RecordDecl>(Tag);
4346       else if (const RecordType *RT =
4347                    DS.getRepAsType().get()->getAsStructureType())
4348         Record = RT->getDecl();
4349       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4350         Record = UT->getDecl();
4351 
4352       if (Record && getLangOpts().MicrosoftExt) {
4353         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4354             << Record->isUnion() << DS.getSourceRange();
4355         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4356       }
4357 
4358       DeclaresAnything = false;
4359     }
4360   }
4361 
4362   // Skip all the checks below if we have a type error.
4363   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4364       (TagD && TagD->isInvalidDecl()))
4365     return TagD;
4366 
4367   if (getLangOpts().CPlusPlus &&
4368       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4369     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4370       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4371           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4372         DeclaresAnything = false;
4373 
4374   if (!DS.isMissingDeclaratorOk()) {
4375     // Customize diagnostic for a typedef missing a name.
4376     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4377       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4378           << DS.getSourceRange();
4379     else
4380       DeclaresAnything = false;
4381   }
4382 
4383   if (DS.isModulePrivateSpecified() &&
4384       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4385     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4386       << Tag->getTagKind()
4387       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4388 
4389   ActOnDocumentableDecl(TagD);
4390 
4391   // C 6.7/2:
4392   //   A declaration [...] shall declare at least a declarator [...], a tag,
4393   //   or the members of an enumeration.
4394   // C++ [dcl.dcl]p3:
4395   //   [If there are no declarators], and except for the declaration of an
4396   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4397   //   names into the program, or shall redeclare a name introduced by a
4398   //   previous declaration.
4399   if (!DeclaresAnything) {
4400     // In C, we allow this as a (popular) extension / bug. Don't bother
4401     // producing further diagnostics for redundant qualifiers after this.
4402     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4403     return TagD;
4404   }
4405 
4406   // C++ [dcl.stc]p1:
4407   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4408   //   init-declarator-list of the declaration shall not be empty.
4409   // C++ [dcl.fct.spec]p1:
4410   //   If a cv-qualifier appears in a decl-specifier-seq, the
4411   //   init-declarator-list of the declaration shall not be empty.
4412   //
4413   // Spurious qualifiers here appear to be valid in C.
4414   unsigned DiagID = diag::warn_standalone_specifier;
4415   if (getLangOpts().CPlusPlus)
4416     DiagID = diag::ext_standalone_specifier;
4417 
4418   // Note that a linkage-specification sets a storage class, but
4419   // 'extern "C" struct foo;' is actually valid and not theoretically
4420   // useless.
4421   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4422     if (SCS == DeclSpec::SCS_mutable)
4423       // Since mutable is not a viable storage class specifier in C, there is
4424       // no reason to treat it as an extension. Instead, diagnose as an error.
4425       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4426     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4427       Diag(DS.getStorageClassSpecLoc(), DiagID)
4428         << DeclSpec::getSpecifierName(SCS);
4429   }
4430 
4431   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4432     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4433       << DeclSpec::getSpecifierName(TSCS);
4434   if (DS.getTypeQualifiers()) {
4435     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4436       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4437     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4438       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4439     // Restrict is covered above.
4440     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4441       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4442     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4443       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4444   }
4445 
4446   // Warn about ignored type attributes, for example:
4447   // __attribute__((aligned)) struct A;
4448   // Attributes should be placed after tag to apply to type declaration.
4449   if (!DS.getAttributes().empty()) {
4450     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4451     if (TypeSpecType == DeclSpec::TST_class ||
4452         TypeSpecType == DeclSpec::TST_struct ||
4453         TypeSpecType == DeclSpec::TST_interface ||
4454         TypeSpecType == DeclSpec::TST_union ||
4455         TypeSpecType == DeclSpec::TST_enum) {
4456       for (const ParsedAttr &AL : DS.getAttributes())
4457         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4458             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4459     }
4460   }
4461 
4462   return TagD;
4463 }
4464 
4465 /// We are trying to inject an anonymous member into the given scope;
4466 /// check if there's an existing declaration that can't be overloaded.
4467 ///
4468 /// \return true if this is a forbidden redeclaration
4469 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4470                                          Scope *S,
4471                                          DeclContext *Owner,
4472                                          DeclarationName Name,
4473                                          SourceLocation NameLoc,
4474                                          bool IsUnion) {
4475   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4476                  Sema::ForVisibleRedeclaration);
4477   if (!SemaRef.LookupName(R, S)) return false;
4478 
4479   // Pick a representative declaration.
4480   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4481   assert(PrevDecl && "Expected a non-null Decl");
4482 
4483   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4484     return false;
4485 
4486   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4487     << IsUnion << Name;
4488   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4489 
4490   return true;
4491 }
4492 
4493 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4494 /// anonymous struct or union AnonRecord into the owning context Owner
4495 /// and scope S. This routine will be invoked just after we realize
4496 /// that an unnamed union or struct is actually an anonymous union or
4497 /// struct, e.g.,
4498 ///
4499 /// @code
4500 /// union {
4501 ///   int i;
4502 ///   float f;
4503 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4504 ///    // f into the surrounding scope.x
4505 /// @endcode
4506 ///
4507 /// This routine is recursive, injecting the names of nested anonymous
4508 /// structs/unions into the owning context and scope as well.
4509 static bool
4510 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4511                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4512                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4513   bool Invalid = false;
4514 
4515   // Look every FieldDecl and IndirectFieldDecl with a name.
4516   for (auto *D : AnonRecord->decls()) {
4517     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4518         cast<NamedDecl>(D)->getDeclName()) {
4519       ValueDecl *VD = cast<ValueDecl>(D);
4520       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4521                                        VD->getLocation(),
4522                                        AnonRecord->isUnion())) {
4523         // C++ [class.union]p2:
4524         //   The names of the members of an anonymous union shall be
4525         //   distinct from the names of any other entity in the
4526         //   scope in which the anonymous union is declared.
4527         Invalid = true;
4528       } else {
4529         // C++ [class.union]p2:
4530         //   For the purpose of name lookup, after the anonymous union
4531         //   definition, the members of the anonymous union are
4532         //   considered to have been defined in the scope in which the
4533         //   anonymous union is declared.
4534         unsigned OldChainingSize = Chaining.size();
4535         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4536           Chaining.append(IF->chain_begin(), IF->chain_end());
4537         else
4538           Chaining.push_back(VD);
4539 
4540         assert(Chaining.size() >= 2);
4541         NamedDecl **NamedChain =
4542           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4543         for (unsigned i = 0; i < Chaining.size(); i++)
4544           NamedChain[i] = Chaining[i];
4545 
4546         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4547             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4548             VD->getType(), {NamedChain, Chaining.size()});
4549 
4550         for (const auto *Attr : VD->attrs())
4551           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4552 
4553         IndirectField->setAccess(AS);
4554         IndirectField->setImplicit();
4555         SemaRef.PushOnScopeChains(IndirectField, S);
4556 
4557         // That includes picking up the appropriate access specifier.
4558         if (AS != AS_none) IndirectField->setAccess(AS);
4559 
4560         Chaining.resize(OldChainingSize);
4561       }
4562     }
4563   }
4564 
4565   return Invalid;
4566 }
4567 
4568 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4569 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4570 /// illegal input values are mapped to SC_None.
4571 static StorageClass
4572 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4573   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4574   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4575          "Parser allowed 'typedef' as storage class VarDecl.");
4576   switch (StorageClassSpec) {
4577   case DeclSpec::SCS_unspecified:    return SC_None;
4578   case DeclSpec::SCS_extern:
4579     if (DS.isExternInLinkageSpec())
4580       return SC_None;
4581     return SC_Extern;
4582   case DeclSpec::SCS_static:         return SC_Static;
4583   case DeclSpec::SCS_auto:           return SC_Auto;
4584   case DeclSpec::SCS_register:       return SC_Register;
4585   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4586     // Illegal SCSs map to None: error reporting is up to the caller.
4587   case DeclSpec::SCS_mutable:        // Fall through.
4588   case DeclSpec::SCS_typedef:        return SC_None;
4589   }
4590   llvm_unreachable("unknown storage class specifier");
4591 }
4592 
4593 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4594   assert(Record->hasInClassInitializer());
4595 
4596   for (const auto *I : Record->decls()) {
4597     const auto *FD = dyn_cast<FieldDecl>(I);
4598     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4599       FD = IFD->getAnonField();
4600     if (FD && FD->hasInClassInitializer())
4601       return FD->getLocation();
4602   }
4603 
4604   llvm_unreachable("couldn't find in-class initializer");
4605 }
4606 
4607 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4608                                       SourceLocation DefaultInitLoc) {
4609   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4610     return;
4611 
4612   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4613   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4614 }
4615 
4616 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4617                                       CXXRecordDecl *AnonUnion) {
4618   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4619     return;
4620 
4621   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4622 }
4623 
4624 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4625 /// anonymous structure or union. Anonymous unions are a C++ feature
4626 /// (C++ [class.union]) and a C11 feature; anonymous structures
4627 /// are a C11 feature and GNU C++ extension.
4628 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4629                                         AccessSpecifier AS,
4630                                         RecordDecl *Record,
4631                                         const PrintingPolicy &Policy) {
4632   DeclContext *Owner = Record->getDeclContext();
4633 
4634   // Diagnose whether this anonymous struct/union is an extension.
4635   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4636     Diag(Record->getLocation(), diag::ext_anonymous_union);
4637   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4638     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4639   else if (!Record->isUnion() && !getLangOpts().C11)
4640     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4641 
4642   // C and C++ require different kinds of checks for anonymous
4643   // structs/unions.
4644   bool Invalid = false;
4645   if (getLangOpts().CPlusPlus) {
4646     const char *PrevSpec = nullptr;
4647     unsigned DiagID;
4648     if (Record->isUnion()) {
4649       // C++ [class.union]p6:
4650       // C++17 [class.union.anon]p2:
4651       //   Anonymous unions declared in a named namespace or in the
4652       //   global namespace shall be declared static.
4653       DeclContext *OwnerScope = Owner->getRedeclContext();
4654       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4655           (OwnerScope->isTranslationUnit() ||
4656            (OwnerScope->isNamespace() &&
4657             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4658         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4659           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4660 
4661         // Recover by adding 'static'.
4662         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4663                                PrevSpec, DiagID, Policy);
4664       }
4665       // C++ [class.union]p6:
4666       //   A storage class is not allowed in a declaration of an
4667       //   anonymous union in a class scope.
4668       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4669                isa<RecordDecl>(Owner)) {
4670         Diag(DS.getStorageClassSpecLoc(),
4671              diag::err_anonymous_union_with_storage_spec)
4672           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4673 
4674         // Recover by removing the storage specifier.
4675         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4676                                SourceLocation(),
4677                                PrevSpec, DiagID, Context.getPrintingPolicy());
4678       }
4679     }
4680 
4681     // Ignore const/volatile/restrict qualifiers.
4682     if (DS.getTypeQualifiers()) {
4683       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4684         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4685           << Record->isUnion() << "const"
4686           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4687       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4688         Diag(DS.getVolatileSpecLoc(),
4689              diag::ext_anonymous_struct_union_qualified)
4690           << Record->isUnion() << "volatile"
4691           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4692       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4693         Diag(DS.getRestrictSpecLoc(),
4694              diag::ext_anonymous_struct_union_qualified)
4695           << Record->isUnion() << "restrict"
4696           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4697       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4698         Diag(DS.getAtomicSpecLoc(),
4699              diag::ext_anonymous_struct_union_qualified)
4700           << Record->isUnion() << "_Atomic"
4701           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4702       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4703         Diag(DS.getUnalignedSpecLoc(),
4704              diag::ext_anonymous_struct_union_qualified)
4705           << Record->isUnion() << "__unaligned"
4706           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4707 
4708       DS.ClearTypeQualifiers();
4709     }
4710 
4711     // C++ [class.union]p2:
4712     //   The member-specification of an anonymous union shall only
4713     //   define non-static data members. [Note: nested types and
4714     //   functions cannot be declared within an anonymous union. ]
4715     for (auto *Mem : Record->decls()) {
4716       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4717         // C++ [class.union]p3:
4718         //   An anonymous union shall not have private or protected
4719         //   members (clause 11).
4720         assert(FD->getAccess() != AS_none);
4721         if (FD->getAccess() != AS_public) {
4722           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4723             << Record->isUnion() << (FD->getAccess() == AS_protected);
4724           Invalid = true;
4725         }
4726 
4727         // C++ [class.union]p1
4728         //   An object of a class with a non-trivial constructor, a non-trivial
4729         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4730         //   assignment operator cannot be a member of a union, nor can an
4731         //   array of such objects.
4732         if (CheckNontrivialField(FD))
4733           Invalid = true;
4734       } else if (Mem->isImplicit()) {
4735         // Any implicit members are fine.
4736       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4737         // This is a type that showed up in an
4738         // elaborated-type-specifier inside the anonymous struct or
4739         // union, but which actually declares a type outside of the
4740         // anonymous struct or union. It's okay.
4741       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4742         if (!MemRecord->isAnonymousStructOrUnion() &&
4743             MemRecord->getDeclName()) {
4744           // Visual C++ allows type definition in anonymous struct or union.
4745           if (getLangOpts().MicrosoftExt)
4746             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4747               << Record->isUnion();
4748           else {
4749             // This is a nested type declaration.
4750             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4751               << Record->isUnion();
4752             Invalid = true;
4753           }
4754         } else {
4755           // This is an anonymous type definition within another anonymous type.
4756           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4757           // not part of standard C++.
4758           Diag(MemRecord->getLocation(),
4759                diag::ext_anonymous_record_with_anonymous_type)
4760             << Record->isUnion();
4761         }
4762       } else if (isa<AccessSpecDecl>(Mem)) {
4763         // Any access specifier is fine.
4764       } else if (isa<StaticAssertDecl>(Mem)) {
4765         // In C++1z, static_assert declarations are also fine.
4766       } else {
4767         // We have something that isn't a non-static data
4768         // member. Complain about it.
4769         unsigned DK = diag::err_anonymous_record_bad_member;
4770         if (isa<TypeDecl>(Mem))
4771           DK = diag::err_anonymous_record_with_type;
4772         else if (isa<FunctionDecl>(Mem))
4773           DK = diag::err_anonymous_record_with_function;
4774         else if (isa<VarDecl>(Mem))
4775           DK = diag::err_anonymous_record_with_static;
4776 
4777         // Visual C++ allows type definition in anonymous struct or union.
4778         if (getLangOpts().MicrosoftExt &&
4779             DK == diag::err_anonymous_record_with_type)
4780           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4781             << Record->isUnion();
4782         else {
4783           Diag(Mem->getLocation(), DK) << Record->isUnion();
4784           Invalid = true;
4785         }
4786       }
4787     }
4788 
4789     // C++11 [class.union]p8 (DR1460):
4790     //   At most one variant member of a union may have a
4791     //   brace-or-equal-initializer.
4792     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4793         Owner->isRecord())
4794       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4795                                 cast<CXXRecordDecl>(Record));
4796   }
4797 
4798   if (!Record->isUnion() && !Owner->isRecord()) {
4799     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4800       << getLangOpts().CPlusPlus;
4801     Invalid = true;
4802   }
4803 
4804   // Mock up a declarator.
4805   Declarator Dc(DS, DeclaratorContext::MemberContext);
4806   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4807   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4808 
4809   // Create a declaration for this anonymous struct/union.
4810   NamedDecl *Anon = nullptr;
4811   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4812     Anon = FieldDecl::Create(
4813         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4814         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4815         /*BitWidth=*/nullptr, /*Mutable=*/false,
4816         /*InitStyle=*/ICIS_NoInit);
4817     Anon->setAccess(AS);
4818     if (getLangOpts().CPlusPlus)
4819       FieldCollector->Add(cast<FieldDecl>(Anon));
4820   } else {
4821     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4822     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4823     if (SCSpec == DeclSpec::SCS_mutable) {
4824       // mutable can only appear on non-static class members, so it's always
4825       // an error here
4826       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4827       Invalid = true;
4828       SC = SC_None;
4829     }
4830 
4831     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4832                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4833                            Context.getTypeDeclType(Record), TInfo, SC);
4834 
4835     // Default-initialize the implicit variable. This initialization will be
4836     // trivial in almost all cases, except if a union member has an in-class
4837     // initializer:
4838     //   union { int n = 0; };
4839     ActOnUninitializedDecl(Anon);
4840   }
4841   Anon->setImplicit();
4842 
4843   // Mark this as an anonymous struct/union type.
4844   Record->setAnonymousStructOrUnion(true);
4845 
4846   // Add the anonymous struct/union object to the current
4847   // context. We'll be referencing this object when we refer to one of
4848   // its members.
4849   Owner->addDecl(Anon);
4850 
4851   // Inject the members of the anonymous struct/union into the owning
4852   // context and into the identifier resolver chain for name lookup
4853   // purposes.
4854   SmallVector<NamedDecl*, 2> Chain;
4855   Chain.push_back(Anon);
4856 
4857   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4858     Invalid = true;
4859 
4860   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4861     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4862       Decl *ManglingContextDecl;
4863       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4864               NewVD->getDeclContext(), ManglingContextDecl)) {
4865         Context.setManglingNumber(
4866             NewVD, MCtx->getManglingNumber(
4867                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4868         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4869       }
4870     }
4871   }
4872 
4873   if (Invalid)
4874     Anon->setInvalidDecl();
4875 
4876   return Anon;
4877 }
4878 
4879 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4880 /// Microsoft C anonymous structure.
4881 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4882 /// Example:
4883 ///
4884 /// struct A { int a; };
4885 /// struct B { struct A; int b; };
4886 ///
4887 /// void foo() {
4888 ///   B var;
4889 ///   var.a = 3;
4890 /// }
4891 ///
4892 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4893                                            RecordDecl *Record) {
4894   assert(Record && "expected a record!");
4895 
4896   // Mock up a declarator.
4897   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4898   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4899   assert(TInfo && "couldn't build declarator info for anonymous struct");
4900 
4901   auto *ParentDecl = cast<RecordDecl>(CurContext);
4902   QualType RecTy = Context.getTypeDeclType(Record);
4903 
4904   // Create a declaration for this anonymous struct.
4905   NamedDecl *Anon =
4906       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4907                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4908                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4909                         /*InitStyle=*/ICIS_NoInit);
4910   Anon->setImplicit();
4911 
4912   // Add the anonymous struct object to the current context.
4913   CurContext->addDecl(Anon);
4914 
4915   // Inject the members of the anonymous struct into the current
4916   // context and into the identifier resolver chain for name lookup
4917   // purposes.
4918   SmallVector<NamedDecl*, 2> Chain;
4919   Chain.push_back(Anon);
4920 
4921   RecordDecl *RecordDef = Record->getDefinition();
4922   if (RequireCompleteType(Anon->getLocation(), RecTy,
4923                           diag::err_field_incomplete) ||
4924       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4925                                           AS_none, Chain)) {
4926     Anon->setInvalidDecl();
4927     ParentDecl->setInvalidDecl();
4928   }
4929 
4930   return Anon;
4931 }
4932 
4933 /// GetNameForDeclarator - Determine the full declaration name for the
4934 /// given Declarator.
4935 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4936   return GetNameFromUnqualifiedId(D.getName());
4937 }
4938 
4939 /// Retrieves the declaration name from a parsed unqualified-id.
4940 DeclarationNameInfo
4941 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4942   DeclarationNameInfo NameInfo;
4943   NameInfo.setLoc(Name.StartLocation);
4944 
4945   switch (Name.getKind()) {
4946 
4947   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4948   case UnqualifiedIdKind::IK_Identifier:
4949     NameInfo.setName(Name.Identifier);
4950     return NameInfo;
4951 
4952   case UnqualifiedIdKind::IK_DeductionGuideName: {
4953     // C++ [temp.deduct.guide]p3:
4954     //   The simple-template-id shall name a class template specialization.
4955     //   The template-name shall be the same identifier as the template-name
4956     //   of the simple-template-id.
4957     // These together intend to imply that the template-name shall name a
4958     // class template.
4959     // FIXME: template<typename T> struct X {};
4960     //        template<typename T> using Y = X<T>;
4961     //        Y(int) -> Y<int>;
4962     //   satisfies these rules but does not name a class template.
4963     TemplateName TN = Name.TemplateName.get().get();
4964     auto *Template = TN.getAsTemplateDecl();
4965     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4966       Diag(Name.StartLocation,
4967            diag::err_deduction_guide_name_not_class_template)
4968         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4969       if (Template)
4970         Diag(Template->getLocation(), diag::note_template_decl_here);
4971       return DeclarationNameInfo();
4972     }
4973 
4974     NameInfo.setName(
4975         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4976     return NameInfo;
4977   }
4978 
4979   case UnqualifiedIdKind::IK_OperatorFunctionId:
4980     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4981                                            Name.OperatorFunctionId.Operator));
4982     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4983       = Name.OperatorFunctionId.SymbolLocations[0];
4984     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4985       = Name.EndLocation.getRawEncoding();
4986     return NameInfo;
4987 
4988   case UnqualifiedIdKind::IK_LiteralOperatorId:
4989     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4990                                                            Name.Identifier));
4991     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4992     return NameInfo;
4993 
4994   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4995     TypeSourceInfo *TInfo;
4996     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4997     if (Ty.isNull())
4998       return DeclarationNameInfo();
4999     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5000                                                Context.getCanonicalType(Ty)));
5001     NameInfo.setNamedTypeInfo(TInfo);
5002     return NameInfo;
5003   }
5004 
5005   case UnqualifiedIdKind::IK_ConstructorName: {
5006     TypeSourceInfo *TInfo;
5007     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5008     if (Ty.isNull())
5009       return DeclarationNameInfo();
5010     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5011                                               Context.getCanonicalType(Ty)));
5012     NameInfo.setNamedTypeInfo(TInfo);
5013     return NameInfo;
5014   }
5015 
5016   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5017     // In well-formed code, we can only have a constructor
5018     // template-id that refers to the current context, so go there
5019     // to find the actual type being constructed.
5020     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5021     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5022       return DeclarationNameInfo();
5023 
5024     // Determine the type of the class being constructed.
5025     QualType CurClassType = Context.getTypeDeclType(CurClass);
5026 
5027     // FIXME: Check two things: that the template-id names the same type as
5028     // CurClassType, and that the template-id does not occur when the name
5029     // was qualified.
5030 
5031     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5032                                     Context.getCanonicalType(CurClassType)));
5033     // FIXME: should we retrieve TypeSourceInfo?
5034     NameInfo.setNamedTypeInfo(nullptr);
5035     return NameInfo;
5036   }
5037 
5038   case UnqualifiedIdKind::IK_DestructorName: {
5039     TypeSourceInfo *TInfo;
5040     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5041     if (Ty.isNull())
5042       return DeclarationNameInfo();
5043     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5044                                               Context.getCanonicalType(Ty)));
5045     NameInfo.setNamedTypeInfo(TInfo);
5046     return NameInfo;
5047   }
5048 
5049   case UnqualifiedIdKind::IK_TemplateId: {
5050     TemplateName TName = Name.TemplateId->Template.get();
5051     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5052     return Context.getNameForTemplate(TName, TNameLoc);
5053   }
5054 
5055   } // switch (Name.getKind())
5056 
5057   llvm_unreachable("Unknown name kind");
5058 }
5059 
5060 static QualType getCoreType(QualType Ty) {
5061   do {
5062     if (Ty->isPointerType() || Ty->isReferenceType())
5063       Ty = Ty->getPointeeType();
5064     else if (Ty->isArrayType())
5065       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5066     else
5067       return Ty.withoutLocalFastQualifiers();
5068   } while (true);
5069 }
5070 
5071 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5072 /// and Definition have "nearly" matching parameters. This heuristic is
5073 /// used to improve diagnostics in the case where an out-of-line function
5074 /// definition doesn't match any declaration within the class or namespace.
5075 /// Also sets Params to the list of indices to the parameters that differ
5076 /// between the declaration and the definition. If hasSimilarParameters
5077 /// returns true and Params is empty, then all of the parameters match.
5078 static bool hasSimilarParameters(ASTContext &Context,
5079                                      FunctionDecl *Declaration,
5080                                      FunctionDecl *Definition,
5081                                      SmallVectorImpl<unsigned> &Params) {
5082   Params.clear();
5083   if (Declaration->param_size() != Definition->param_size())
5084     return false;
5085   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5086     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5087     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5088 
5089     // The parameter types are identical
5090     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5091       continue;
5092 
5093     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5094     QualType DefParamBaseTy = getCoreType(DefParamTy);
5095     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5096     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5097 
5098     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5099         (DeclTyName && DeclTyName == DefTyName))
5100       Params.push_back(Idx);
5101     else  // The two parameters aren't even close
5102       return false;
5103   }
5104 
5105   return true;
5106 }
5107 
5108 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5109 /// declarator needs to be rebuilt in the current instantiation.
5110 /// Any bits of declarator which appear before the name are valid for
5111 /// consideration here.  That's specifically the type in the decl spec
5112 /// and the base type in any member-pointer chunks.
5113 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5114                                                     DeclarationName Name) {
5115   // The types we specifically need to rebuild are:
5116   //   - typenames, typeofs, and decltypes
5117   //   - types which will become injected class names
5118   // Of course, we also need to rebuild any type referencing such a
5119   // type.  It's safest to just say "dependent", but we call out a
5120   // few cases here.
5121 
5122   DeclSpec &DS = D.getMutableDeclSpec();
5123   switch (DS.getTypeSpecType()) {
5124   case DeclSpec::TST_typename:
5125   case DeclSpec::TST_typeofType:
5126   case DeclSpec::TST_underlyingType:
5127   case DeclSpec::TST_atomic: {
5128     // Grab the type from the parser.
5129     TypeSourceInfo *TSI = nullptr;
5130     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5131     if (T.isNull() || !T->isDependentType()) break;
5132 
5133     // Make sure there's a type source info.  This isn't really much
5134     // of a waste; most dependent types should have type source info
5135     // attached already.
5136     if (!TSI)
5137       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5138 
5139     // Rebuild the type in the current instantiation.
5140     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5141     if (!TSI) return true;
5142 
5143     // Store the new type back in the decl spec.
5144     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5145     DS.UpdateTypeRep(LocType);
5146     break;
5147   }
5148 
5149   case DeclSpec::TST_decltype:
5150   case DeclSpec::TST_typeofExpr: {
5151     Expr *E = DS.getRepAsExpr();
5152     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5153     if (Result.isInvalid()) return true;
5154     DS.UpdateExprRep(Result.get());
5155     break;
5156   }
5157 
5158   default:
5159     // Nothing to do for these decl specs.
5160     break;
5161   }
5162 
5163   // It doesn't matter what order we do this in.
5164   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5165     DeclaratorChunk &Chunk = D.getTypeObject(I);
5166 
5167     // The only type information in the declarator which can come
5168     // before the declaration name is the base type of a member
5169     // pointer.
5170     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5171       continue;
5172 
5173     // Rebuild the scope specifier in-place.
5174     CXXScopeSpec &SS = Chunk.Mem.Scope();
5175     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5176       return true;
5177   }
5178 
5179   return false;
5180 }
5181 
5182 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5183   D.setFunctionDefinitionKind(FDK_Declaration);
5184   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5185 
5186   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5187       Dcl && Dcl->getDeclContext()->isFileContext())
5188     Dcl->setTopLevelDeclInObjCContainer();
5189 
5190   if (getLangOpts().OpenCL)
5191     setCurrentOpenCLExtensionForDecl(Dcl);
5192 
5193   return Dcl;
5194 }
5195 
5196 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5197 ///   If T is the name of a class, then each of the following shall have a
5198 ///   name different from T:
5199 ///     - every static data member of class T;
5200 ///     - every member function of class T
5201 ///     - every member of class T that is itself a type;
5202 /// \returns true if the declaration name violates these rules.
5203 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5204                                    DeclarationNameInfo NameInfo) {
5205   DeclarationName Name = NameInfo.getName();
5206 
5207   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5208   while (Record && Record->isAnonymousStructOrUnion())
5209     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5210   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5211     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5212     return true;
5213   }
5214 
5215   return false;
5216 }
5217 
5218 /// Diagnose a declaration whose declarator-id has the given
5219 /// nested-name-specifier.
5220 ///
5221 /// \param SS The nested-name-specifier of the declarator-id.
5222 ///
5223 /// \param DC The declaration context to which the nested-name-specifier
5224 /// resolves.
5225 ///
5226 /// \param Name The name of the entity being declared.
5227 ///
5228 /// \param Loc The location of the name of the entity being declared.
5229 ///
5230 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5231 /// we're declaring an explicit / partial specialization / instantiation.
5232 ///
5233 /// \returns true if we cannot safely recover from this error, false otherwise.
5234 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5235                                         DeclarationName Name,
5236                                         SourceLocation Loc, bool IsTemplateId) {
5237   DeclContext *Cur = CurContext;
5238   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5239     Cur = Cur->getParent();
5240 
5241   // If the user provided a superfluous scope specifier that refers back to the
5242   // class in which the entity is already declared, diagnose and ignore it.
5243   //
5244   // class X {
5245   //   void X::f();
5246   // };
5247   //
5248   // Note, it was once ill-formed to give redundant qualification in all
5249   // contexts, but that rule was removed by DR482.
5250   if (Cur->Equals(DC)) {
5251     if (Cur->isRecord()) {
5252       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5253                                       : diag::err_member_extra_qualification)
5254         << Name << FixItHint::CreateRemoval(SS.getRange());
5255       SS.clear();
5256     } else {
5257       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5258     }
5259     return false;
5260   }
5261 
5262   // Check whether the qualifying scope encloses the scope of the original
5263   // declaration. For a template-id, we perform the checks in
5264   // CheckTemplateSpecializationScope.
5265   if (!Cur->Encloses(DC) && !IsTemplateId) {
5266     if (Cur->isRecord())
5267       Diag(Loc, diag::err_member_qualification)
5268         << Name << SS.getRange();
5269     else if (isa<TranslationUnitDecl>(DC))
5270       Diag(Loc, diag::err_invalid_declarator_global_scope)
5271         << Name << SS.getRange();
5272     else if (isa<FunctionDecl>(Cur))
5273       Diag(Loc, diag::err_invalid_declarator_in_function)
5274         << Name << SS.getRange();
5275     else if (isa<BlockDecl>(Cur))
5276       Diag(Loc, diag::err_invalid_declarator_in_block)
5277         << Name << SS.getRange();
5278     else
5279       Diag(Loc, diag::err_invalid_declarator_scope)
5280       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5281 
5282     return true;
5283   }
5284 
5285   if (Cur->isRecord()) {
5286     // Cannot qualify members within a class.
5287     Diag(Loc, diag::err_member_qualification)
5288       << Name << SS.getRange();
5289     SS.clear();
5290 
5291     // C++ constructors and destructors with incorrect scopes can break
5292     // our AST invariants by having the wrong underlying types. If
5293     // that's the case, then drop this declaration entirely.
5294     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5295          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5296         !Context.hasSameType(Name.getCXXNameType(),
5297                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5298       return true;
5299 
5300     return false;
5301   }
5302 
5303   // C++11 [dcl.meaning]p1:
5304   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5305   //   not begin with a decltype-specifer"
5306   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5307   while (SpecLoc.getPrefix())
5308     SpecLoc = SpecLoc.getPrefix();
5309   if (dyn_cast_or_null<DecltypeType>(
5310         SpecLoc.getNestedNameSpecifier()->getAsType()))
5311     Diag(Loc, diag::err_decltype_in_declarator)
5312       << SpecLoc.getTypeLoc().getSourceRange();
5313 
5314   return false;
5315 }
5316 
5317 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5318                                   MultiTemplateParamsArg TemplateParamLists) {
5319   // TODO: consider using NameInfo for diagnostic.
5320   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5321   DeclarationName Name = NameInfo.getName();
5322 
5323   // All of these full declarators require an identifier.  If it doesn't have
5324   // one, the ParsedFreeStandingDeclSpec action should be used.
5325   if (D.isDecompositionDeclarator()) {
5326     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5327   } else if (!Name) {
5328     if (!D.isInvalidType())  // Reject this if we think it is valid.
5329       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5330           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5331     return nullptr;
5332   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5333     return nullptr;
5334 
5335   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5336   // we find one that is.
5337   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5338          (S->getFlags() & Scope::TemplateParamScope) != 0)
5339     S = S->getParent();
5340 
5341   DeclContext *DC = CurContext;
5342   if (D.getCXXScopeSpec().isInvalid())
5343     D.setInvalidType();
5344   else if (D.getCXXScopeSpec().isSet()) {
5345     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5346                                         UPPC_DeclarationQualifier))
5347       return nullptr;
5348 
5349     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5350     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5351     if (!DC || isa<EnumDecl>(DC)) {
5352       // If we could not compute the declaration context, it's because the
5353       // declaration context is dependent but does not refer to a class,
5354       // class template, or class template partial specialization. Complain
5355       // and return early, to avoid the coming semantic disaster.
5356       Diag(D.getIdentifierLoc(),
5357            diag::err_template_qualified_declarator_no_match)
5358         << D.getCXXScopeSpec().getScopeRep()
5359         << D.getCXXScopeSpec().getRange();
5360       return nullptr;
5361     }
5362     bool IsDependentContext = DC->isDependentContext();
5363 
5364     if (!IsDependentContext &&
5365         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5366       return nullptr;
5367 
5368     // If a class is incomplete, do not parse entities inside it.
5369     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5370       Diag(D.getIdentifierLoc(),
5371            diag::err_member_def_undefined_record)
5372         << Name << DC << D.getCXXScopeSpec().getRange();
5373       return nullptr;
5374     }
5375     if (!D.getDeclSpec().isFriendSpecified()) {
5376       if (diagnoseQualifiedDeclaration(
5377               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5378               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5379         if (DC->isRecord())
5380           return nullptr;
5381 
5382         D.setInvalidType();
5383       }
5384     }
5385 
5386     // Check whether we need to rebuild the type of the given
5387     // declaration in the current instantiation.
5388     if (EnteringContext && IsDependentContext &&
5389         TemplateParamLists.size() != 0) {
5390       ContextRAII SavedContext(*this, DC);
5391       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5392         D.setInvalidType();
5393     }
5394   }
5395 
5396   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5397   QualType R = TInfo->getType();
5398 
5399   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5400                                       UPPC_DeclarationType))
5401     D.setInvalidType();
5402 
5403   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5404                         forRedeclarationInCurContext());
5405 
5406   // See if this is a redefinition of a variable in the same scope.
5407   if (!D.getCXXScopeSpec().isSet()) {
5408     bool IsLinkageLookup = false;
5409     bool CreateBuiltins = false;
5410 
5411     // If the declaration we're planning to build will be a function
5412     // or object with linkage, then look for another declaration with
5413     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5414     //
5415     // If the declaration we're planning to build will be declared with
5416     // external linkage in the translation unit, create any builtin with
5417     // the same name.
5418     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5419       /* Do nothing*/;
5420     else if (CurContext->isFunctionOrMethod() &&
5421              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5422               R->isFunctionType())) {
5423       IsLinkageLookup = true;
5424       CreateBuiltins =
5425           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5426     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5427                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5428       CreateBuiltins = true;
5429 
5430     if (IsLinkageLookup) {
5431       Previous.clear(LookupRedeclarationWithLinkage);
5432       Previous.setRedeclarationKind(ForExternalRedeclaration);
5433     }
5434 
5435     LookupName(Previous, S, CreateBuiltins);
5436   } else { // Something like "int foo::x;"
5437     LookupQualifiedName(Previous, DC);
5438 
5439     // C++ [dcl.meaning]p1:
5440     //   When the declarator-id is qualified, the declaration shall refer to a
5441     //  previously declared member of the class or namespace to which the
5442     //  qualifier refers (or, in the case of a namespace, of an element of the
5443     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5444     //  thereof; [...]
5445     //
5446     // Note that we already checked the context above, and that we do not have
5447     // enough information to make sure that Previous contains the declaration
5448     // we want to match. For example, given:
5449     //
5450     //   class X {
5451     //     void f();
5452     //     void f(float);
5453     //   };
5454     //
5455     //   void X::f(int) { } // ill-formed
5456     //
5457     // In this case, Previous will point to the overload set
5458     // containing the two f's declared in X, but neither of them
5459     // matches.
5460 
5461     // C++ [dcl.meaning]p1:
5462     //   [...] the member shall not merely have been introduced by a
5463     //   using-declaration in the scope of the class or namespace nominated by
5464     //   the nested-name-specifier of the declarator-id.
5465     RemoveUsingDecls(Previous);
5466   }
5467 
5468   if (Previous.isSingleResult() &&
5469       Previous.getFoundDecl()->isTemplateParameter()) {
5470     // Maybe we will complain about the shadowed template parameter.
5471     if (!D.isInvalidType())
5472       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5473                                       Previous.getFoundDecl());
5474 
5475     // Just pretend that we didn't see the previous declaration.
5476     Previous.clear();
5477   }
5478 
5479   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5480     // Forget that the previous declaration is the injected-class-name.
5481     Previous.clear();
5482 
5483   // In C++, the previous declaration we find might be a tag type
5484   // (class or enum). In this case, the new declaration will hide the
5485   // tag type. Note that this applies to functions, function templates, and
5486   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5487   if (Previous.isSingleTagDecl() &&
5488       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5489       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5490     Previous.clear();
5491 
5492   // Check that there are no default arguments other than in the parameters
5493   // of a function declaration (C++ only).
5494   if (getLangOpts().CPlusPlus)
5495     CheckExtraCXXDefaultArguments(D);
5496 
5497   NamedDecl *New;
5498 
5499   bool AddToScope = true;
5500   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5501     if (TemplateParamLists.size()) {
5502       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5503       return nullptr;
5504     }
5505 
5506     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5507   } else if (R->isFunctionType()) {
5508     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5509                                   TemplateParamLists,
5510                                   AddToScope);
5511   } else {
5512     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5513                                   AddToScope);
5514   }
5515 
5516   if (!New)
5517     return nullptr;
5518 
5519   // If this has an identifier and is not a function template specialization,
5520   // add it to the scope stack.
5521   if (New->getDeclName() && AddToScope)
5522     PushOnScopeChains(New, S);
5523 
5524   if (isInOpenMPDeclareTargetContext())
5525     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5526 
5527   return New;
5528 }
5529 
5530 /// Helper method to turn variable array types into constant array
5531 /// types in certain situations which would otherwise be errors (for
5532 /// GCC compatibility).
5533 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5534                                                     ASTContext &Context,
5535                                                     bool &SizeIsNegative,
5536                                                     llvm::APSInt &Oversized) {
5537   // This method tries to turn a variable array into a constant
5538   // array even when the size isn't an ICE.  This is necessary
5539   // for compatibility with code that depends on gcc's buggy
5540   // constant expression folding, like struct {char x[(int)(char*)2];}
5541   SizeIsNegative = false;
5542   Oversized = 0;
5543 
5544   if (T->isDependentType())
5545     return QualType();
5546 
5547   QualifierCollector Qs;
5548   const Type *Ty = Qs.strip(T);
5549 
5550   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5551     QualType Pointee = PTy->getPointeeType();
5552     QualType FixedType =
5553         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5554                                             Oversized);
5555     if (FixedType.isNull()) return FixedType;
5556     FixedType = Context.getPointerType(FixedType);
5557     return Qs.apply(Context, FixedType);
5558   }
5559   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5560     QualType Inner = PTy->getInnerType();
5561     QualType FixedType =
5562         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5563                                             Oversized);
5564     if (FixedType.isNull()) return FixedType;
5565     FixedType = Context.getParenType(FixedType);
5566     return Qs.apply(Context, FixedType);
5567   }
5568 
5569   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5570   if (!VLATy)
5571     return QualType();
5572   // FIXME: We should probably handle this case
5573   if (VLATy->getElementType()->isVariablyModifiedType())
5574     return QualType();
5575 
5576   Expr::EvalResult Result;
5577   if (!VLATy->getSizeExpr() ||
5578       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5579     return QualType();
5580 
5581   llvm::APSInt Res = Result.Val.getInt();
5582 
5583   // Check whether the array size is negative.
5584   if (Res.isSigned() && Res.isNegative()) {
5585     SizeIsNegative = true;
5586     return QualType();
5587   }
5588 
5589   // Check whether the array is too large to be addressed.
5590   unsigned ActiveSizeBits
5591     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5592                                               Res);
5593   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5594     Oversized = Res;
5595     return QualType();
5596   }
5597 
5598   return Context.getConstantArrayType(VLATy->getElementType(),
5599                                       Res, ArrayType::Normal, 0);
5600 }
5601 
5602 static void
5603 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5604   SrcTL = SrcTL.getUnqualifiedLoc();
5605   DstTL = DstTL.getUnqualifiedLoc();
5606   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5607     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5608     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5609                                       DstPTL.getPointeeLoc());
5610     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5611     return;
5612   }
5613   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5614     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5615     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5616                                       DstPTL.getInnerLoc());
5617     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5618     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5619     return;
5620   }
5621   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5622   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5623   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5624   TypeLoc DstElemTL = DstATL.getElementLoc();
5625   DstElemTL.initializeFullCopy(SrcElemTL);
5626   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5627   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5628   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5629 }
5630 
5631 /// Helper method to turn variable array types into constant array
5632 /// types in certain situations which would otherwise be errors (for
5633 /// GCC compatibility).
5634 static TypeSourceInfo*
5635 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5636                                               ASTContext &Context,
5637                                               bool &SizeIsNegative,
5638                                               llvm::APSInt &Oversized) {
5639   QualType FixedTy
5640     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5641                                           SizeIsNegative, Oversized);
5642   if (FixedTy.isNull())
5643     return nullptr;
5644   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5645   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5646                                     FixedTInfo->getTypeLoc());
5647   return FixedTInfo;
5648 }
5649 
5650 /// Register the given locally-scoped extern "C" declaration so
5651 /// that it can be found later for redeclarations. We include any extern "C"
5652 /// declaration that is not visible in the translation unit here, not just
5653 /// function-scope declarations.
5654 void
5655 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5656   if (!getLangOpts().CPlusPlus &&
5657       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5658     // Don't need to track declarations in the TU in C.
5659     return;
5660 
5661   // Note that we have a locally-scoped external with this name.
5662   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5663 }
5664 
5665 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5666   // FIXME: We can have multiple results via __attribute__((overloadable)).
5667   auto Result = Context.getExternCContextDecl()->lookup(Name);
5668   return Result.empty() ? nullptr : *Result.begin();
5669 }
5670 
5671 /// Diagnose function specifiers on a declaration of an identifier that
5672 /// does not identify a function.
5673 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5674   // FIXME: We should probably indicate the identifier in question to avoid
5675   // confusion for constructs like "virtual int a(), b;"
5676   if (DS.isVirtualSpecified())
5677     Diag(DS.getVirtualSpecLoc(),
5678          diag::err_virtual_non_function);
5679 
5680   if (DS.isExplicitSpecified())
5681     Diag(DS.getExplicitSpecLoc(),
5682          diag::err_explicit_non_function);
5683 
5684   if (DS.isNoreturnSpecified())
5685     Diag(DS.getNoreturnSpecLoc(),
5686          diag::err_noreturn_non_function);
5687 }
5688 
5689 NamedDecl*
5690 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5691                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5692   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5693   if (D.getCXXScopeSpec().isSet()) {
5694     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5695       << D.getCXXScopeSpec().getRange();
5696     D.setInvalidType();
5697     // Pretend we didn't see the scope specifier.
5698     DC = CurContext;
5699     Previous.clear();
5700   }
5701 
5702   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5703 
5704   if (D.getDeclSpec().isInlineSpecified())
5705     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5706         << getLangOpts().CPlusPlus17;
5707   if (D.getDeclSpec().isConstexprSpecified())
5708     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5709       << 1;
5710 
5711   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5712     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5713       Diag(D.getName().StartLocation,
5714            diag::err_deduction_guide_invalid_specifier)
5715           << "typedef";
5716     else
5717       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5718           << D.getName().getSourceRange();
5719     return nullptr;
5720   }
5721 
5722   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5723   if (!NewTD) return nullptr;
5724 
5725   // Handle attributes prior to checking for duplicates in MergeVarDecl
5726   ProcessDeclAttributes(S, NewTD, D);
5727 
5728   CheckTypedefForVariablyModifiedType(S, NewTD);
5729 
5730   bool Redeclaration = D.isRedeclaration();
5731   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5732   D.setRedeclaration(Redeclaration);
5733   return ND;
5734 }
5735 
5736 void
5737 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5738   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5739   // then it shall have block scope.
5740   // Note that variably modified types must be fixed before merging the decl so
5741   // that redeclarations will match.
5742   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5743   QualType T = TInfo->getType();
5744   if (T->isVariablyModifiedType()) {
5745     setFunctionHasBranchProtectedScope();
5746 
5747     if (S->getFnParent() == nullptr) {
5748       bool SizeIsNegative;
5749       llvm::APSInt Oversized;
5750       TypeSourceInfo *FixedTInfo =
5751         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5752                                                       SizeIsNegative,
5753                                                       Oversized);
5754       if (FixedTInfo) {
5755         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5756         NewTD->setTypeSourceInfo(FixedTInfo);
5757       } else {
5758         if (SizeIsNegative)
5759           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5760         else if (T->isVariableArrayType())
5761           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5762         else if (Oversized.getBoolValue())
5763           Diag(NewTD->getLocation(), diag::err_array_too_large)
5764             << Oversized.toString(10);
5765         else
5766           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5767         NewTD->setInvalidDecl();
5768       }
5769     }
5770   }
5771 }
5772 
5773 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5774 /// declares a typedef-name, either using the 'typedef' type specifier or via
5775 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5776 NamedDecl*
5777 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5778                            LookupResult &Previous, bool &Redeclaration) {
5779 
5780   // Find the shadowed declaration before filtering for scope.
5781   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5782 
5783   // Merge the decl with the existing one if appropriate. If the decl is
5784   // in an outer scope, it isn't the same thing.
5785   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5786                        /*AllowInlineNamespace*/false);
5787   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5788   if (!Previous.empty()) {
5789     Redeclaration = true;
5790     MergeTypedefNameDecl(S, NewTD, Previous);
5791   }
5792 
5793   if (ShadowedDecl && !Redeclaration)
5794     CheckShadow(NewTD, ShadowedDecl, Previous);
5795 
5796   // If this is the C FILE type, notify the AST context.
5797   if (IdentifierInfo *II = NewTD->getIdentifier())
5798     if (!NewTD->isInvalidDecl() &&
5799         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5800       if (II->isStr("FILE"))
5801         Context.setFILEDecl(NewTD);
5802       else if (II->isStr("jmp_buf"))
5803         Context.setjmp_bufDecl(NewTD);
5804       else if (II->isStr("sigjmp_buf"))
5805         Context.setsigjmp_bufDecl(NewTD);
5806       else if (II->isStr("ucontext_t"))
5807         Context.setucontext_tDecl(NewTD);
5808     }
5809 
5810   return NewTD;
5811 }
5812 
5813 /// Determines whether the given declaration is an out-of-scope
5814 /// previous declaration.
5815 ///
5816 /// This routine should be invoked when name lookup has found a
5817 /// previous declaration (PrevDecl) that is not in the scope where a
5818 /// new declaration by the same name is being introduced. If the new
5819 /// declaration occurs in a local scope, previous declarations with
5820 /// linkage may still be considered previous declarations (C99
5821 /// 6.2.2p4-5, C++ [basic.link]p6).
5822 ///
5823 /// \param PrevDecl the previous declaration found by name
5824 /// lookup
5825 ///
5826 /// \param DC the context in which the new declaration is being
5827 /// declared.
5828 ///
5829 /// \returns true if PrevDecl is an out-of-scope previous declaration
5830 /// for a new delcaration with the same name.
5831 static bool
5832 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5833                                 ASTContext &Context) {
5834   if (!PrevDecl)
5835     return false;
5836 
5837   if (!PrevDecl->hasLinkage())
5838     return false;
5839 
5840   if (Context.getLangOpts().CPlusPlus) {
5841     // C++ [basic.link]p6:
5842     //   If there is a visible declaration of an entity with linkage
5843     //   having the same name and type, ignoring entities declared
5844     //   outside the innermost enclosing namespace scope, the block
5845     //   scope declaration declares that same entity and receives the
5846     //   linkage of the previous declaration.
5847     DeclContext *OuterContext = DC->getRedeclContext();
5848     if (!OuterContext->isFunctionOrMethod())
5849       // This rule only applies to block-scope declarations.
5850       return false;
5851 
5852     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5853     if (PrevOuterContext->isRecord())
5854       // We found a member function: ignore it.
5855       return false;
5856 
5857     // Find the innermost enclosing namespace for the new and
5858     // previous declarations.
5859     OuterContext = OuterContext->getEnclosingNamespaceContext();
5860     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5861 
5862     // The previous declaration is in a different namespace, so it
5863     // isn't the same function.
5864     if (!OuterContext->Equals(PrevOuterContext))
5865       return false;
5866   }
5867 
5868   return true;
5869 }
5870 
5871 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5872   CXXScopeSpec &SS = D.getCXXScopeSpec();
5873   if (!SS.isSet()) return;
5874   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5875 }
5876 
5877 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5878   QualType type = decl->getType();
5879   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5880   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5881     // Various kinds of declaration aren't allowed to be __autoreleasing.
5882     unsigned kind = -1U;
5883     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5884       if (var->hasAttr<BlocksAttr>())
5885         kind = 0; // __block
5886       else if (!var->hasLocalStorage())
5887         kind = 1; // global
5888     } else if (isa<ObjCIvarDecl>(decl)) {
5889       kind = 3; // ivar
5890     } else if (isa<FieldDecl>(decl)) {
5891       kind = 2; // field
5892     }
5893 
5894     if (kind != -1U) {
5895       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5896         << kind;
5897     }
5898   } else if (lifetime == Qualifiers::OCL_None) {
5899     // Try to infer lifetime.
5900     if (!type->isObjCLifetimeType())
5901       return false;
5902 
5903     lifetime = type->getObjCARCImplicitLifetime();
5904     type = Context.getLifetimeQualifiedType(type, lifetime);
5905     decl->setType(type);
5906   }
5907 
5908   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5909     // Thread-local variables cannot have lifetime.
5910     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5911         var->getTLSKind()) {
5912       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5913         << var->getType();
5914       return true;
5915     }
5916   }
5917 
5918   return false;
5919 }
5920 
5921 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5922   // Ensure that an auto decl is deduced otherwise the checks below might cache
5923   // the wrong linkage.
5924   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5925 
5926   // 'weak' only applies to declarations with external linkage.
5927   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5928     if (!ND.isExternallyVisible()) {
5929       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5930       ND.dropAttr<WeakAttr>();
5931     }
5932   }
5933   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5934     if (ND.isExternallyVisible()) {
5935       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5936       ND.dropAttr<WeakRefAttr>();
5937       ND.dropAttr<AliasAttr>();
5938     }
5939   }
5940 
5941   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5942     if (VD->hasInit()) {
5943       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5944         assert(VD->isThisDeclarationADefinition() &&
5945                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5946         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5947         VD->dropAttr<AliasAttr>();
5948       }
5949     }
5950   }
5951 
5952   // 'selectany' only applies to externally visible variable declarations.
5953   // It does not apply to functions.
5954   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5955     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5956       S.Diag(Attr->getLocation(),
5957              diag::err_attribute_selectany_non_extern_data);
5958       ND.dropAttr<SelectAnyAttr>();
5959     }
5960   }
5961 
5962   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5963     // dll attributes require external linkage. Static locals may have external
5964     // linkage but still cannot be explicitly imported or exported.
5965     auto *VD = dyn_cast<VarDecl>(&ND);
5966     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5967       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5968         << &ND << Attr;
5969       ND.setInvalidDecl();
5970     }
5971   }
5972 
5973   // Virtual functions cannot be marked as 'notail'.
5974   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5975     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5976       if (MD->isVirtual()) {
5977         S.Diag(ND.getLocation(),
5978                diag::err_invalid_attribute_on_virtual_function)
5979             << Attr;
5980         ND.dropAttr<NotTailCalledAttr>();
5981       }
5982 
5983   // Check the attributes on the function type, if any.
5984   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
5985     // Don't declare this variable in the second operand of the for-statement;
5986     // GCC miscompiles that by ending its lifetime before evaluating the
5987     // third operand. See gcc.gnu.org/PR86769.
5988     AttributedTypeLoc ATL;
5989     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
5990          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
5991          TL = ATL.getModifiedLoc()) {
5992       // The [[lifetimebound]] attribute can be applied to the implicit object
5993       // parameter of a non-static member function (other than a ctor or dtor)
5994       // by applying it to the function type.
5995       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
5996         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
5997         if (!MD || MD->isStatic()) {
5998           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
5999               << !MD << A->getRange();
6000         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6001           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6002               << isa<CXXDestructorDecl>(MD) << A->getRange();
6003         }
6004       }
6005     }
6006   }
6007 }
6008 
6009 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6010                                            NamedDecl *NewDecl,
6011                                            bool IsSpecialization,
6012                                            bool IsDefinition) {
6013   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6014     return;
6015 
6016   bool IsTemplate = false;
6017   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6018     OldDecl = OldTD->getTemplatedDecl();
6019     IsTemplate = true;
6020     if (!IsSpecialization)
6021       IsDefinition = false;
6022   }
6023   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6024     NewDecl = NewTD->getTemplatedDecl();
6025     IsTemplate = true;
6026   }
6027 
6028   if (!OldDecl || !NewDecl)
6029     return;
6030 
6031   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6032   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6033   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6034   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6035 
6036   // dllimport and dllexport are inheritable attributes so we have to exclude
6037   // inherited attribute instances.
6038   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6039                     (NewExportAttr && !NewExportAttr->isInherited());
6040 
6041   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6042   // the only exception being explicit specializations.
6043   // Implicitly generated declarations are also excluded for now because there
6044   // is no other way to switch these to use dllimport or dllexport.
6045   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6046 
6047   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6048     // Allow with a warning for free functions and global variables.
6049     bool JustWarn = false;
6050     if (!OldDecl->isCXXClassMember()) {
6051       auto *VD = dyn_cast<VarDecl>(OldDecl);
6052       if (VD && !VD->getDescribedVarTemplate())
6053         JustWarn = true;
6054       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6055       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6056         JustWarn = true;
6057     }
6058 
6059     // We cannot change a declaration that's been used because IR has already
6060     // been emitted. Dllimported functions will still work though (modulo
6061     // address equality) as they can use the thunk.
6062     if (OldDecl->isUsed())
6063       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6064         JustWarn = false;
6065 
6066     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6067                                : diag::err_attribute_dll_redeclaration;
6068     S.Diag(NewDecl->getLocation(), DiagID)
6069         << NewDecl
6070         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6071     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6072     if (!JustWarn) {
6073       NewDecl->setInvalidDecl();
6074       return;
6075     }
6076   }
6077 
6078   // A redeclaration is not allowed to drop a dllimport attribute, the only
6079   // exceptions being inline function definitions (except for function
6080   // templates), local extern declarations, qualified friend declarations or
6081   // special MSVC extension: in the last case, the declaration is treated as if
6082   // it were marked dllexport.
6083   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6084   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6085   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6086     // Ignore static data because out-of-line definitions are diagnosed
6087     // separately.
6088     IsStaticDataMember = VD->isStaticDataMember();
6089     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6090                    VarDecl::DeclarationOnly;
6091   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6092     IsInline = FD->isInlined();
6093     IsQualifiedFriend = FD->getQualifier() &&
6094                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6095   }
6096 
6097   if (OldImportAttr && !HasNewAttr &&
6098       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6099       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6100     if (IsMicrosoft && IsDefinition) {
6101       S.Diag(NewDecl->getLocation(),
6102              diag::warn_redeclaration_without_import_attribute)
6103           << NewDecl;
6104       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6105       NewDecl->dropAttr<DLLImportAttr>();
6106       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6107           NewImportAttr->getRange(), S.Context,
6108           NewImportAttr->getSpellingListIndex()));
6109     } else {
6110       S.Diag(NewDecl->getLocation(),
6111              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6112           << NewDecl << OldImportAttr;
6113       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6114       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6115       OldDecl->dropAttr<DLLImportAttr>();
6116       NewDecl->dropAttr<DLLImportAttr>();
6117     }
6118   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6119     // In MinGW, seeing a function declared inline drops the dllimport
6120     // attribute.
6121     OldDecl->dropAttr<DLLImportAttr>();
6122     NewDecl->dropAttr<DLLImportAttr>();
6123     S.Diag(NewDecl->getLocation(),
6124            diag::warn_dllimport_dropped_from_inline_function)
6125         << NewDecl << OldImportAttr;
6126   }
6127 
6128   // A specialization of a class template member function is processed here
6129   // since it's a redeclaration. If the parent class is dllexport, the
6130   // specialization inherits that attribute. This doesn't happen automatically
6131   // since the parent class isn't instantiated until later.
6132   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6133     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6134         !NewImportAttr && !NewExportAttr) {
6135       if (const DLLExportAttr *ParentExportAttr =
6136               MD->getParent()->getAttr<DLLExportAttr>()) {
6137         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6138         NewAttr->setInherited(true);
6139         NewDecl->addAttr(NewAttr);
6140       }
6141     }
6142   }
6143 }
6144 
6145 /// Given that we are within the definition of the given function,
6146 /// will that definition behave like C99's 'inline', where the
6147 /// definition is discarded except for optimization purposes?
6148 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6149   // Try to avoid calling GetGVALinkageForFunction.
6150 
6151   // All cases of this require the 'inline' keyword.
6152   if (!FD->isInlined()) return false;
6153 
6154   // This is only possible in C++ with the gnu_inline attribute.
6155   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6156     return false;
6157 
6158   // Okay, go ahead and call the relatively-more-expensive function.
6159   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6160 }
6161 
6162 /// Determine whether a variable is extern "C" prior to attaching
6163 /// an initializer. We can't just call isExternC() here, because that
6164 /// will also compute and cache whether the declaration is externally
6165 /// visible, which might change when we attach the initializer.
6166 ///
6167 /// This can only be used if the declaration is known to not be a
6168 /// redeclaration of an internal linkage declaration.
6169 ///
6170 /// For instance:
6171 ///
6172 ///   auto x = []{};
6173 ///
6174 /// Attaching the initializer here makes this declaration not externally
6175 /// visible, because its type has internal linkage.
6176 ///
6177 /// FIXME: This is a hack.
6178 template<typename T>
6179 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6180   if (S.getLangOpts().CPlusPlus) {
6181     // In C++, the overloadable attribute negates the effects of extern "C".
6182     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6183       return false;
6184 
6185     // So do CUDA's host/device attributes.
6186     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6187                                  D->template hasAttr<CUDAHostAttr>()))
6188       return false;
6189   }
6190   return D->isExternC();
6191 }
6192 
6193 static bool shouldConsiderLinkage(const VarDecl *VD) {
6194   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6195   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6196       isa<OMPDeclareMapperDecl>(DC))
6197     return VD->hasExternalStorage();
6198   if (DC->isFileContext())
6199     return true;
6200   if (DC->isRecord())
6201     return false;
6202   llvm_unreachable("Unexpected context");
6203 }
6204 
6205 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6206   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6207   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6208       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6209     return true;
6210   if (DC->isRecord())
6211     return false;
6212   llvm_unreachable("Unexpected context");
6213 }
6214 
6215 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6216                           ParsedAttr::Kind Kind) {
6217   // Check decl attributes on the DeclSpec.
6218   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6219     return true;
6220 
6221   // Walk the declarator structure, checking decl attributes that were in a type
6222   // position to the decl itself.
6223   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6224     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6225       return true;
6226   }
6227 
6228   // Finally, check attributes on the decl itself.
6229   return PD.getAttributes().hasAttribute(Kind);
6230 }
6231 
6232 /// Adjust the \c DeclContext for a function or variable that might be a
6233 /// function-local external declaration.
6234 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6235   if (!DC->isFunctionOrMethod())
6236     return false;
6237 
6238   // If this is a local extern function or variable declared within a function
6239   // template, don't add it into the enclosing namespace scope until it is
6240   // instantiated; it might have a dependent type right now.
6241   if (DC->isDependentContext())
6242     return true;
6243 
6244   // C++11 [basic.link]p7:
6245   //   When a block scope declaration of an entity with linkage is not found to
6246   //   refer to some other declaration, then that entity is a member of the
6247   //   innermost enclosing namespace.
6248   //
6249   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6250   // semantically-enclosing namespace, not a lexically-enclosing one.
6251   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6252     DC = DC->getParent();
6253   return true;
6254 }
6255 
6256 /// Returns true if given declaration has external C language linkage.
6257 static bool isDeclExternC(const Decl *D) {
6258   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6259     return FD->isExternC();
6260   if (const auto *VD = dyn_cast<VarDecl>(D))
6261     return VD->isExternC();
6262 
6263   llvm_unreachable("Unknown type of decl!");
6264 }
6265 
6266 NamedDecl *Sema::ActOnVariableDeclarator(
6267     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6268     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6269     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6270   QualType R = TInfo->getType();
6271   DeclarationName Name = GetNameForDeclarator(D).getName();
6272 
6273   IdentifierInfo *II = Name.getAsIdentifierInfo();
6274 
6275   if (D.isDecompositionDeclarator()) {
6276     // Take the name of the first declarator as our name for diagnostic
6277     // purposes.
6278     auto &Decomp = D.getDecompositionDeclarator();
6279     if (!Decomp.bindings().empty()) {
6280       II = Decomp.bindings()[0].Name;
6281       Name = II;
6282     }
6283   } else if (!II) {
6284     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6285     return nullptr;
6286   }
6287 
6288   if (getLangOpts().OpenCL) {
6289     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6290     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6291     // argument.
6292     if (R->isImageType() || R->isPipeType()) {
6293       Diag(D.getIdentifierLoc(),
6294            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6295           << R;
6296       D.setInvalidType();
6297       return nullptr;
6298     }
6299 
6300     // OpenCL v1.2 s6.9.r:
6301     // The event type cannot be used to declare a program scope variable.
6302     // OpenCL v2.0 s6.9.q:
6303     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6304     if (NULL == S->getParent()) {
6305       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6306         Diag(D.getIdentifierLoc(),
6307              diag::err_invalid_type_for_program_scope_var) << R;
6308         D.setInvalidType();
6309         return nullptr;
6310       }
6311     }
6312 
6313     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6314     QualType NR = R;
6315     while (NR->isPointerType()) {
6316       if (NR->isFunctionPointerType()) {
6317         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6318         D.setInvalidType();
6319         break;
6320       }
6321       NR = NR->getPointeeType();
6322     }
6323 
6324     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6325       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6326       // half array type (unless the cl_khr_fp16 extension is enabled).
6327       if (Context.getBaseElementType(R)->isHalfType()) {
6328         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6329         D.setInvalidType();
6330       }
6331     }
6332 
6333     if (R->isSamplerT()) {
6334       // OpenCL v1.2 s6.9.b p4:
6335       // The sampler type cannot be used with the __local and __global address
6336       // space qualifiers.
6337       if (R.getAddressSpace() == LangAS::opencl_local ||
6338           R.getAddressSpace() == LangAS::opencl_global) {
6339         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6340       }
6341 
6342       // OpenCL v1.2 s6.12.14.1:
6343       // A global sampler must be declared with either the constant address
6344       // space qualifier or with the const qualifier.
6345       if (DC->isTranslationUnit() &&
6346           !(R.getAddressSpace() == LangAS::opencl_constant ||
6347           R.isConstQualified())) {
6348         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6349         D.setInvalidType();
6350       }
6351     }
6352 
6353     // OpenCL v1.2 s6.9.r:
6354     // The event type cannot be used with the __local, __constant and __global
6355     // address space qualifiers.
6356     if (R->isEventT()) {
6357       if (R.getAddressSpace() != LangAS::opencl_private) {
6358         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6359         D.setInvalidType();
6360       }
6361     }
6362 
6363     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6364     // supported.  OpenCL C does not support thread_local either, and
6365     // also reject all other thread storage class specifiers.
6366     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6367     if (TSC != TSCS_unspecified) {
6368       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6369       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6370            diag::err_opencl_unknown_type_specifier)
6371           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6372           << DeclSpec::getSpecifierName(TSC) << 1;
6373       D.setInvalidType();
6374       return nullptr;
6375     }
6376   }
6377 
6378   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6379   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6380 
6381   // dllimport globals without explicit storage class are treated as extern. We
6382   // have to change the storage class this early to get the right DeclContext.
6383   if (SC == SC_None && !DC->isRecord() &&
6384       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6385       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6386     SC = SC_Extern;
6387 
6388   DeclContext *OriginalDC = DC;
6389   bool IsLocalExternDecl = SC == SC_Extern &&
6390                            adjustContextForLocalExternDecl(DC);
6391 
6392   if (SCSpec == DeclSpec::SCS_mutable) {
6393     // mutable can only appear on non-static class members, so it's always
6394     // an error here
6395     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6396     D.setInvalidType();
6397     SC = SC_None;
6398   }
6399 
6400   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6401       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6402                               D.getDeclSpec().getStorageClassSpecLoc())) {
6403     // In C++11, the 'register' storage class specifier is deprecated.
6404     // Suppress the warning in system macros, it's used in macros in some
6405     // popular C system headers, such as in glibc's htonl() macro.
6406     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6407          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6408                                    : diag::warn_deprecated_register)
6409       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6410   }
6411 
6412   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6413 
6414   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6415     // C99 6.9p2: The storage-class specifiers auto and register shall not
6416     // appear in the declaration specifiers in an external declaration.
6417     // Global Register+Asm is a GNU extension we support.
6418     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6419       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6420       D.setInvalidType();
6421     }
6422   }
6423 
6424   bool IsMemberSpecialization = false;
6425   bool IsVariableTemplateSpecialization = false;
6426   bool IsPartialSpecialization = false;
6427   bool IsVariableTemplate = false;
6428   VarDecl *NewVD = nullptr;
6429   VarTemplateDecl *NewTemplate = nullptr;
6430   TemplateParameterList *TemplateParams = nullptr;
6431   if (!getLangOpts().CPlusPlus) {
6432     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6433                             II, R, TInfo, SC);
6434 
6435     if (R->getContainedDeducedType())
6436       ParsingInitForAutoVars.insert(NewVD);
6437 
6438     if (D.isInvalidType())
6439       NewVD->setInvalidDecl();
6440   } else {
6441     bool Invalid = false;
6442 
6443     if (DC->isRecord() && !CurContext->isRecord()) {
6444       // This is an out-of-line definition of a static data member.
6445       switch (SC) {
6446       case SC_None:
6447         break;
6448       case SC_Static:
6449         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6450              diag::err_static_out_of_line)
6451           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6452         break;
6453       case SC_Auto:
6454       case SC_Register:
6455       case SC_Extern:
6456         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6457         // to names of variables declared in a block or to function parameters.
6458         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6459         // of class members
6460 
6461         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6462              diag::err_storage_class_for_static_member)
6463           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6464         break;
6465       case SC_PrivateExtern:
6466         llvm_unreachable("C storage class in c++!");
6467       }
6468     }
6469 
6470     if (SC == SC_Static && CurContext->isRecord()) {
6471       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6472         if (RD->isLocalClass())
6473           Diag(D.getIdentifierLoc(),
6474                diag::err_static_data_member_not_allowed_in_local_class)
6475             << Name << RD->getDeclName();
6476 
6477         // C++98 [class.union]p1: If a union contains a static data member,
6478         // the program is ill-formed. C++11 drops this restriction.
6479         if (RD->isUnion())
6480           Diag(D.getIdentifierLoc(),
6481                getLangOpts().CPlusPlus11
6482                  ? diag::warn_cxx98_compat_static_data_member_in_union
6483                  : diag::ext_static_data_member_in_union) << Name;
6484         // We conservatively disallow static data members in anonymous structs.
6485         else if (!RD->getDeclName())
6486           Diag(D.getIdentifierLoc(),
6487                diag::err_static_data_member_not_allowed_in_anon_struct)
6488             << Name << RD->isUnion();
6489       }
6490     }
6491 
6492     // Match up the template parameter lists with the scope specifier, then
6493     // determine whether we have a template or a template specialization.
6494     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6495         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6496         D.getCXXScopeSpec(),
6497         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6498             ? D.getName().TemplateId
6499             : nullptr,
6500         TemplateParamLists,
6501         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6502 
6503     if (TemplateParams) {
6504       if (!TemplateParams->size() &&
6505           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6506         // There is an extraneous 'template<>' for this variable. Complain
6507         // about it, but allow the declaration of the variable.
6508         Diag(TemplateParams->getTemplateLoc(),
6509              diag::err_template_variable_noparams)
6510           << II
6511           << SourceRange(TemplateParams->getTemplateLoc(),
6512                          TemplateParams->getRAngleLoc());
6513         TemplateParams = nullptr;
6514       } else {
6515         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6516           // This is an explicit specialization or a partial specialization.
6517           // FIXME: Check that we can declare a specialization here.
6518           IsVariableTemplateSpecialization = true;
6519           IsPartialSpecialization = TemplateParams->size() > 0;
6520         } else { // if (TemplateParams->size() > 0)
6521           // This is a template declaration.
6522           IsVariableTemplate = true;
6523 
6524           // Check that we can declare a template here.
6525           if (CheckTemplateDeclScope(S, TemplateParams))
6526             return nullptr;
6527 
6528           // Only C++1y supports variable templates (N3651).
6529           Diag(D.getIdentifierLoc(),
6530                getLangOpts().CPlusPlus14
6531                    ? diag::warn_cxx11_compat_variable_template
6532                    : diag::ext_variable_template);
6533         }
6534       }
6535     } else {
6536       assert((Invalid ||
6537               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6538              "should have a 'template<>' for this decl");
6539     }
6540 
6541     if (IsVariableTemplateSpecialization) {
6542       SourceLocation TemplateKWLoc =
6543           TemplateParamLists.size() > 0
6544               ? TemplateParamLists[0]->getTemplateLoc()
6545               : SourceLocation();
6546       DeclResult Res = ActOnVarTemplateSpecialization(
6547           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6548           IsPartialSpecialization);
6549       if (Res.isInvalid())
6550         return nullptr;
6551       NewVD = cast<VarDecl>(Res.get());
6552       AddToScope = false;
6553     } else if (D.isDecompositionDeclarator()) {
6554       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6555                                         D.getIdentifierLoc(), R, TInfo, SC,
6556                                         Bindings);
6557     } else
6558       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6559                               D.getIdentifierLoc(), II, R, TInfo, SC);
6560 
6561     // If this is supposed to be a variable template, create it as such.
6562     if (IsVariableTemplate) {
6563       NewTemplate =
6564           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6565                                   TemplateParams, NewVD);
6566       NewVD->setDescribedVarTemplate(NewTemplate);
6567     }
6568 
6569     // If this decl has an auto type in need of deduction, make a note of the
6570     // Decl so we can diagnose uses of it in its own initializer.
6571     if (R->getContainedDeducedType())
6572       ParsingInitForAutoVars.insert(NewVD);
6573 
6574     if (D.isInvalidType() || Invalid) {
6575       NewVD->setInvalidDecl();
6576       if (NewTemplate)
6577         NewTemplate->setInvalidDecl();
6578     }
6579 
6580     SetNestedNameSpecifier(*this, NewVD, D);
6581 
6582     // If we have any template parameter lists that don't directly belong to
6583     // the variable (matching the scope specifier), store them.
6584     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6585     if (TemplateParamLists.size() > VDTemplateParamLists)
6586       NewVD->setTemplateParameterListsInfo(
6587           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6588 
6589     if (D.getDeclSpec().isConstexprSpecified()) {
6590       NewVD->setConstexpr(true);
6591       // C++1z [dcl.spec.constexpr]p1:
6592       //   A static data member declared with the constexpr specifier is
6593       //   implicitly an inline variable.
6594       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6595         NewVD->setImplicitlyInline();
6596     }
6597   }
6598 
6599   if (D.getDeclSpec().isInlineSpecified()) {
6600     if (!getLangOpts().CPlusPlus) {
6601       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6602           << 0;
6603     } else if (CurContext->isFunctionOrMethod()) {
6604       // 'inline' is not allowed on block scope variable declaration.
6605       Diag(D.getDeclSpec().getInlineSpecLoc(),
6606            diag::err_inline_declaration_block_scope) << Name
6607         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6608     } else {
6609       Diag(D.getDeclSpec().getInlineSpecLoc(),
6610            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6611                                      : diag::ext_inline_variable);
6612       NewVD->setInlineSpecified();
6613     }
6614   }
6615 
6616   // Set the lexical context. If the declarator has a C++ scope specifier, the
6617   // lexical context will be different from the semantic context.
6618   NewVD->setLexicalDeclContext(CurContext);
6619   if (NewTemplate)
6620     NewTemplate->setLexicalDeclContext(CurContext);
6621 
6622   if (IsLocalExternDecl) {
6623     if (D.isDecompositionDeclarator())
6624       for (auto *B : Bindings)
6625         B->setLocalExternDecl();
6626     else
6627       NewVD->setLocalExternDecl();
6628   }
6629 
6630   bool EmitTLSUnsupportedError = false;
6631   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6632     // C++11 [dcl.stc]p4:
6633     //   When thread_local is applied to a variable of block scope the
6634     //   storage-class-specifier static is implied if it does not appear
6635     //   explicitly.
6636     // Core issue: 'static' is not implied if the variable is declared
6637     //   'extern'.
6638     if (NewVD->hasLocalStorage() &&
6639         (SCSpec != DeclSpec::SCS_unspecified ||
6640          TSCS != DeclSpec::TSCS_thread_local ||
6641          !DC->isFunctionOrMethod()))
6642       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6643            diag::err_thread_non_global)
6644         << DeclSpec::getSpecifierName(TSCS);
6645     else if (!Context.getTargetInfo().isTLSSupported()) {
6646       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6647         // Postpone error emission until we've collected attributes required to
6648         // figure out whether it's a host or device variable and whether the
6649         // error should be ignored.
6650         EmitTLSUnsupportedError = true;
6651         // We still need to mark the variable as TLS so it shows up in AST with
6652         // proper storage class for other tools to use even if we're not going
6653         // to emit any code for it.
6654         NewVD->setTSCSpec(TSCS);
6655       } else
6656         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6657              diag::err_thread_unsupported);
6658     } else
6659       NewVD->setTSCSpec(TSCS);
6660   }
6661 
6662   // C99 6.7.4p3
6663   //   An inline definition of a function with external linkage shall
6664   //   not contain a definition of a modifiable object with static or
6665   //   thread storage duration...
6666   // We only apply this when the function is required to be defined
6667   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6668   // that a local variable with thread storage duration still has to
6669   // be marked 'static'.  Also note that it's possible to get these
6670   // semantics in C++ using __attribute__((gnu_inline)).
6671   if (SC == SC_Static && S->getFnParent() != nullptr &&
6672       !NewVD->getType().isConstQualified()) {
6673     FunctionDecl *CurFD = getCurFunctionDecl();
6674     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6675       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6676            diag::warn_static_local_in_extern_inline);
6677       MaybeSuggestAddingStaticToDecl(CurFD);
6678     }
6679   }
6680 
6681   if (D.getDeclSpec().isModulePrivateSpecified()) {
6682     if (IsVariableTemplateSpecialization)
6683       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6684           << (IsPartialSpecialization ? 1 : 0)
6685           << FixItHint::CreateRemoval(
6686                  D.getDeclSpec().getModulePrivateSpecLoc());
6687     else if (IsMemberSpecialization)
6688       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6689         << 2
6690         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6691     else if (NewVD->hasLocalStorage())
6692       Diag(NewVD->getLocation(), diag::err_module_private_local)
6693         << 0 << NewVD->getDeclName()
6694         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6695         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6696     else {
6697       NewVD->setModulePrivate();
6698       if (NewTemplate)
6699         NewTemplate->setModulePrivate();
6700       for (auto *B : Bindings)
6701         B->setModulePrivate();
6702     }
6703   }
6704 
6705   // Handle attributes prior to checking for duplicates in MergeVarDecl
6706   ProcessDeclAttributes(S, NewVD, D);
6707 
6708   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6709     if (EmitTLSUnsupportedError &&
6710         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6711          (getLangOpts().OpenMPIsDevice &&
6712           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6713       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6714            diag::err_thread_unsupported);
6715     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6716     // storage [duration]."
6717     if (SC == SC_None && S->getFnParent() != nullptr &&
6718         (NewVD->hasAttr<CUDASharedAttr>() ||
6719          NewVD->hasAttr<CUDAConstantAttr>())) {
6720       NewVD->setStorageClass(SC_Static);
6721     }
6722   }
6723 
6724   // Ensure that dllimport globals without explicit storage class are treated as
6725   // extern. The storage class is set above using parsed attributes. Now we can
6726   // check the VarDecl itself.
6727   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6728          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6729          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6730 
6731   // In auto-retain/release, infer strong retension for variables of
6732   // retainable type.
6733   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6734     NewVD->setInvalidDecl();
6735 
6736   // Handle GNU asm-label extension (encoded as an attribute).
6737   if (Expr *E = (Expr*)D.getAsmLabel()) {
6738     // The parser guarantees this is a string.
6739     StringLiteral *SE = cast<StringLiteral>(E);
6740     StringRef Label = SE->getString();
6741     if (S->getFnParent() != nullptr) {
6742       switch (SC) {
6743       case SC_None:
6744       case SC_Auto:
6745         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6746         break;
6747       case SC_Register:
6748         // Local Named register
6749         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6750             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6751           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6752         break;
6753       case SC_Static:
6754       case SC_Extern:
6755       case SC_PrivateExtern:
6756         break;
6757       }
6758     } else if (SC == SC_Register) {
6759       // Global Named register
6760       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6761         const auto &TI = Context.getTargetInfo();
6762         bool HasSizeMismatch;
6763 
6764         if (!TI.isValidGCCRegisterName(Label))
6765           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6766         else if (!TI.validateGlobalRegisterVariable(Label,
6767                                                     Context.getTypeSize(R),
6768                                                     HasSizeMismatch))
6769           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6770         else if (HasSizeMismatch)
6771           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6772       }
6773 
6774       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6775         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6776         NewVD->setInvalidDecl(true);
6777       }
6778     }
6779 
6780     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6781                                                 Context, Label, 0));
6782   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6783     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6784       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6785     if (I != ExtnameUndeclaredIdentifiers.end()) {
6786       if (isDeclExternC(NewVD)) {
6787         NewVD->addAttr(I->second);
6788         ExtnameUndeclaredIdentifiers.erase(I);
6789       } else
6790         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6791             << /*Variable*/1 << NewVD;
6792     }
6793   }
6794 
6795   // Find the shadowed declaration before filtering for scope.
6796   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6797                                 ? getShadowedDeclaration(NewVD, Previous)
6798                                 : nullptr;
6799 
6800   // Don't consider existing declarations that are in a different
6801   // scope and are out-of-semantic-context declarations (if the new
6802   // declaration has linkage).
6803   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6804                        D.getCXXScopeSpec().isNotEmpty() ||
6805                        IsMemberSpecialization ||
6806                        IsVariableTemplateSpecialization);
6807 
6808   // Check whether the previous declaration is in the same block scope. This
6809   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6810   if (getLangOpts().CPlusPlus &&
6811       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6812     NewVD->setPreviousDeclInSameBlockScope(
6813         Previous.isSingleResult() && !Previous.isShadowed() &&
6814         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6815 
6816   if (!getLangOpts().CPlusPlus) {
6817     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6818   } else {
6819     // If this is an explicit specialization of a static data member, check it.
6820     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6821         CheckMemberSpecialization(NewVD, Previous))
6822       NewVD->setInvalidDecl();
6823 
6824     // Merge the decl with the existing one if appropriate.
6825     if (!Previous.empty()) {
6826       if (Previous.isSingleResult() &&
6827           isa<FieldDecl>(Previous.getFoundDecl()) &&
6828           D.getCXXScopeSpec().isSet()) {
6829         // The user tried to define a non-static data member
6830         // out-of-line (C++ [dcl.meaning]p1).
6831         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6832           << D.getCXXScopeSpec().getRange();
6833         Previous.clear();
6834         NewVD->setInvalidDecl();
6835       }
6836     } else if (D.getCXXScopeSpec().isSet()) {
6837       // No previous declaration in the qualifying scope.
6838       Diag(D.getIdentifierLoc(), diag::err_no_member)
6839         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6840         << D.getCXXScopeSpec().getRange();
6841       NewVD->setInvalidDecl();
6842     }
6843 
6844     if (!IsVariableTemplateSpecialization)
6845       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6846 
6847     if (NewTemplate) {
6848       VarTemplateDecl *PrevVarTemplate =
6849           NewVD->getPreviousDecl()
6850               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6851               : nullptr;
6852 
6853       // Check the template parameter list of this declaration, possibly
6854       // merging in the template parameter list from the previous variable
6855       // template declaration.
6856       if (CheckTemplateParameterList(
6857               TemplateParams,
6858               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6859                               : nullptr,
6860               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6861                DC->isDependentContext())
6862                   ? TPC_ClassTemplateMember
6863                   : TPC_VarTemplate))
6864         NewVD->setInvalidDecl();
6865 
6866       // If we are providing an explicit specialization of a static variable
6867       // template, make a note of that.
6868       if (PrevVarTemplate &&
6869           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6870         PrevVarTemplate->setMemberSpecialization();
6871     }
6872   }
6873 
6874   // Diagnose shadowed variables iff this isn't a redeclaration.
6875   if (ShadowedDecl && !D.isRedeclaration())
6876     CheckShadow(NewVD, ShadowedDecl, Previous);
6877 
6878   ProcessPragmaWeak(S, NewVD);
6879 
6880   // If this is the first declaration of an extern C variable, update
6881   // the map of such variables.
6882   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6883       isIncompleteDeclExternC(*this, NewVD))
6884     RegisterLocallyScopedExternCDecl(NewVD, S);
6885 
6886   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6887     Decl *ManglingContextDecl;
6888     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6889             NewVD->getDeclContext(), ManglingContextDecl)) {
6890       Context.setManglingNumber(
6891           NewVD, MCtx->getManglingNumber(
6892                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6893       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6894     }
6895   }
6896 
6897   // Special handling of variable named 'main'.
6898   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6899       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6900       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6901 
6902     // C++ [basic.start.main]p3
6903     // A program that declares a variable main at global scope is ill-formed.
6904     if (getLangOpts().CPlusPlus)
6905       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6906 
6907     // In C, and external-linkage variable named main results in undefined
6908     // behavior.
6909     else if (NewVD->hasExternalFormalLinkage())
6910       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6911   }
6912 
6913   if (D.isRedeclaration() && !Previous.empty()) {
6914     NamedDecl *Prev = Previous.getRepresentativeDecl();
6915     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6916                                    D.isFunctionDefinition());
6917   }
6918 
6919   if (NewTemplate) {
6920     if (NewVD->isInvalidDecl())
6921       NewTemplate->setInvalidDecl();
6922     ActOnDocumentableDecl(NewTemplate);
6923     return NewTemplate;
6924   }
6925 
6926   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6927     CompleteMemberSpecialization(NewVD, Previous);
6928 
6929   return NewVD;
6930 }
6931 
6932 /// Enum describing the %select options in diag::warn_decl_shadow.
6933 enum ShadowedDeclKind {
6934   SDK_Local,
6935   SDK_Global,
6936   SDK_StaticMember,
6937   SDK_Field,
6938   SDK_Typedef,
6939   SDK_Using
6940 };
6941 
6942 /// Determine what kind of declaration we're shadowing.
6943 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6944                                                 const DeclContext *OldDC) {
6945   if (isa<TypeAliasDecl>(ShadowedDecl))
6946     return SDK_Using;
6947   else if (isa<TypedefDecl>(ShadowedDecl))
6948     return SDK_Typedef;
6949   else if (isa<RecordDecl>(OldDC))
6950     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6951 
6952   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6953 }
6954 
6955 /// Return the location of the capture if the given lambda captures the given
6956 /// variable \p VD, or an invalid source location otherwise.
6957 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6958                                          const VarDecl *VD) {
6959   for (const Capture &Capture : LSI->Captures) {
6960     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6961       return Capture.getLocation();
6962   }
6963   return SourceLocation();
6964 }
6965 
6966 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6967                                      const LookupResult &R) {
6968   // Only diagnose if we're shadowing an unambiguous field or variable.
6969   if (R.getResultKind() != LookupResult::Found)
6970     return false;
6971 
6972   // Return false if warning is ignored.
6973   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6974 }
6975 
6976 /// Return the declaration shadowed by the given variable \p D, or null
6977 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6978 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6979                                         const LookupResult &R) {
6980   if (!shouldWarnIfShadowedDecl(Diags, R))
6981     return nullptr;
6982 
6983   // Don't diagnose declarations at file scope.
6984   if (D->hasGlobalStorage())
6985     return nullptr;
6986 
6987   NamedDecl *ShadowedDecl = R.getFoundDecl();
6988   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6989              ? ShadowedDecl
6990              : nullptr;
6991 }
6992 
6993 /// Return the declaration shadowed by the given typedef \p D, or null
6994 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6995 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6996                                         const LookupResult &R) {
6997   // Don't warn if typedef declaration is part of a class
6998   if (D->getDeclContext()->isRecord())
6999     return nullptr;
7000 
7001   if (!shouldWarnIfShadowedDecl(Diags, R))
7002     return nullptr;
7003 
7004   NamedDecl *ShadowedDecl = R.getFoundDecl();
7005   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7006 }
7007 
7008 /// Diagnose variable or built-in function shadowing.  Implements
7009 /// -Wshadow.
7010 ///
7011 /// This method is called whenever a VarDecl is added to a "useful"
7012 /// scope.
7013 ///
7014 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7015 /// \param R the lookup of the name
7016 ///
7017 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7018                        const LookupResult &R) {
7019   DeclContext *NewDC = D->getDeclContext();
7020 
7021   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7022     // Fields are not shadowed by variables in C++ static methods.
7023     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7024       if (MD->isStatic())
7025         return;
7026 
7027     // Fields shadowed by constructor parameters are a special case. Usually
7028     // the constructor initializes the field with the parameter.
7029     if (isa<CXXConstructorDecl>(NewDC))
7030       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7031         // Remember that this was shadowed so we can either warn about its
7032         // modification or its existence depending on warning settings.
7033         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7034         return;
7035       }
7036   }
7037 
7038   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7039     if (shadowedVar->isExternC()) {
7040       // For shadowing external vars, make sure that we point to the global
7041       // declaration, not a locally scoped extern declaration.
7042       for (auto I : shadowedVar->redecls())
7043         if (I->isFileVarDecl()) {
7044           ShadowedDecl = I;
7045           break;
7046         }
7047     }
7048 
7049   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7050 
7051   unsigned WarningDiag = diag::warn_decl_shadow;
7052   SourceLocation CaptureLoc;
7053   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7054       isa<CXXMethodDecl>(NewDC)) {
7055     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7056       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7057         if (RD->getLambdaCaptureDefault() == LCD_None) {
7058           // Try to avoid warnings for lambdas with an explicit capture list.
7059           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7060           // Warn only when the lambda captures the shadowed decl explicitly.
7061           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7062           if (CaptureLoc.isInvalid())
7063             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7064         } else {
7065           // Remember that this was shadowed so we can avoid the warning if the
7066           // shadowed decl isn't captured and the warning settings allow it.
7067           cast<LambdaScopeInfo>(getCurFunction())
7068               ->ShadowingDecls.push_back(
7069                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7070           return;
7071         }
7072       }
7073 
7074       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7075         // A variable can't shadow a local variable in an enclosing scope, if
7076         // they are separated by a non-capturing declaration context.
7077         for (DeclContext *ParentDC = NewDC;
7078              ParentDC && !ParentDC->Equals(OldDC);
7079              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7080           // Only block literals, captured statements, and lambda expressions
7081           // can capture; other scopes don't.
7082           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7083               !isLambdaCallOperator(ParentDC)) {
7084             return;
7085           }
7086         }
7087       }
7088     }
7089   }
7090 
7091   // Only warn about certain kinds of shadowing for class members.
7092   if (NewDC && NewDC->isRecord()) {
7093     // In particular, don't warn about shadowing non-class members.
7094     if (!OldDC->isRecord())
7095       return;
7096 
7097     // TODO: should we warn about static data members shadowing
7098     // static data members from base classes?
7099 
7100     // TODO: don't diagnose for inaccessible shadowed members.
7101     // This is hard to do perfectly because we might friend the
7102     // shadowing context, but that's just a false negative.
7103   }
7104 
7105 
7106   DeclarationName Name = R.getLookupName();
7107 
7108   // Emit warning and note.
7109   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7110     return;
7111   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7112   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7113   if (!CaptureLoc.isInvalid())
7114     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7115         << Name << /*explicitly*/ 1;
7116   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7117 }
7118 
7119 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7120 /// when these variables are captured by the lambda.
7121 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7122   for (const auto &Shadow : LSI->ShadowingDecls) {
7123     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7124     // Try to avoid the warning when the shadowed decl isn't captured.
7125     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7126     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7127     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7128                                        ? diag::warn_decl_shadow_uncaptured_local
7129                                        : diag::warn_decl_shadow)
7130         << Shadow.VD->getDeclName()
7131         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7132     if (!CaptureLoc.isInvalid())
7133       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7134           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7135     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7136   }
7137 }
7138 
7139 /// Check -Wshadow without the advantage of a previous lookup.
7140 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7141   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7142     return;
7143 
7144   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7145                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7146   LookupName(R, S);
7147   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7148     CheckShadow(D, ShadowedDecl, R);
7149 }
7150 
7151 /// Check if 'E', which is an expression that is about to be modified, refers
7152 /// to a constructor parameter that shadows a field.
7153 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7154   // Quickly ignore expressions that can't be shadowing ctor parameters.
7155   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7156     return;
7157   E = E->IgnoreParenImpCasts();
7158   auto *DRE = dyn_cast<DeclRefExpr>(E);
7159   if (!DRE)
7160     return;
7161   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7162   auto I = ShadowingDecls.find(D);
7163   if (I == ShadowingDecls.end())
7164     return;
7165   const NamedDecl *ShadowedDecl = I->second;
7166   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7167   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7168   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7169   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7170 
7171   // Avoid issuing multiple warnings about the same decl.
7172   ShadowingDecls.erase(I);
7173 }
7174 
7175 /// Check for conflict between this global or extern "C" declaration and
7176 /// previous global or extern "C" declarations. This is only used in C++.
7177 template<typename T>
7178 static bool checkGlobalOrExternCConflict(
7179     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7180   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7181   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7182 
7183   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7184     // The common case: this global doesn't conflict with any extern "C"
7185     // declaration.
7186     return false;
7187   }
7188 
7189   if (Prev) {
7190     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7191       // Both the old and new declarations have C language linkage. This is a
7192       // redeclaration.
7193       Previous.clear();
7194       Previous.addDecl(Prev);
7195       return true;
7196     }
7197 
7198     // This is a global, non-extern "C" declaration, and there is a previous
7199     // non-global extern "C" declaration. Diagnose if this is a variable
7200     // declaration.
7201     if (!isa<VarDecl>(ND))
7202       return false;
7203   } else {
7204     // The declaration is extern "C". Check for any declaration in the
7205     // translation unit which might conflict.
7206     if (IsGlobal) {
7207       // We have already performed the lookup into the translation unit.
7208       IsGlobal = false;
7209       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7210            I != E; ++I) {
7211         if (isa<VarDecl>(*I)) {
7212           Prev = *I;
7213           break;
7214         }
7215       }
7216     } else {
7217       DeclContext::lookup_result R =
7218           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7219       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7220            I != E; ++I) {
7221         if (isa<VarDecl>(*I)) {
7222           Prev = *I;
7223           break;
7224         }
7225         // FIXME: If we have any other entity with this name in global scope,
7226         // the declaration is ill-formed, but that is a defect: it breaks the
7227         // 'stat' hack, for instance. Only variables can have mangled name
7228         // clashes with extern "C" declarations, so only they deserve a
7229         // diagnostic.
7230       }
7231     }
7232 
7233     if (!Prev)
7234       return false;
7235   }
7236 
7237   // Use the first declaration's location to ensure we point at something which
7238   // is lexically inside an extern "C" linkage-spec.
7239   assert(Prev && "should have found a previous declaration to diagnose");
7240   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7241     Prev = FD->getFirstDecl();
7242   else
7243     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7244 
7245   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7246     << IsGlobal << ND;
7247   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7248     << IsGlobal;
7249   return false;
7250 }
7251 
7252 /// Apply special rules for handling extern "C" declarations. Returns \c true
7253 /// if we have found that this is a redeclaration of some prior entity.
7254 ///
7255 /// Per C++ [dcl.link]p6:
7256 ///   Two declarations [for a function or variable] with C language linkage
7257 ///   with the same name that appear in different scopes refer to the same
7258 ///   [entity]. An entity with C language linkage shall not be declared with
7259 ///   the same name as an entity in global scope.
7260 template<typename T>
7261 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7262                                                   LookupResult &Previous) {
7263   if (!S.getLangOpts().CPlusPlus) {
7264     // In C, when declaring a global variable, look for a corresponding 'extern'
7265     // variable declared in function scope. We don't need this in C++, because
7266     // we find local extern decls in the surrounding file-scope DeclContext.
7267     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7268       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7269         Previous.clear();
7270         Previous.addDecl(Prev);
7271         return true;
7272       }
7273     }
7274     return false;
7275   }
7276 
7277   // A declaration in the translation unit can conflict with an extern "C"
7278   // declaration.
7279   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7280     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7281 
7282   // An extern "C" declaration can conflict with a declaration in the
7283   // translation unit or can be a redeclaration of an extern "C" declaration
7284   // in another scope.
7285   if (isIncompleteDeclExternC(S,ND))
7286     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7287 
7288   // Neither global nor extern "C": nothing to do.
7289   return false;
7290 }
7291 
7292 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7293   // If the decl is already known invalid, don't check it.
7294   if (NewVD->isInvalidDecl())
7295     return;
7296 
7297   QualType T = NewVD->getType();
7298 
7299   // Defer checking an 'auto' type until its initializer is attached.
7300   if (T->isUndeducedType())
7301     return;
7302 
7303   if (NewVD->hasAttrs())
7304     CheckAlignasUnderalignment(NewVD);
7305 
7306   if (T->isObjCObjectType()) {
7307     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7308       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7309     T = Context.getObjCObjectPointerType(T);
7310     NewVD->setType(T);
7311   }
7312 
7313   // Emit an error if an address space was applied to decl with local storage.
7314   // This includes arrays of objects with address space qualifiers, but not
7315   // automatic variables that point to other address spaces.
7316   // ISO/IEC TR 18037 S5.1.2
7317   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7318       T.getAddressSpace() != LangAS::Default) {
7319     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7320     NewVD->setInvalidDecl();
7321     return;
7322   }
7323 
7324   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7325   // scope.
7326   if (getLangOpts().OpenCLVersion == 120 &&
7327       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7328       NewVD->isStaticLocal()) {
7329     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7330     NewVD->setInvalidDecl();
7331     return;
7332   }
7333 
7334   if (getLangOpts().OpenCL) {
7335     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7336     if (NewVD->hasAttr<BlocksAttr>()) {
7337       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7338       return;
7339     }
7340 
7341     if (T->isBlockPointerType()) {
7342       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7343       // can't use 'extern' storage class.
7344       if (!T.isConstQualified()) {
7345         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7346             << 0 /*const*/;
7347         NewVD->setInvalidDecl();
7348         return;
7349       }
7350       if (NewVD->hasExternalStorage()) {
7351         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7352         NewVD->setInvalidDecl();
7353         return;
7354       }
7355     }
7356     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7357     // __constant address space.
7358     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7359     // variables inside a function can also be declared in the global
7360     // address space.
7361     // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7362     // address space additionally.
7363     // FIXME: Add local AS for OpenCL C++.
7364     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7365         NewVD->hasExternalStorage()) {
7366       if (!T->isSamplerT() &&
7367           !(T.getAddressSpace() == LangAS::opencl_constant ||
7368             (T.getAddressSpace() == LangAS::opencl_global &&
7369              (getLangOpts().OpenCLVersion == 200 ||
7370               getLangOpts().OpenCLCPlusPlus)))) {
7371         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7372         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7373           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7374               << Scope << "global or constant";
7375         else
7376           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7377               << Scope << "constant";
7378         NewVD->setInvalidDecl();
7379         return;
7380       }
7381     } else {
7382       if (T.getAddressSpace() == LangAS::opencl_global) {
7383         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7384             << 1 /*is any function*/ << "global";
7385         NewVD->setInvalidDecl();
7386         return;
7387       }
7388       if (T.getAddressSpace() == LangAS::opencl_constant ||
7389           T.getAddressSpace() == LangAS::opencl_local) {
7390         FunctionDecl *FD = getCurFunctionDecl();
7391         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7392         // in functions.
7393         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7394           if (T.getAddressSpace() == LangAS::opencl_constant)
7395             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7396                 << 0 /*non-kernel only*/ << "constant";
7397           else
7398             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7399                 << 0 /*non-kernel only*/ << "local";
7400           NewVD->setInvalidDecl();
7401           return;
7402         }
7403         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7404         // in the outermost scope of a kernel function.
7405         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7406           if (!getCurScope()->isFunctionScope()) {
7407             if (T.getAddressSpace() == LangAS::opencl_constant)
7408               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7409                   << "constant";
7410             else
7411               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7412                   << "local";
7413             NewVD->setInvalidDecl();
7414             return;
7415           }
7416         }
7417       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7418         // Do not allow other address spaces on automatic variable.
7419         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7420         NewVD->setInvalidDecl();
7421         return;
7422       }
7423     }
7424   }
7425 
7426   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7427       && !NewVD->hasAttr<BlocksAttr>()) {
7428     if (getLangOpts().getGC() != LangOptions::NonGC)
7429       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7430     else {
7431       assert(!getLangOpts().ObjCAutoRefCount);
7432       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7433     }
7434   }
7435 
7436   bool isVM = T->isVariablyModifiedType();
7437   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7438       NewVD->hasAttr<BlocksAttr>())
7439     setFunctionHasBranchProtectedScope();
7440 
7441   if ((isVM && NewVD->hasLinkage()) ||
7442       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7443     bool SizeIsNegative;
7444     llvm::APSInt Oversized;
7445     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7446         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7447     QualType FixedT;
7448     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7449       FixedT = FixedTInfo->getType();
7450     else if (FixedTInfo) {
7451       // Type and type-as-written are canonically different. We need to fix up
7452       // both types separately.
7453       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7454                                                    Oversized);
7455     }
7456     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7457       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7458       // FIXME: This won't give the correct result for
7459       // int a[10][n];
7460       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7461 
7462       if (NewVD->isFileVarDecl())
7463         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7464         << SizeRange;
7465       else if (NewVD->isStaticLocal())
7466         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7467         << SizeRange;
7468       else
7469         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7470         << SizeRange;
7471       NewVD->setInvalidDecl();
7472       return;
7473     }
7474 
7475     if (!FixedTInfo) {
7476       if (NewVD->isFileVarDecl())
7477         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7478       else
7479         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7480       NewVD->setInvalidDecl();
7481       return;
7482     }
7483 
7484     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7485     NewVD->setType(FixedT);
7486     NewVD->setTypeSourceInfo(FixedTInfo);
7487   }
7488 
7489   if (T->isVoidType()) {
7490     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7491     //                    of objects and functions.
7492     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7493       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7494         << T;
7495       NewVD->setInvalidDecl();
7496       return;
7497     }
7498   }
7499 
7500   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7501     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7502     NewVD->setInvalidDecl();
7503     return;
7504   }
7505 
7506   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7507     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7508     NewVD->setInvalidDecl();
7509     return;
7510   }
7511 
7512   if (NewVD->isConstexpr() && !T->isDependentType() &&
7513       RequireLiteralType(NewVD->getLocation(), T,
7514                          diag::err_constexpr_var_non_literal)) {
7515     NewVD->setInvalidDecl();
7516     return;
7517   }
7518 }
7519 
7520 /// Perform semantic checking on a newly-created variable
7521 /// declaration.
7522 ///
7523 /// This routine performs all of the type-checking required for a
7524 /// variable declaration once it has been built. It is used both to
7525 /// check variables after they have been parsed and their declarators
7526 /// have been translated into a declaration, and to check variables
7527 /// that have been instantiated from a template.
7528 ///
7529 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7530 ///
7531 /// Returns true if the variable declaration is a redeclaration.
7532 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7533   CheckVariableDeclarationType(NewVD);
7534 
7535   // If the decl is already known invalid, don't check it.
7536   if (NewVD->isInvalidDecl())
7537     return false;
7538 
7539   // If we did not find anything by this name, look for a non-visible
7540   // extern "C" declaration with the same name.
7541   if (Previous.empty() &&
7542       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7543     Previous.setShadowed();
7544 
7545   if (!Previous.empty()) {
7546     MergeVarDecl(NewVD, Previous);
7547     return true;
7548   }
7549   return false;
7550 }
7551 
7552 namespace {
7553 struct FindOverriddenMethod {
7554   Sema *S;
7555   CXXMethodDecl *Method;
7556 
7557   /// Member lookup function that determines whether a given C++
7558   /// method overrides a method in a base class, to be used with
7559   /// CXXRecordDecl::lookupInBases().
7560   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7561     RecordDecl *BaseRecord =
7562         Specifier->getType()->getAs<RecordType>()->getDecl();
7563 
7564     DeclarationName Name = Method->getDeclName();
7565 
7566     // FIXME: Do we care about other names here too?
7567     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7568       // We really want to find the base class destructor here.
7569       QualType T = S->Context.getTypeDeclType(BaseRecord);
7570       CanQualType CT = S->Context.getCanonicalType(T);
7571 
7572       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7573     }
7574 
7575     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7576          Path.Decls = Path.Decls.slice(1)) {
7577       NamedDecl *D = Path.Decls.front();
7578       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7579         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7580           return true;
7581       }
7582     }
7583 
7584     return false;
7585   }
7586 };
7587 
7588 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7589 } // end anonymous namespace
7590 
7591 /// Report an error regarding overriding, along with any relevant
7592 /// overridden methods.
7593 ///
7594 /// \param DiagID the primary error to report.
7595 /// \param MD the overriding method.
7596 /// \param OEK which overrides to include as notes.
7597 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7598                             OverrideErrorKind OEK = OEK_All) {
7599   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7600   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7601     // This check (& the OEK parameter) could be replaced by a predicate, but
7602     // without lambdas that would be overkill. This is still nicer than writing
7603     // out the diag loop 3 times.
7604     if ((OEK == OEK_All) ||
7605         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7606         (OEK == OEK_Deleted && O->isDeleted()))
7607       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7608   }
7609 }
7610 
7611 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7612 /// and if so, check that it's a valid override and remember it.
7613 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7614   // Look for methods in base classes that this method might override.
7615   CXXBasePaths Paths;
7616   FindOverriddenMethod FOM;
7617   FOM.Method = MD;
7618   FOM.S = this;
7619   bool hasDeletedOverridenMethods = false;
7620   bool hasNonDeletedOverridenMethods = false;
7621   bool AddedAny = false;
7622   if (DC->lookupInBases(FOM, Paths)) {
7623     for (auto *I : Paths.found_decls()) {
7624       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7625         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7626         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7627             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7628             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7629             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7630           hasDeletedOverridenMethods |= OldMD->isDeleted();
7631           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7632           AddedAny = true;
7633         }
7634       }
7635     }
7636   }
7637 
7638   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7639     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7640   }
7641   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7642     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7643   }
7644 
7645   return AddedAny;
7646 }
7647 
7648 namespace {
7649   // Struct for holding all of the extra arguments needed by
7650   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7651   struct ActOnFDArgs {
7652     Scope *S;
7653     Declarator &D;
7654     MultiTemplateParamsArg TemplateParamLists;
7655     bool AddToScope;
7656   };
7657 } // end anonymous namespace
7658 
7659 namespace {
7660 
7661 // Callback to only accept typo corrections that have a non-zero edit distance.
7662 // Also only accept corrections that have the same parent decl.
7663 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7664  public:
7665   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7666                             CXXRecordDecl *Parent)
7667       : Context(Context), OriginalFD(TypoFD),
7668         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7669 
7670   bool ValidateCandidate(const TypoCorrection &candidate) override {
7671     if (candidate.getEditDistance() == 0)
7672       return false;
7673 
7674     SmallVector<unsigned, 1> MismatchedParams;
7675     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7676                                           CDeclEnd = candidate.end();
7677          CDecl != CDeclEnd; ++CDecl) {
7678       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7679 
7680       if (FD && !FD->hasBody() &&
7681           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7682         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7683           CXXRecordDecl *Parent = MD->getParent();
7684           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7685             return true;
7686         } else if (!ExpectedParent) {
7687           return true;
7688         }
7689       }
7690     }
7691 
7692     return false;
7693   }
7694 
7695  private:
7696   ASTContext &Context;
7697   FunctionDecl *OriginalFD;
7698   CXXRecordDecl *ExpectedParent;
7699 };
7700 
7701 } // end anonymous namespace
7702 
7703 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7704   TypoCorrectedFunctionDefinitions.insert(F);
7705 }
7706 
7707 /// Generate diagnostics for an invalid function redeclaration.
7708 ///
7709 /// This routine handles generating the diagnostic messages for an invalid
7710 /// function redeclaration, including finding possible similar declarations
7711 /// or performing typo correction if there are no previous declarations with
7712 /// the same name.
7713 ///
7714 /// Returns a NamedDecl iff typo correction was performed and substituting in
7715 /// the new declaration name does not cause new errors.
7716 static NamedDecl *DiagnoseInvalidRedeclaration(
7717     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7718     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7719   DeclarationName Name = NewFD->getDeclName();
7720   DeclContext *NewDC = NewFD->getDeclContext();
7721   SmallVector<unsigned, 1> MismatchedParams;
7722   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7723   TypoCorrection Correction;
7724   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7725   unsigned DiagMsg =
7726     IsLocalFriend ? diag::err_no_matching_local_friend :
7727     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
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 destructor needs an implicit exception specification, set it
7960       // now. FIXME: It'd be nice to be able to create the right type to start
7961       // with, but the type needs to reference the destructor declaration.
7962       if (SemaRef.getLangOpts().CPlusPlus11)
7963         SemaRef.AdjustDestructorExceptionSpec(NewDD);
7964 
7965       IsVirtualOkay = true;
7966       return NewDD;
7967 
7968     } else {
7969       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7970       D.setInvalidType();
7971 
7972       // Create a FunctionDecl to satisfy the function definition parsing
7973       // code path.
7974       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7975                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
7976                                   isInline,
7977                                   /*hasPrototype=*/true, isConstexpr);
7978     }
7979 
7980   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7981     if (!DC->isRecord()) {
7982       SemaRef.Diag(D.getIdentifierLoc(),
7983            diag::err_conv_function_not_member);
7984       return nullptr;
7985     }
7986 
7987     SemaRef.CheckConversionDeclarator(D, R, SC);
7988     IsVirtualOkay = true;
7989     return CXXConversionDecl::Create(
7990         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7991         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
7992 
7993   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7994     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7995 
7996     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7997                                          isExplicit, NameInfo, R, TInfo,
7998                                          D.getEndLoc());
7999   } else if (DC->isRecord()) {
8000     // If the name of the function is the same as the name of the record,
8001     // then this must be an invalid constructor that has a return type.
8002     // (The parser checks for a return type and makes the declarator a
8003     // constructor if it has no return type).
8004     if (Name.getAsIdentifierInfo() &&
8005         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8006       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8007         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8008         << SourceRange(D.getIdentifierLoc());
8009       return nullptr;
8010     }
8011 
8012     // This is a C++ method declaration.
8013     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8014         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8015         TInfo, SC, isInline, isConstexpr, SourceLocation());
8016     IsVirtualOkay = !Ret->isStatic();
8017     return Ret;
8018   } else {
8019     bool isFriend =
8020         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8021     if (!isFriend && SemaRef.CurContext->isRecord())
8022       return nullptr;
8023 
8024     // Determine whether the function was written with a
8025     // prototype. This true when:
8026     //   - we're in C++ (where every function has a prototype),
8027     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8028                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8029                                 isConstexpr);
8030   }
8031 }
8032 
8033 enum OpenCLParamType {
8034   ValidKernelParam,
8035   PtrPtrKernelParam,
8036   PtrKernelParam,
8037   InvalidAddrSpacePtrKernelParam,
8038   InvalidKernelParam,
8039   RecordKernelParam
8040 };
8041 
8042 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8043   // Size dependent types are just typedefs to normal integer types
8044   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8045   // integers other than by their names.
8046   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8047 
8048   // Remove typedefs one by one until we reach a typedef
8049   // for a size dependent type.
8050   QualType DesugaredTy = Ty;
8051   do {
8052     ArrayRef<StringRef> Names(SizeTypeNames);
8053     auto Match =
8054         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8055     if (Names.end() != Match)
8056       return true;
8057 
8058     Ty = DesugaredTy;
8059     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8060   } while (DesugaredTy != Ty);
8061 
8062   return false;
8063 }
8064 
8065 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8066   if (PT->isPointerType()) {
8067     QualType PointeeType = PT->getPointeeType();
8068     if (PointeeType->isPointerType())
8069       return PtrPtrKernelParam;
8070     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8071         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8072         PointeeType.getAddressSpace() == LangAS::Default)
8073       return InvalidAddrSpacePtrKernelParam;
8074     return PtrKernelParam;
8075   }
8076 
8077   // OpenCL v1.2 s6.9.k:
8078   // Arguments to kernel functions in a program cannot be declared with the
8079   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8080   // uintptr_t or a struct and/or union that contain fields declared to be one
8081   // of these built-in scalar types.
8082   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8083     return InvalidKernelParam;
8084 
8085   if (PT->isImageType())
8086     return PtrKernelParam;
8087 
8088   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8089     return InvalidKernelParam;
8090 
8091   // OpenCL extension spec v1.2 s9.5:
8092   // This extension adds support for half scalar and vector types as built-in
8093   // types that can be used for arithmetic operations, conversions etc.
8094   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8095     return InvalidKernelParam;
8096 
8097   if (PT->isRecordType())
8098     return RecordKernelParam;
8099 
8100   // Look into an array argument to check if it has a forbidden type.
8101   if (PT->isArrayType()) {
8102     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8103     // Call ourself to check an underlying type of an array. Since the
8104     // getPointeeOrArrayElementType returns an innermost type which is not an
8105     // array, this recursive call only happens once.
8106     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8107   }
8108 
8109   return ValidKernelParam;
8110 }
8111 
8112 static void checkIsValidOpenCLKernelParameter(
8113   Sema &S,
8114   Declarator &D,
8115   ParmVarDecl *Param,
8116   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8117   QualType PT = Param->getType();
8118 
8119   // Cache the valid types we encounter to avoid rechecking structs that are
8120   // used again
8121   if (ValidTypes.count(PT.getTypePtr()))
8122     return;
8123 
8124   switch (getOpenCLKernelParameterType(S, PT)) {
8125   case PtrPtrKernelParam:
8126     // OpenCL v1.2 s6.9.a:
8127     // A kernel function argument cannot be declared as a
8128     // pointer to a pointer type.
8129     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8130     D.setInvalidType();
8131     return;
8132 
8133   case InvalidAddrSpacePtrKernelParam:
8134     // OpenCL v1.0 s6.5:
8135     // __kernel function arguments declared to be a pointer of a type can point
8136     // to one of the following address spaces only : __global, __local or
8137     // __constant.
8138     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8139     D.setInvalidType();
8140     return;
8141 
8142     // OpenCL v1.2 s6.9.k:
8143     // Arguments to kernel functions in a program cannot be declared with the
8144     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8145     // uintptr_t or a struct and/or union that contain fields declared to be
8146     // one of these built-in scalar types.
8147 
8148   case InvalidKernelParam:
8149     // OpenCL v1.2 s6.8 n:
8150     // A kernel function argument cannot be declared
8151     // of event_t type.
8152     // Do not diagnose half type since it is diagnosed as invalid argument
8153     // type for any function elsewhere.
8154     if (!PT->isHalfType()) {
8155       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8156 
8157       // Explain what typedefs are involved.
8158       const TypedefType *Typedef = nullptr;
8159       while ((Typedef = PT->getAs<TypedefType>())) {
8160         SourceLocation Loc = Typedef->getDecl()->getLocation();
8161         // SourceLocation may be invalid for a built-in type.
8162         if (Loc.isValid())
8163           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8164         PT = Typedef->desugar();
8165       }
8166     }
8167 
8168     D.setInvalidType();
8169     return;
8170 
8171   case PtrKernelParam:
8172   case ValidKernelParam:
8173     ValidTypes.insert(PT.getTypePtr());
8174     return;
8175 
8176   case RecordKernelParam:
8177     break;
8178   }
8179 
8180   // Track nested structs we will inspect
8181   SmallVector<const Decl *, 4> VisitStack;
8182 
8183   // Track where we are in the nested structs. Items will migrate from
8184   // VisitStack to HistoryStack as we do the DFS for bad field.
8185   SmallVector<const FieldDecl *, 4> HistoryStack;
8186   HistoryStack.push_back(nullptr);
8187 
8188   // At this point we already handled everything except of a RecordType or
8189   // an ArrayType of a RecordType.
8190   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8191   const RecordType *RecTy =
8192       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8193   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8194 
8195   VisitStack.push_back(RecTy->getDecl());
8196   assert(VisitStack.back() && "First decl null?");
8197 
8198   do {
8199     const Decl *Next = VisitStack.pop_back_val();
8200     if (!Next) {
8201       assert(!HistoryStack.empty());
8202       // Found a marker, we have gone up a level
8203       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8204         ValidTypes.insert(Hist->getType().getTypePtr());
8205 
8206       continue;
8207     }
8208 
8209     // Adds everything except the original parameter declaration (which is not a
8210     // field itself) to the history stack.
8211     const RecordDecl *RD;
8212     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8213       HistoryStack.push_back(Field);
8214 
8215       QualType FieldTy = Field->getType();
8216       // Other field types (known to be valid or invalid) are handled while we
8217       // walk around RecordDecl::fields().
8218       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8219              "Unexpected type.");
8220       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8221 
8222       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8223     } else {
8224       RD = cast<RecordDecl>(Next);
8225     }
8226 
8227     // Add a null marker so we know when we've gone back up a level
8228     VisitStack.push_back(nullptr);
8229 
8230     for (const auto *FD : RD->fields()) {
8231       QualType QT = FD->getType();
8232 
8233       if (ValidTypes.count(QT.getTypePtr()))
8234         continue;
8235 
8236       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8237       if (ParamType == ValidKernelParam)
8238         continue;
8239 
8240       if (ParamType == RecordKernelParam) {
8241         VisitStack.push_back(FD);
8242         continue;
8243       }
8244 
8245       // OpenCL v1.2 s6.9.p:
8246       // Arguments to kernel functions that are declared to be a struct or union
8247       // do not allow OpenCL objects to be passed as elements of the struct or
8248       // union.
8249       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8250           ParamType == InvalidAddrSpacePtrKernelParam) {
8251         S.Diag(Param->getLocation(),
8252                diag::err_record_with_pointers_kernel_param)
8253           << PT->isUnionType()
8254           << PT;
8255       } else {
8256         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8257       }
8258 
8259       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8260           << OrigRecDecl->getDeclName();
8261 
8262       // We have an error, now let's go back up through history and show where
8263       // the offending field came from
8264       for (ArrayRef<const FieldDecl *>::const_iterator
8265                I = HistoryStack.begin() + 1,
8266                E = HistoryStack.end();
8267            I != E; ++I) {
8268         const FieldDecl *OuterField = *I;
8269         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8270           << OuterField->getType();
8271       }
8272 
8273       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8274         << QT->isPointerType()
8275         << QT;
8276       D.setInvalidType();
8277       return;
8278     }
8279   } while (!VisitStack.empty());
8280 }
8281 
8282 /// Find the DeclContext in which a tag is implicitly declared if we see an
8283 /// elaborated type specifier in the specified context, and lookup finds
8284 /// nothing.
8285 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8286   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8287     DC = DC->getParent();
8288   return DC;
8289 }
8290 
8291 /// Find the Scope in which a tag is implicitly declared if we see an
8292 /// elaborated type specifier in the specified context, and lookup finds
8293 /// nothing.
8294 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8295   while (S->isClassScope() ||
8296          (LangOpts.CPlusPlus &&
8297           S->isFunctionPrototypeScope()) ||
8298          ((S->getFlags() & Scope::DeclScope) == 0) ||
8299          (S->getEntity() && S->getEntity()->isTransparentContext()))
8300     S = S->getParent();
8301   return S;
8302 }
8303 
8304 NamedDecl*
8305 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8306                               TypeSourceInfo *TInfo, LookupResult &Previous,
8307                               MultiTemplateParamsArg TemplateParamLists,
8308                               bool &AddToScope) {
8309   QualType R = TInfo->getType();
8310 
8311   assert(R->isFunctionType());
8312 
8313   // TODO: consider using NameInfo for diagnostic.
8314   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8315   DeclarationName Name = NameInfo.getName();
8316   StorageClass SC = getFunctionStorageClass(*this, D);
8317 
8318   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8319     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8320          diag::err_invalid_thread)
8321       << DeclSpec::getSpecifierName(TSCS);
8322 
8323   if (D.isFirstDeclarationOfMember())
8324     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8325                            D.getIdentifierLoc());
8326 
8327   bool isFriend = false;
8328   FunctionTemplateDecl *FunctionTemplate = nullptr;
8329   bool isMemberSpecialization = false;
8330   bool isFunctionTemplateSpecialization = false;
8331 
8332   bool isDependentClassScopeExplicitSpecialization = false;
8333   bool HasExplicitTemplateArgs = false;
8334   TemplateArgumentListInfo TemplateArgs;
8335 
8336   bool isVirtualOkay = false;
8337 
8338   DeclContext *OriginalDC = DC;
8339   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8340 
8341   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8342                                               isVirtualOkay);
8343   if (!NewFD) return nullptr;
8344 
8345   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8346     NewFD->setTopLevelDeclInObjCContainer();
8347 
8348   // Set the lexical context. If this is a function-scope declaration, or has a
8349   // C++ scope specifier, or is the object of a friend declaration, the lexical
8350   // context will be different from the semantic context.
8351   NewFD->setLexicalDeclContext(CurContext);
8352 
8353   if (IsLocalExternDecl)
8354     NewFD->setLocalExternDecl();
8355 
8356   if (getLangOpts().CPlusPlus) {
8357     bool isInline = D.getDeclSpec().isInlineSpecified();
8358     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8359     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8360     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8361     isFriend = D.getDeclSpec().isFriendSpecified();
8362     if (isFriend && !isInline && D.isFunctionDefinition()) {
8363       // C++ [class.friend]p5
8364       //   A function can be defined in a friend declaration of a
8365       //   class . . . . Such a function is implicitly inline.
8366       NewFD->setImplicitlyInline();
8367     }
8368 
8369     // If this is a method defined in an __interface, and is not a constructor
8370     // or an overloaded operator, then set the pure flag (isVirtual will already
8371     // return true).
8372     if (const CXXRecordDecl *Parent =
8373           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8374       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8375         NewFD->setPure(true);
8376 
8377       // C++ [class.union]p2
8378       //   A union can have member functions, but not virtual functions.
8379       if (isVirtual && Parent->isUnion())
8380         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8381     }
8382 
8383     SetNestedNameSpecifier(*this, NewFD, D);
8384     isMemberSpecialization = false;
8385     isFunctionTemplateSpecialization = false;
8386     if (D.isInvalidType())
8387       NewFD->setInvalidDecl();
8388 
8389     // Match up the template parameter lists with the scope specifier, then
8390     // determine whether we have a template or a template specialization.
8391     bool Invalid = false;
8392     if (TemplateParameterList *TemplateParams =
8393             MatchTemplateParametersToScopeSpecifier(
8394                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8395                 D.getCXXScopeSpec(),
8396                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8397                     ? D.getName().TemplateId
8398                     : nullptr,
8399                 TemplateParamLists, isFriend, isMemberSpecialization,
8400                 Invalid)) {
8401       if (TemplateParams->size() > 0) {
8402         // This is a function template
8403 
8404         // Check that we can declare a template here.
8405         if (CheckTemplateDeclScope(S, TemplateParams))
8406           NewFD->setInvalidDecl();
8407 
8408         // A destructor cannot be a template.
8409         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8410           Diag(NewFD->getLocation(), diag::err_destructor_template);
8411           NewFD->setInvalidDecl();
8412         }
8413 
8414         // If we're adding a template to a dependent context, we may need to
8415         // rebuilding some of the types used within the template parameter list,
8416         // now that we know what the current instantiation is.
8417         if (DC->isDependentContext()) {
8418           ContextRAII SavedContext(*this, DC);
8419           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8420             Invalid = true;
8421         }
8422 
8423         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8424                                                         NewFD->getLocation(),
8425                                                         Name, TemplateParams,
8426                                                         NewFD);
8427         FunctionTemplate->setLexicalDeclContext(CurContext);
8428         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8429 
8430         // For source fidelity, store the other template param lists.
8431         if (TemplateParamLists.size() > 1) {
8432           NewFD->setTemplateParameterListsInfo(Context,
8433                                                TemplateParamLists.drop_back(1));
8434         }
8435       } else {
8436         // This is a function template specialization.
8437         isFunctionTemplateSpecialization = true;
8438         // For source fidelity, store all the template param lists.
8439         if (TemplateParamLists.size() > 0)
8440           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8441 
8442         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8443         if (isFriend) {
8444           // We want to remove the "template<>", found here.
8445           SourceRange RemoveRange = TemplateParams->getSourceRange();
8446 
8447           // If we remove the template<> and the name is not a
8448           // template-id, we're actually silently creating a problem:
8449           // the friend declaration will refer to an untemplated decl,
8450           // and clearly the user wants a template specialization.  So
8451           // we need to insert '<>' after the name.
8452           SourceLocation InsertLoc;
8453           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8454             InsertLoc = D.getName().getSourceRange().getEnd();
8455             InsertLoc = getLocForEndOfToken(InsertLoc);
8456           }
8457 
8458           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8459             << Name << RemoveRange
8460             << FixItHint::CreateRemoval(RemoveRange)
8461             << FixItHint::CreateInsertion(InsertLoc, "<>");
8462         }
8463       }
8464     } else {
8465       // All template param lists were matched against the scope specifier:
8466       // this is NOT (an explicit specialization of) a template.
8467       if (TemplateParamLists.size() > 0)
8468         // For source fidelity, store all the template param lists.
8469         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8470     }
8471 
8472     if (Invalid) {
8473       NewFD->setInvalidDecl();
8474       if (FunctionTemplate)
8475         FunctionTemplate->setInvalidDecl();
8476     }
8477 
8478     // C++ [dcl.fct.spec]p5:
8479     //   The virtual specifier shall only be used in declarations of
8480     //   nonstatic class member functions that appear within a
8481     //   member-specification of a class declaration; see 10.3.
8482     //
8483     if (isVirtual && !NewFD->isInvalidDecl()) {
8484       if (!isVirtualOkay) {
8485         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8486              diag::err_virtual_non_function);
8487       } else if (!CurContext->isRecord()) {
8488         // 'virtual' was specified outside of the class.
8489         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8490              diag::err_virtual_out_of_class)
8491           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8492       } else if (NewFD->getDescribedFunctionTemplate()) {
8493         // C++ [temp.mem]p3:
8494         //  A member function template shall not be virtual.
8495         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8496              diag::err_virtual_member_function_template)
8497           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8498       } else {
8499         // Okay: Add virtual to the method.
8500         NewFD->setVirtualAsWritten(true);
8501       }
8502 
8503       if (getLangOpts().CPlusPlus14 &&
8504           NewFD->getReturnType()->isUndeducedType())
8505         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8506     }
8507 
8508     if (getLangOpts().CPlusPlus14 &&
8509         (NewFD->isDependentContext() ||
8510          (isFriend && CurContext->isDependentContext())) &&
8511         NewFD->getReturnType()->isUndeducedType()) {
8512       // If the function template is referenced directly (for instance, as a
8513       // member of the current instantiation), pretend it has a dependent type.
8514       // This is not really justified by the standard, but is the only sane
8515       // thing to do.
8516       // FIXME: For a friend function, we have not marked the function as being
8517       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8518       const FunctionProtoType *FPT =
8519           NewFD->getType()->castAs<FunctionProtoType>();
8520       QualType Result =
8521           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8522       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8523                                              FPT->getExtProtoInfo()));
8524     }
8525 
8526     // C++ [dcl.fct.spec]p3:
8527     //  The inline specifier shall not appear on a block scope function
8528     //  declaration.
8529     if (isInline && !NewFD->isInvalidDecl()) {
8530       if (CurContext->isFunctionOrMethod()) {
8531         // 'inline' is not allowed on block scope function declaration.
8532         Diag(D.getDeclSpec().getInlineSpecLoc(),
8533              diag::err_inline_declaration_block_scope) << Name
8534           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8535       }
8536     }
8537 
8538     // C++ [dcl.fct.spec]p6:
8539     //  The explicit specifier shall be used only in the declaration of a
8540     //  constructor or conversion function within its class definition;
8541     //  see 12.3.1 and 12.3.2.
8542     if (isExplicit && !NewFD->isInvalidDecl() &&
8543         !isa<CXXDeductionGuideDecl>(NewFD)) {
8544       if (!CurContext->isRecord()) {
8545         // 'explicit' was specified outside of the class.
8546         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8547              diag::err_explicit_out_of_class)
8548           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8549       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8550                  !isa<CXXConversionDecl>(NewFD)) {
8551         // 'explicit' was specified on a function that wasn't a constructor
8552         // or conversion function.
8553         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8554              diag::err_explicit_non_ctor_or_conv_function)
8555           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8556       }
8557     }
8558 
8559     if (isConstexpr) {
8560       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8561       // are implicitly inline.
8562       NewFD->setImplicitlyInline();
8563 
8564       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8565       // be either constructors or to return a literal type. Therefore,
8566       // destructors cannot be declared constexpr.
8567       if (isa<CXXDestructorDecl>(NewFD))
8568         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8569     }
8570 
8571     // If __module_private__ was specified, mark the function accordingly.
8572     if (D.getDeclSpec().isModulePrivateSpecified()) {
8573       if (isFunctionTemplateSpecialization) {
8574         SourceLocation ModulePrivateLoc
8575           = D.getDeclSpec().getModulePrivateSpecLoc();
8576         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8577           << 0
8578           << FixItHint::CreateRemoval(ModulePrivateLoc);
8579       } else {
8580         NewFD->setModulePrivate();
8581         if (FunctionTemplate)
8582           FunctionTemplate->setModulePrivate();
8583       }
8584     }
8585 
8586     if (isFriend) {
8587       if (FunctionTemplate) {
8588         FunctionTemplate->setObjectOfFriendDecl();
8589         FunctionTemplate->setAccess(AS_public);
8590       }
8591       NewFD->setObjectOfFriendDecl();
8592       NewFD->setAccess(AS_public);
8593     }
8594 
8595     // If a function is defined as defaulted or deleted, mark it as such now.
8596     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8597     // definition kind to FDK_Definition.
8598     switch (D.getFunctionDefinitionKind()) {
8599       case FDK_Declaration:
8600       case FDK_Definition:
8601         break;
8602 
8603       case FDK_Defaulted:
8604         NewFD->setDefaulted();
8605         break;
8606 
8607       case FDK_Deleted:
8608         NewFD->setDeletedAsWritten();
8609         break;
8610     }
8611 
8612     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8613         D.isFunctionDefinition()) {
8614       // C++ [class.mfct]p2:
8615       //   A member function may be defined (8.4) in its class definition, in
8616       //   which case it is an inline member function (7.1.2)
8617       NewFD->setImplicitlyInline();
8618     }
8619 
8620     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8621         !CurContext->isRecord()) {
8622       // C++ [class.static]p1:
8623       //   A data or function member of a class may be declared static
8624       //   in a class definition, in which case it is a static member of
8625       //   the class.
8626 
8627       // Complain about the 'static' specifier if it's on an out-of-line
8628       // member function definition.
8629 
8630       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8631       // member function template declaration, warn about this.
8632       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8633            NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
8634            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8635         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8636     }
8637 
8638     // C++11 [except.spec]p15:
8639     //   A deallocation function with no exception-specification is treated
8640     //   as if it were specified with noexcept(true).
8641     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8642     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8643          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8644         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8645       NewFD->setType(Context.getFunctionType(
8646           FPT->getReturnType(), FPT->getParamTypes(),
8647           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8648   }
8649 
8650   // Filter out previous declarations that don't match the scope.
8651   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8652                        D.getCXXScopeSpec().isNotEmpty() ||
8653                        isMemberSpecialization ||
8654                        isFunctionTemplateSpecialization);
8655 
8656   // Handle GNU asm-label extension (encoded as an attribute).
8657   if (Expr *E = (Expr*) D.getAsmLabel()) {
8658     // The parser guarantees this is a string.
8659     StringLiteral *SE = cast<StringLiteral>(E);
8660     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8661                                                 SE->getString(), 0));
8662   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8663     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8664       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8665     if (I != ExtnameUndeclaredIdentifiers.end()) {
8666       if (isDeclExternC(NewFD)) {
8667         NewFD->addAttr(I->second);
8668         ExtnameUndeclaredIdentifiers.erase(I);
8669       } else
8670         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8671             << /*Variable*/0 << NewFD;
8672     }
8673   }
8674 
8675   // Copy the parameter declarations from the declarator D to the function
8676   // declaration NewFD, if they are available.  First scavenge them into Params.
8677   SmallVector<ParmVarDecl*, 16> Params;
8678   unsigned FTIIdx;
8679   if (D.isFunctionDeclarator(FTIIdx)) {
8680     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8681 
8682     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8683     // function that takes no arguments, not a function that takes a
8684     // single void argument.
8685     // We let through "const void" here because Sema::GetTypeForDeclarator
8686     // already checks for that case.
8687     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8688       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8689         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8690         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8691         Param->setDeclContext(NewFD);
8692         Params.push_back(Param);
8693 
8694         if (Param->isInvalidDecl())
8695           NewFD->setInvalidDecl();
8696       }
8697     }
8698 
8699     if (!getLangOpts().CPlusPlus) {
8700       // In C, find all the tag declarations from the prototype and move them
8701       // into the function DeclContext. Remove them from the surrounding tag
8702       // injection context of the function, which is typically but not always
8703       // the TU.
8704       DeclContext *PrototypeTagContext =
8705           getTagInjectionContext(NewFD->getLexicalDeclContext());
8706       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8707         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8708 
8709         // We don't want to reparent enumerators. Look at their parent enum
8710         // instead.
8711         if (!TD) {
8712           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8713             TD = cast<EnumDecl>(ECD->getDeclContext());
8714         }
8715         if (!TD)
8716           continue;
8717         DeclContext *TagDC = TD->getLexicalDeclContext();
8718         if (!TagDC->containsDecl(TD))
8719           continue;
8720         TagDC->removeDecl(TD);
8721         TD->setDeclContext(NewFD);
8722         NewFD->addDecl(TD);
8723 
8724         // Preserve the lexical DeclContext if it is not the surrounding tag
8725         // injection context of the FD. In this example, the semantic context of
8726         // E will be f and the lexical context will be S, while both the
8727         // semantic and lexical contexts of S will be f:
8728         //   void f(struct S { enum E { a } f; } s);
8729         if (TagDC != PrototypeTagContext)
8730           TD->setLexicalDeclContext(TagDC);
8731       }
8732     }
8733   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8734     // When we're declaring a function with a typedef, typeof, etc as in the
8735     // following example, we'll need to synthesize (unnamed)
8736     // parameters for use in the declaration.
8737     //
8738     // @code
8739     // typedef void fn(int);
8740     // fn f;
8741     // @endcode
8742 
8743     // Synthesize a parameter for each argument type.
8744     for (const auto &AI : FT->param_types()) {
8745       ParmVarDecl *Param =
8746           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8747       Param->setScopeInfo(0, Params.size());
8748       Params.push_back(Param);
8749     }
8750   } else {
8751     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8752            "Should not need args for typedef of non-prototype fn");
8753   }
8754 
8755   // Finally, we know we have the right number of parameters, install them.
8756   NewFD->setParams(Params);
8757 
8758   if (D.getDeclSpec().isNoreturnSpecified())
8759     NewFD->addAttr(
8760         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8761                                        Context, 0));
8762 
8763   // Functions returning a variably modified type violate C99 6.7.5.2p2
8764   // because all functions have linkage.
8765   if (!NewFD->isInvalidDecl() &&
8766       NewFD->getReturnType()->isVariablyModifiedType()) {
8767     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8768     NewFD->setInvalidDecl();
8769   }
8770 
8771   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8772   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8773       !NewFD->hasAttr<SectionAttr>()) {
8774     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8775                                                  PragmaClangTextSection.SectionName,
8776                                                  PragmaClangTextSection.PragmaLocation));
8777   }
8778 
8779   // Apply an implicit SectionAttr if #pragma code_seg is active.
8780   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8781       !NewFD->hasAttr<SectionAttr>()) {
8782     NewFD->addAttr(
8783         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8784                                     CodeSegStack.CurrentValue->getString(),
8785                                     CodeSegStack.CurrentPragmaLocation));
8786     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8787                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8788                          ASTContext::PSF_Read,
8789                      NewFD))
8790       NewFD->dropAttr<SectionAttr>();
8791   }
8792 
8793   // Apply an implicit CodeSegAttr from class declspec or
8794   // apply an implicit SectionAttr from #pragma code_seg if active.
8795   if (!NewFD->hasAttr<CodeSegAttr>()) {
8796     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8797                                                                  D.isFunctionDefinition())) {
8798       NewFD->addAttr(SAttr);
8799     }
8800   }
8801 
8802   // Handle attributes.
8803   ProcessDeclAttributes(S, NewFD, D);
8804 
8805   if (getLangOpts().OpenCL) {
8806     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8807     // type declaration will generate a compilation error.
8808     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8809     if (AddressSpace != LangAS::Default) {
8810       Diag(NewFD->getLocation(),
8811            diag::err_opencl_return_value_with_address_space);
8812       NewFD->setInvalidDecl();
8813     }
8814   }
8815 
8816   if (!getLangOpts().CPlusPlus) {
8817     // Perform semantic checking on the function declaration.
8818     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8819       CheckMain(NewFD, D.getDeclSpec());
8820 
8821     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8822       CheckMSVCRTEntryPoint(NewFD);
8823 
8824     if (!NewFD->isInvalidDecl())
8825       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8826                                                   isMemberSpecialization));
8827     else if (!Previous.empty())
8828       // Recover gracefully from an invalid redeclaration.
8829       D.setRedeclaration(true);
8830     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8831             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8832            "previous declaration set still overloaded");
8833 
8834     // Diagnose no-prototype function declarations with calling conventions that
8835     // don't support variadic calls. Only do this in C and do it after merging
8836     // possibly prototyped redeclarations.
8837     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8838     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8839       CallingConv CC = FT->getExtInfo().getCC();
8840       if (!supportsVariadicCall(CC)) {
8841         // Windows system headers sometimes accidentally use stdcall without
8842         // (void) parameters, so we relax this to a warning.
8843         int DiagID =
8844             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8845         Diag(NewFD->getLocation(), DiagID)
8846             << FunctionType::getNameForCallConv(CC);
8847       }
8848     }
8849   } else {
8850     // C++11 [replacement.functions]p3:
8851     //  The program's definitions shall not be specified as inline.
8852     //
8853     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8854     //
8855     // Suppress the diagnostic if the function is __attribute__((used)), since
8856     // that forces an external definition to be emitted.
8857     if (D.getDeclSpec().isInlineSpecified() &&
8858         NewFD->isReplaceableGlobalAllocationFunction() &&
8859         !NewFD->hasAttr<UsedAttr>())
8860       Diag(D.getDeclSpec().getInlineSpecLoc(),
8861            diag::ext_operator_new_delete_declared_inline)
8862         << NewFD->getDeclName();
8863 
8864     // If the declarator is a template-id, translate the parser's template
8865     // argument list into our AST format.
8866     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8867       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8868       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8869       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8870       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8871                                          TemplateId->NumArgs);
8872       translateTemplateArguments(TemplateArgsPtr,
8873                                  TemplateArgs);
8874 
8875       HasExplicitTemplateArgs = true;
8876 
8877       if (NewFD->isInvalidDecl()) {
8878         HasExplicitTemplateArgs = false;
8879       } else if (FunctionTemplate) {
8880         // Function template with explicit template arguments.
8881         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8882           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8883 
8884         HasExplicitTemplateArgs = false;
8885       } else {
8886         assert((isFunctionTemplateSpecialization ||
8887                 D.getDeclSpec().isFriendSpecified()) &&
8888                "should have a 'template<>' for this decl");
8889         // "friend void foo<>(int);" is an implicit specialization decl.
8890         isFunctionTemplateSpecialization = true;
8891       }
8892     } else if (isFriend && isFunctionTemplateSpecialization) {
8893       // This combination is only possible in a recovery case;  the user
8894       // wrote something like:
8895       //   template <> friend void foo(int);
8896       // which we're recovering from as if the user had written:
8897       //   friend void foo<>(int);
8898       // Go ahead and fake up a template id.
8899       HasExplicitTemplateArgs = true;
8900       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8901       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8902     }
8903 
8904     // We do not add HD attributes to specializations here because
8905     // they may have different constexpr-ness compared to their
8906     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8907     // may end up with different effective targets. Instead, a
8908     // specialization inherits its target attributes from its template
8909     // in the CheckFunctionTemplateSpecialization() call below.
8910     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8911       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8912 
8913     // If it's a friend (and only if it's a friend), it's possible
8914     // that either the specialized function type or the specialized
8915     // template is dependent, and therefore matching will fail.  In
8916     // this case, don't check the specialization yet.
8917     bool InstantiationDependent = false;
8918     if (isFunctionTemplateSpecialization && isFriend &&
8919         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8920          TemplateSpecializationType::anyDependentTemplateArguments(
8921             TemplateArgs,
8922             InstantiationDependent))) {
8923       assert(HasExplicitTemplateArgs &&
8924              "friend function specialization without template args");
8925       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8926                                                        Previous))
8927         NewFD->setInvalidDecl();
8928     } else if (isFunctionTemplateSpecialization) {
8929       if (CurContext->isDependentContext() && CurContext->isRecord()
8930           && !isFriend) {
8931         isDependentClassScopeExplicitSpecialization = true;
8932       } else if (!NewFD->isInvalidDecl() &&
8933                  CheckFunctionTemplateSpecialization(
8934                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8935                      Previous))
8936         NewFD->setInvalidDecl();
8937 
8938       // C++ [dcl.stc]p1:
8939       //   A storage-class-specifier shall not be specified in an explicit
8940       //   specialization (14.7.3)
8941       FunctionTemplateSpecializationInfo *Info =
8942           NewFD->getTemplateSpecializationInfo();
8943       if (Info && SC != SC_None) {
8944         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8945           Diag(NewFD->getLocation(),
8946                diag::err_explicit_specialization_inconsistent_storage_class)
8947             << SC
8948             << FixItHint::CreateRemoval(
8949                                       D.getDeclSpec().getStorageClassSpecLoc());
8950 
8951         else
8952           Diag(NewFD->getLocation(),
8953                diag::ext_explicit_specialization_storage_class)
8954             << FixItHint::CreateRemoval(
8955                                       D.getDeclSpec().getStorageClassSpecLoc());
8956       }
8957     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8958       if (CheckMemberSpecialization(NewFD, Previous))
8959           NewFD->setInvalidDecl();
8960     }
8961 
8962     // Perform semantic checking on the function declaration.
8963     if (!isDependentClassScopeExplicitSpecialization) {
8964       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8965         CheckMain(NewFD, D.getDeclSpec());
8966 
8967       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8968         CheckMSVCRTEntryPoint(NewFD);
8969 
8970       if (!NewFD->isInvalidDecl())
8971         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8972                                                     isMemberSpecialization));
8973       else if (!Previous.empty())
8974         // Recover gracefully from an invalid redeclaration.
8975         D.setRedeclaration(true);
8976     }
8977 
8978     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8979             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8980            "previous declaration set still overloaded");
8981 
8982     NamedDecl *PrincipalDecl = (FunctionTemplate
8983                                 ? cast<NamedDecl>(FunctionTemplate)
8984                                 : NewFD);
8985 
8986     if (isFriend && NewFD->getPreviousDecl()) {
8987       AccessSpecifier Access = AS_public;
8988       if (!NewFD->isInvalidDecl())
8989         Access = NewFD->getPreviousDecl()->getAccess();
8990 
8991       NewFD->setAccess(Access);
8992       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8993     }
8994 
8995     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8996         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8997       PrincipalDecl->setNonMemberOperator();
8998 
8999     // If we have a function template, check the template parameter
9000     // list. This will check and merge default template arguments.
9001     if (FunctionTemplate) {
9002       FunctionTemplateDecl *PrevTemplate =
9003                                      FunctionTemplate->getPreviousDecl();
9004       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9005                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9006                                     : nullptr,
9007                             D.getDeclSpec().isFriendSpecified()
9008                               ? (D.isFunctionDefinition()
9009                                    ? TPC_FriendFunctionTemplateDefinition
9010                                    : TPC_FriendFunctionTemplate)
9011                               : (D.getCXXScopeSpec().isSet() &&
9012                                  DC && DC->isRecord() &&
9013                                  DC->isDependentContext())
9014                                   ? TPC_ClassTemplateMember
9015                                   : TPC_FunctionTemplate);
9016     }
9017 
9018     if (NewFD->isInvalidDecl()) {
9019       // Ignore all the rest of this.
9020     } else if (!D.isRedeclaration()) {
9021       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9022                                        AddToScope };
9023       // Fake up an access specifier if it's supposed to be a class member.
9024       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9025         NewFD->setAccess(AS_public);
9026 
9027       // Qualified decls generally require a previous declaration.
9028       if (D.getCXXScopeSpec().isSet()) {
9029         // ...with the major exception of templated-scope or
9030         // dependent-scope friend declarations.
9031 
9032         // TODO: we currently also suppress this check in dependent
9033         // contexts because (1) the parameter depth will be off when
9034         // matching friend templates and (2) we might actually be
9035         // selecting a friend based on a dependent factor.  But there
9036         // are situations where these conditions don't apply and we
9037         // can actually do this check immediately.
9038         //
9039         // Unless the scope is dependent, it's always an error if qualified
9040         // redeclaration lookup found nothing at all. Diagnose that now;
9041         // nothing will diagnose that error later.
9042         if (isFriend &&
9043             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9044              (!Previous.empty() && (TemplateParamLists.size() ||
9045                                     CurContext->isDependentContext())))) {
9046           // ignore these
9047         } else {
9048           // The user tried to provide an out-of-line definition for a
9049           // function that is a member of a class or namespace, but there
9050           // was no such member function declared (C++ [class.mfct]p2,
9051           // C++ [namespace.memdef]p2). For example:
9052           //
9053           // class X {
9054           //   void f() const;
9055           // };
9056           //
9057           // void X::f() { } // ill-formed
9058           //
9059           // Complain about this problem, and attempt to suggest close
9060           // matches (e.g., those that differ only in cv-qualifiers and
9061           // whether the parameter types are references).
9062 
9063           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9064                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9065             AddToScope = ExtraArgs.AddToScope;
9066             return Result;
9067           }
9068         }
9069 
9070         // Unqualified local friend declarations are required to resolve
9071         // to something.
9072       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9073         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9074                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9075           AddToScope = ExtraArgs.AddToScope;
9076           return Result;
9077         }
9078       }
9079     } else if (!D.isFunctionDefinition() &&
9080                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9081                !isFriend && !isFunctionTemplateSpecialization &&
9082                !isMemberSpecialization) {
9083       // An out-of-line member function declaration must also be a
9084       // definition (C++ [class.mfct]p2).
9085       // Note that this is not the case for explicit specializations of
9086       // function templates or member functions of class templates, per
9087       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9088       // extension for compatibility with old SWIG code which likes to
9089       // generate them.
9090       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9091         << D.getCXXScopeSpec().getRange();
9092     }
9093   }
9094 
9095   ProcessPragmaWeak(S, NewFD);
9096   checkAttributesAfterMerging(*this, *NewFD);
9097 
9098   AddKnownFunctionAttributes(NewFD);
9099 
9100   if (NewFD->hasAttr<OverloadableAttr>() &&
9101       !NewFD->getType()->getAs<FunctionProtoType>()) {
9102     Diag(NewFD->getLocation(),
9103          diag::err_attribute_overloadable_no_prototype)
9104       << NewFD;
9105 
9106     // Turn this into a variadic function with no parameters.
9107     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9108     FunctionProtoType::ExtProtoInfo EPI(
9109         Context.getDefaultCallingConvention(true, false));
9110     EPI.Variadic = true;
9111     EPI.ExtInfo = FT->getExtInfo();
9112 
9113     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9114     NewFD->setType(R);
9115   }
9116 
9117   // If there's a #pragma GCC visibility in scope, and this isn't a class
9118   // member, set the visibility of this function.
9119   if (!DC->isRecord() && NewFD->isExternallyVisible())
9120     AddPushedVisibilityAttribute(NewFD);
9121 
9122   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9123   // marking the function.
9124   AddCFAuditedAttribute(NewFD);
9125 
9126   // If this is a function definition, check if we have to apply optnone due to
9127   // a pragma.
9128   if(D.isFunctionDefinition())
9129     AddRangeBasedOptnone(NewFD);
9130 
9131   // If this is the first declaration of an extern C variable, update
9132   // the map of such variables.
9133   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9134       isIncompleteDeclExternC(*this, NewFD))
9135     RegisterLocallyScopedExternCDecl(NewFD, S);
9136 
9137   // Set this FunctionDecl's range up to the right paren.
9138   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9139 
9140   if (D.isRedeclaration() && !Previous.empty()) {
9141     NamedDecl *Prev = Previous.getRepresentativeDecl();
9142     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9143                                    isMemberSpecialization ||
9144                                        isFunctionTemplateSpecialization,
9145                                    D.isFunctionDefinition());
9146   }
9147 
9148   if (getLangOpts().CUDA) {
9149     IdentifierInfo *II = NewFD->getIdentifier();
9150     if (II && II->isStr(getCudaConfigureFuncName()) &&
9151         !NewFD->isInvalidDecl() &&
9152         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9153       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9154         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9155             << getCudaConfigureFuncName();
9156       Context.setcudaConfigureCallDecl(NewFD);
9157     }
9158 
9159     // Variadic functions, other than a *declaration* of printf, are not allowed
9160     // in device-side CUDA code, unless someone passed
9161     // -fcuda-allow-variadic-functions.
9162     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9163         (NewFD->hasAttr<CUDADeviceAttr>() ||
9164          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9165         !(II && II->isStr("printf") && NewFD->isExternC() &&
9166           !D.isFunctionDefinition())) {
9167       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9168     }
9169   }
9170 
9171   MarkUnusedFileScopedDecl(NewFD);
9172 
9173   if (getLangOpts().CPlusPlus) {
9174     if (FunctionTemplate) {
9175       if (NewFD->isInvalidDecl())
9176         FunctionTemplate->setInvalidDecl();
9177       return FunctionTemplate;
9178     }
9179 
9180     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9181       CompleteMemberSpecialization(NewFD, Previous);
9182   }
9183 
9184   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9185     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9186     if ((getLangOpts().OpenCLVersion >= 120)
9187         && (SC == SC_Static)) {
9188       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9189       D.setInvalidType();
9190     }
9191 
9192     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9193     if (!NewFD->getReturnType()->isVoidType()) {
9194       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9195       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9196           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9197                                 : FixItHint());
9198       D.setInvalidType();
9199     }
9200 
9201     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9202     for (auto Param : NewFD->parameters())
9203       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9204   }
9205   for (const ParmVarDecl *Param : NewFD->parameters()) {
9206     QualType PT = Param->getType();
9207 
9208     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9209     // types.
9210     if (getLangOpts().OpenCLVersion >= 200) {
9211       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9212         QualType ElemTy = PipeTy->getElementType();
9213           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9214             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9215             D.setInvalidType();
9216           }
9217       }
9218     }
9219   }
9220 
9221   // Here we have an function template explicit specialization at class scope.
9222   // The actual specialization will be postponed to template instatiation
9223   // time via the ClassScopeFunctionSpecializationDecl node.
9224   if (isDependentClassScopeExplicitSpecialization) {
9225     ClassScopeFunctionSpecializationDecl *NewSpec =
9226                          ClassScopeFunctionSpecializationDecl::Create(
9227                                 Context, CurContext, NewFD->getLocation(),
9228                                 cast<CXXMethodDecl>(NewFD),
9229                                 HasExplicitTemplateArgs, TemplateArgs);
9230     CurContext->addDecl(NewSpec);
9231     AddToScope = false;
9232   }
9233 
9234   // Diagnose availability attributes. Availability cannot be used on functions
9235   // that are run during load/unload.
9236   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9237     if (NewFD->hasAttr<ConstructorAttr>()) {
9238       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9239           << 1;
9240       NewFD->dropAttr<AvailabilityAttr>();
9241     }
9242     if (NewFD->hasAttr<DestructorAttr>()) {
9243       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9244           << 2;
9245       NewFD->dropAttr<AvailabilityAttr>();
9246     }
9247   }
9248 
9249   return NewFD;
9250 }
9251 
9252 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9253 /// when __declspec(code_seg) "is applied to a class, all member functions of
9254 /// the class and nested classes -- this includes compiler-generated special
9255 /// member functions -- are put in the specified segment."
9256 /// The actual behavior is a little more complicated. The Microsoft compiler
9257 /// won't check outer classes if there is an active value from #pragma code_seg.
9258 /// The CodeSeg is always applied from the direct parent but only from outer
9259 /// classes when the #pragma code_seg stack is empty. See:
9260 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9261 /// available since MS has removed the page.
9262 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9263   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9264   if (!Method)
9265     return nullptr;
9266   const CXXRecordDecl *Parent = Method->getParent();
9267   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9268     Attr *NewAttr = SAttr->clone(S.getASTContext());
9269     NewAttr->setImplicit(true);
9270     return NewAttr;
9271   }
9272 
9273   // The Microsoft compiler won't check outer classes for the CodeSeg
9274   // when the #pragma code_seg stack is active.
9275   if (S.CodeSegStack.CurrentValue)
9276    return nullptr;
9277 
9278   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9279     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9280       Attr *NewAttr = SAttr->clone(S.getASTContext());
9281       NewAttr->setImplicit(true);
9282       return NewAttr;
9283     }
9284   }
9285   return nullptr;
9286 }
9287 
9288 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9289 /// containing class. Otherwise it will return implicit SectionAttr if the
9290 /// function is a definition and there is an active value on CodeSegStack
9291 /// (from the current #pragma code-seg value).
9292 ///
9293 /// \param FD Function being declared.
9294 /// \param IsDefinition Whether it is a definition or just a declarartion.
9295 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9296 ///          nullptr if no attribute should be added.
9297 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9298                                                        bool IsDefinition) {
9299   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9300     return A;
9301   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9302       CodeSegStack.CurrentValue) {
9303     return SectionAttr::CreateImplicit(getASTContext(),
9304                                        SectionAttr::Declspec_allocate,
9305                                        CodeSegStack.CurrentValue->getString(),
9306                                        CodeSegStack.CurrentPragmaLocation);
9307   }
9308   return nullptr;
9309 }
9310 
9311 /// Determines if we can perform a correct type check for \p D as a
9312 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9313 /// best-effort check.
9314 ///
9315 /// \param NewD The new declaration.
9316 /// \param OldD The old declaration.
9317 /// \param NewT The portion of the type of the new declaration to check.
9318 /// \param OldT The portion of the type of the old declaration to check.
9319 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9320                                           QualType NewT, QualType OldT) {
9321   if (!NewD->getLexicalDeclContext()->isDependentContext())
9322     return true;
9323 
9324   // For dependently-typed local extern declarations and friends, we can't
9325   // perform a correct type check in general until instantiation:
9326   //
9327   //   int f();
9328   //   template<typename T> void g() { T f(); }
9329   //
9330   // (valid if g() is only instantiated with T = int).
9331   if (NewT->isDependentType() &&
9332       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9333     return false;
9334 
9335   // Similarly, if the previous declaration was a dependent local extern
9336   // declaration, we don't really know its type yet.
9337   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9338     return false;
9339 
9340   return true;
9341 }
9342 
9343 /// Checks if the new declaration declared in dependent context must be
9344 /// put in the same redeclaration chain as the specified declaration.
9345 ///
9346 /// \param D Declaration that is checked.
9347 /// \param PrevDecl Previous declaration found with proper lookup method for the
9348 ///                 same declaration name.
9349 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9350 ///          belongs to.
9351 ///
9352 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9353   if (!D->getLexicalDeclContext()->isDependentContext())
9354     return true;
9355 
9356   // Don't chain dependent friend function definitions until instantiation, to
9357   // permit cases like
9358   //
9359   //   void func();
9360   //   template<typename T> class C1 { friend void func() {} };
9361   //   template<typename T> class C2 { friend void func() {} };
9362   //
9363   // ... which is valid if only one of C1 and C2 is ever instantiated.
9364   //
9365   // FIXME: This need only apply to function definitions. For now, we proxy
9366   // this by checking for a file-scope function. We do not want this to apply
9367   // to friend declarations nominating member functions, because that gets in
9368   // the way of access checks.
9369   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9370     return false;
9371 
9372   auto *VD = dyn_cast<ValueDecl>(D);
9373   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9374   return !VD || !PrevVD ||
9375          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9376                                         PrevVD->getType());
9377 }
9378 
9379 /// Check the target attribute of the function for MultiVersion
9380 /// validity.
9381 ///
9382 /// Returns true if there was an error, false otherwise.
9383 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9384   const auto *TA = FD->getAttr<TargetAttr>();
9385   assert(TA && "MultiVersion Candidate requires a target attribute");
9386   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9387   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9388   enum ErrType { Feature = 0, Architecture = 1 };
9389 
9390   if (!ParseInfo.Architecture.empty() &&
9391       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9392     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9393         << Architecture << ParseInfo.Architecture;
9394     return true;
9395   }
9396 
9397   for (const auto &Feat : ParseInfo.Features) {
9398     auto BareFeat = StringRef{Feat}.substr(1);
9399     if (Feat[0] == '-') {
9400       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9401           << Feature << ("no-" + BareFeat).str();
9402       return true;
9403     }
9404 
9405     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9406         !TargetInfo.isValidFeatureName(BareFeat)) {
9407       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9408           << Feature << BareFeat;
9409       return true;
9410     }
9411   }
9412   return false;
9413 }
9414 
9415 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9416                                          MultiVersionKind MVType) {
9417   for (const Attr *A : FD->attrs()) {
9418     switch (A->getKind()) {
9419     case attr::CPUDispatch:
9420     case attr::CPUSpecific:
9421       if (MVType != MultiVersionKind::CPUDispatch &&
9422           MVType != MultiVersionKind::CPUSpecific)
9423         return true;
9424       break;
9425     case attr::Target:
9426       if (MVType != MultiVersionKind::Target)
9427         return true;
9428       break;
9429     default:
9430       return true;
9431     }
9432   }
9433   return false;
9434 }
9435 
9436 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9437                                              const FunctionDecl *NewFD,
9438                                              bool CausesMV,
9439                                              MultiVersionKind MVType) {
9440   enum DoesntSupport {
9441     FuncTemplates = 0,
9442     VirtFuncs = 1,
9443     DeducedReturn = 2,
9444     Constructors = 3,
9445     Destructors = 4,
9446     DeletedFuncs = 5,
9447     DefaultedFuncs = 6,
9448     ConstexprFuncs = 7,
9449   };
9450   enum Different {
9451     CallingConv = 0,
9452     ReturnType = 1,
9453     ConstexprSpec = 2,
9454     InlineSpec = 3,
9455     StorageClass = 4,
9456     Linkage = 5
9457   };
9458 
9459   bool IsCPUSpecificCPUDispatchMVType =
9460       MVType == MultiVersionKind::CPUDispatch ||
9461       MVType == MultiVersionKind::CPUSpecific;
9462 
9463   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9464     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9465     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9466     return true;
9467   }
9468 
9469   if (!NewFD->getType()->getAs<FunctionProtoType>())
9470     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9471 
9472   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9473     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9474     if (OldFD)
9475       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9476     return true;
9477   }
9478 
9479   // For now, disallow all other attributes.  These should be opt-in, but
9480   // an analysis of all of them is a future FIXME.
9481   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9482     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9483         << IsCPUSpecificCPUDispatchMVType;
9484     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9485     return true;
9486   }
9487 
9488   if (HasNonMultiVersionAttributes(NewFD, MVType))
9489     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9490            << IsCPUSpecificCPUDispatchMVType;
9491 
9492   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9493     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9494            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9495 
9496   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9497     if (NewCXXFD->isVirtual())
9498       return S.Diag(NewCXXFD->getLocation(),
9499                     diag::err_multiversion_doesnt_support)
9500              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9501 
9502     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9503       return S.Diag(NewCXXCtor->getLocation(),
9504                     diag::err_multiversion_doesnt_support)
9505              << IsCPUSpecificCPUDispatchMVType << Constructors;
9506 
9507     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9508       return S.Diag(NewCXXDtor->getLocation(),
9509                     diag::err_multiversion_doesnt_support)
9510              << IsCPUSpecificCPUDispatchMVType << Destructors;
9511   }
9512 
9513   if (NewFD->isDeleted())
9514     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9515            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9516 
9517   if (NewFD->isDefaulted())
9518     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9519            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9520 
9521   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9522                                MVType == MultiVersionKind::CPUSpecific))
9523     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9524            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9525 
9526   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9527   const auto *NewType = cast<FunctionType>(NewQType);
9528   QualType NewReturnType = NewType->getReturnType();
9529 
9530   if (NewReturnType->isUndeducedType())
9531     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9532            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9533 
9534   // Only allow transition to MultiVersion if it hasn't been used.
9535   if (OldFD && CausesMV && OldFD->isUsed(false))
9536     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9537 
9538   // Ensure the return type is identical.
9539   if (OldFD) {
9540     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9541     const auto *OldType = cast<FunctionType>(OldQType);
9542     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9543     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9544 
9545     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9546       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9547              << CallingConv;
9548 
9549     QualType OldReturnType = OldType->getReturnType();
9550 
9551     if (OldReturnType != NewReturnType)
9552       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9553              << ReturnType;
9554 
9555     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9556       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9557              << ConstexprSpec;
9558 
9559     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9560       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9561              << InlineSpec;
9562 
9563     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9564       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9565              << StorageClass;
9566 
9567     if (OldFD->isExternC() != NewFD->isExternC())
9568       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9569              << Linkage;
9570 
9571     if (S.CheckEquivalentExceptionSpec(
9572             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9573             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9574       return true;
9575   }
9576   return false;
9577 }
9578 
9579 /// Check the validity of a multiversion function declaration that is the
9580 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9581 ///
9582 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9583 ///
9584 /// Returns true if there was an error, false otherwise.
9585 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9586                                            MultiVersionKind MVType,
9587                                            const TargetAttr *TA,
9588                                            const CPUDispatchAttr *CPUDisp,
9589                                            const CPUSpecificAttr *CPUSpec) {
9590   assert(MVType != MultiVersionKind::None &&
9591          "Function lacks multiversion attribute");
9592 
9593   // Target only causes MV if it is default, otherwise this is a normal
9594   // function.
9595   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9596     return false;
9597 
9598   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9599     FD->setInvalidDecl();
9600     return true;
9601   }
9602 
9603   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9604     FD->setInvalidDecl();
9605     return true;
9606   }
9607 
9608   FD->setIsMultiVersion();
9609   return false;
9610 }
9611 
9612 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9613   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9614     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9615       return true;
9616   }
9617 
9618   return false;
9619 }
9620 
9621 static bool CheckTargetCausesMultiVersioning(
9622     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9623     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9624     LookupResult &Previous) {
9625   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9626   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9627   // Sort order doesn't matter, it just needs to be consistent.
9628   llvm::sort(NewParsed.Features);
9629 
9630   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9631   // to change, this is a simple redeclaration.
9632   if (!NewTA->isDefaultVersion() &&
9633       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9634     return false;
9635 
9636   // Otherwise, this decl causes MultiVersioning.
9637   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9638     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9639     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9640     NewFD->setInvalidDecl();
9641     return true;
9642   }
9643 
9644   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9645                                        MultiVersionKind::Target)) {
9646     NewFD->setInvalidDecl();
9647     return true;
9648   }
9649 
9650   if (CheckMultiVersionValue(S, NewFD)) {
9651     NewFD->setInvalidDecl();
9652     return true;
9653   }
9654 
9655   // If this is 'default', permit the forward declaration.
9656   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9657     Redeclaration = true;
9658     OldDecl = OldFD;
9659     OldFD->setIsMultiVersion();
9660     NewFD->setIsMultiVersion();
9661     return false;
9662   }
9663 
9664   if (CheckMultiVersionValue(S, OldFD)) {
9665     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9666     NewFD->setInvalidDecl();
9667     return true;
9668   }
9669 
9670   TargetAttr::ParsedTargetAttr OldParsed =
9671       OldTA->parse(std::less<std::string>());
9672 
9673   if (OldParsed == NewParsed) {
9674     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9675     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9676     NewFD->setInvalidDecl();
9677     return true;
9678   }
9679 
9680   for (const auto *FD : OldFD->redecls()) {
9681     const auto *CurTA = FD->getAttr<TargetAttr>();
9682     // We allow forward declarations before ANY multiversioning attributes, but
9683     // nothing after the fact.
9684     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9685         (!CurTA || CurTA->isInherited())) {
9686       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9687           << 0;
9688       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9689       NewFD->setInvalidDecl();
9690       return true;
9691     }
9692   }
9693 
9694   OldFD->setIsMultiVersion();
9695   NewFD->setIsMultiVersion();
9696   Redeclaration = false;
9697   MergeTypeWithPrevious = false;
9698   OldDecl = nullptr;
9699   Previous.clear();
9700   return false;
9701 }
9702 
9703 /// Check the validity of a new function declaration being added to an existing
9704 /// multiversioned declaration collection.
9705 static bool CheckMultiVersionAdditionalDecl(
9706     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9707     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9708     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9709     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9710     LookupResult &Previous) {
9711 
9712   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9713   // Disallow mixing of multiversioning types.
9714   if ((OldMVType == MultiVersionKind::Target &&
9715        NewMVType != MultiVersionKind::Target) ||
9716       (NewMVType == MultiVersionKind::Target &&
9717        OldMVType != MultiVersionKind::Target)) {
9718     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9719     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9720     NewFD->setInvalidDecl();
9721     return true;
9722   }
9723 
9724   TargetAttr::ParsedTargetAttr NewParsed;
9725   if (NewTA) {
9726     NewParsed = NewTA->parse();
9727     llvm::sort(NewParsed.Features);
9728   }
9729 
9730   bool UseMemberUsingDeclRules =
9731       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9732 
9733   // Next, check ALL non-overloads to see if this is a redeclaration of a
9734   // previous member of the MultiVersion set.
9735   for (NamedDecl *ND : Previous) {
9736     FunctionDecl *CurFD = ND->getAsFunction();
9737     if (!CurFD)
9738       continue;
9739     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9740       continue;
9741 
9742     if (NewMVType == MultiVersionKind::Target) {
9743       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9744       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9745         NewFD->setIsMultiVersion();
9746         Redeclaration = true;
9747         OldDecl = ND;
9748         return false;
9749       }
9750 
9751       TargetAttr::ParsedTargetAttr CurParsed =
9752           CurTA->parse(std::less<std::string>());
9753       if (CurParsed == NewParsed) {
9754         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9755         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9756         NewFD->setInvalidDecl();
9757         return true;
9758       }
9759     } else {
9760       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9761       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9762       // Handle CPUDispatch/CPUSpecific versions.
9763       // Only 1 CPUDispatch function is allowed, this will make it go through
9764       // the redeclaration errors.
9765       if (NewMVType == MultiVersionKind::CPUDispatch &&
9766           CurFD->hasAttr<CPUDispatchAttr>()) {
9767         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9768             std::equal(
9769                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9770                 NewCPUDisp->cpus_begin(),
9771                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9772                   return Cur->getName() == New->getName();
9773                 })) {
9774           NewFD->setIsMultiVersion();
9775           Redeclaration = true;
9776           OldDecl = ND;
9777           return false;
9778         }
9779 
9780         // If the declarations don't match, this is an error condition.
9781         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9782         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9783         NewFD->setInvalidDecl();
9784         return true;
9785       }
9786       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9787 
9788         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9789             std::equal(
9790                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9791                 NewCPUSpec->cpus_begin(),
9792                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9793                   return Cur->getName() == New->getName();
9794                 })) {
9795           NewFD->setIsMultiVersion();
9796           Redeclaration = true;
9797           OldDecl = ND;
9798           return false;
9799         }
9800 
9801         // Only 1 version of CPUSpecific is allowed for each CPU.
9802         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9803           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9804             if (CurII == NewII) {
9805               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9806                   << NewII;
9807               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9808               NewFD->setInvalidDecl();
9809               return true;
9810             }
9811           }
9812         }
9813       }
9814       // If the two decls aren't the same MVType, there is no possible error
9815       // condition.
9816     }
9817   }
9818 
9819   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9820   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9821   // handled in the attribute adding step.
9822   if (NewMVType == MultiVersionKind::Target &&
9823       CheckMultiVersionValue(S, NewFD)) {
9824     NewFD->setInvalidDecl();
9825     return true;
9826   }
9827 
9828   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9829                                        !OldFD->isMultiVersion(), NewMVType)) {
9830     NewFD->setInvalidDecl();
9831     return true;
9832   }
9833 
9834   // Permit forward declarations in the case where these two are compatible.
9835   if (!OldFD->isMultiVersion()) {
9836     OldFD->setIsMultiVersion();
9837     NewFD->setIsMultiVersion();
9838     Redeclaration = true;
9839     OldDecl = OldFD;
9840     return false;
9841   }
9842 
9843   NewFD->setIsMultiVersion();
9844   Redeclaration = false;
9845   MergeTypeWithPrevious = false;
9846   OldDecl = nullptr;
9847   Previous.clear();
9848   return false;
9849 }
9850 
9851 
9852 /// Check the validity of a mulitversion function declaration.
9853 /// Also sets the multiversion'ness' of the function itself.
9854 ///
9855 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9856 ///
9857 /// Returns true if there was an error, false otherwise.
9858 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9859                                       bool &Redeclaration, NamedDecl *&OldDecl,
9860                                       bool &MergeTypeWithPrevious,
9861                                       LookupResult &Previous) {
9862   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9863   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9864   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9865 
9866   // Mixing Multiversioning types is prohibited.
9867   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9868       (NewCPUDisp && NewCPUSpec)) {
9869     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9870     NewFD->setInvalidDecl();
9871     return true;
9872   }
9873 
9874   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9875 
9876   // Main isn't allowed to become a multiversion function, however it IS
9877   // permitted to have 'main' be marked with the 'target' optimization hint.
9878   if (NewFD->isMain()) {
9879     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9880         MVType == MultiVersionKind::CPUDispatch ||
9881         MVType == MultiVersionKind::CPUSpecific) {
9882       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9883       NewFD->setInvalidDecl();
9884       return true;
9885     }
9886     return false;
9887   }
9888 
9889   if (!OldDecl || !OldDecl->getAsFunction() ||
9890       OldDecl->getDeclContext()->getRedeclContext() !=
9891           NewFD->getDeclContext()->getRedeclContext()) {
9892     // If there's no previous declaration, AND this isn't attempting to cause
9893     // multiversioning, this isn't an error condition.
9894     if (MVType == MultiVersionKind::None)
9895       return false;
9896     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9897                                           NewCPUSpec);
9898   }
9899 
9900   FunctionDecl *OldFD = OldDecl->getAsFunction();
9901 
9902   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9903     return false;
9904 
9905   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9906     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9907         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9908     NewFD->setInvalidDecl();
9909     return true;
9910   }
9911 
9912   // Handle the target potentially causes multiversioning case.
9913   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
9914     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9915                                             Redeclaration, OldDecl,
9916                                             MergeTypeWithPrevious, Previous);
9917 
9918   // At this point, we have a multiversion function decl (in OldFD) AND an
9919   // appropriate attribute in the current function decl.  Resolve that these are
9920   // still compatible with previous declarations.
9921   return CheckMultiVersionAdditionalDecl(
9922       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9923       OldDecl, MergeTypeWithPrevious, Previous);
9924 }
9925 
9926 /// Perform semantic checking of a new function declaration.
9927 ///
9928 /// Performs semantic analysis of the new function declaration
9929 /// NewFD. This routine performs all semantic checking that does not
9930 /// require the actual declarator involved in the declaration, and is
9931 /// used both for the declaration of functions as they are parsed
9932 /// (called via ActOnDeclarator) and for the declaration of functions
9933 /// that have been instantiated via C++ template instantiation (called
9934 /// via InstantiateDecl).
9935 ///
9936 /// \param IsMemberSpecialization whether this new function declaration is
9937 /// a member specialization (that replaces any definition provided by the
9938 /// previous declaration).
9939 ///
9940 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9941 ///
9942 /// \returns true if the function declaration is a redeclaration.
9943 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9944                                     LookupResult &Previous,
9945                                     bool IsMemberSpecialization) {
9946   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9947          "Variably modified return types are not handled here");
9948 
9949   // Determine whether the type of this function should be merged with
9950   // a previous visible declaration. This never happens for functions in C++,
9951   // and always happens in C if the previous declaration was visible.
9952   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9953                                !Previous.isShadowed();
9954 
9955   bool Redeclaration = false;
9956   NamedDecl *OldDecl = nullptr;
9957   bool MayNeedOverloadableChecks = false;
9958 
9959   // Merge or overload the declaration with an existing declaration of
9960   // the same name, if appropriate.
9961   if (!Previous.empty()) {
9962     // Determine whether NewFD is an overload of PrevDecl or
9963     // a declaration that requires merging. If it's an overload,
9964     // there's no more work to do here; we'll just add the new
9965     // function to the scope.
9966     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9967       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9968       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9969         Redeclaration = true;
9970         OldDecl = Candidate;
9971       }
9972     } else {
9973       MayNeedOverloadableChecks = true;
9974       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9975                             /*NewIsUsingDecl*/ false)) {
9976       case Ovl_Match:
9977         Redeclaration = true;
9978         break;
9979 
9980       case Ovl_NonFunction:
9981         Redeclaration = true;
9982         break;
9983 
9984       case Ovl_Overload:
9985         Redeclaration = false;
9986         break;
9987       }
9988     }
9989   }
9990 
9991   // Check for a previous extern "C" declaration with this name.
9992   if (!Redeclaration &&
9993       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9994     if (!Previous.empty()) {
9995       // This is an extern "C" declaration with the same name as a previous
9996       // declaration, and thus redeclares that entity...
9997       Redeclaration = true;
9998       OldDecl = Previous.getFoundDecl();
9999       MergeTypeWithPrevious = false;
10000 
10001       // ... except in the presence of __attribute__((overloadable)).
10002       if (OldDecl->hasAttr<OverloadableAttr>() ||
10003           NewFD->hasAttr<OverloadableAttr>()) {
10004         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10005           MayNeedOverloadableChecks = true;
10006           Redeclaration = false;
10007           OldDecl = nullptr;
10008         }
10009       }
10010     }
10011   }
10012 
10013   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10014                                 MergeTypeWithPrevious, Previous))
10015     return Redeclaration;
10016 
10017   // C++11 [dcl.constexpr]p8:
10018   //   A constexpr specifier for a non-static member function that is not
10019   //   a constructor declares that member function to be const.
10020   //
10021   // This needs to be delayed until we know whether this is an out-of-line
10022   // definition of a static member function.
10023   //
10024   // This rule is not present in C++1y, so we produce a backwards
10025   // compatibility warning whenever it happens in C++11.
10026   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10027   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10028       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10029       !MD->getMethodQualifiers().hasConst()) {
10030     CXXMethodDecl *OldMD = nullptr;
10031     if (OldDecl)
10032       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10033     if (!OldMD || !OldMD->isStatic()) {
10034       const FunctionProtoType *FPT =
10035         MD->getType()->castAs<FunctionProtoType>();
10036       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10037       EPI.TypeQuals.addConst();
10038       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10039                                           FPT->getParamTypes(), EPI));
10040 
10041       // Warn that we did this, if we're not performing template instantiation.
10042       // In that case, we'll have warned already when the template was defined.
10043       if (!inTemplateInstantiation()) {
10044         SourceLocation AddConstLoc;
10045         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10046                 .IgnoreParens().getAs<FunctionTypeLoc>())
10047           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10048 
10049         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10050           << FixItHint::CreateInsertion(AddConstLoc, " const");
10051       }
10052     }
10053   }
10054 
10055   if (Redeclaration) {
10056     // NewFD and OldDecl represent declarations that need to be
10057     // merged.
10058     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10059       NewFD->setInvalidDecl();
10060       return Redeclaration;
10061     }
10062 
10063     Previous.clear();
10064     Previous.addDecl(OldDecl);
10065 
10066     if (FunctionTemplateDecl *OldTemplateDecl =
10067             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10068       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10069       FunctionTemplateDecl *NewTemplateDecl
10070         = NewFD->getDescribedFunctionTemplate();
10071       assert(NewTemplateDecl && "Template/non-template mismatch");
10072 
10073       // The call to MergeFunctionDecl above may have created some state in
10074       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10075       // can add it as a redeclaration.
10076       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10077 
10078       NewFD->setPreviousDeclaration(OldFD);
10079       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10080       if (NewFD->isCXXClassMember()) {
10081         NewFD->setAccess(OldTemplateDecl->getAccess());
10082         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10083       }
10084 
10085       // If this is an explicit specialization of a member that is a function
10086       // template, mark it as a member specialization.
10087       if (IsMemberSpecialization &&
10088           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10089         NewTemplateDecl->setMemberSpecialization();
10090         assert(OldTemplateDecl->isMemberSpecialization());
10091         // Explicit specializations of a member template do not inherit deleted
10092         // status from the parent member template that they are specializing.
10093         if (OldFD->isDeleted()) {
10094           // FIXME: This assert will not hold in the presence of modules.
10095           assert(OldFD->getCanonicalDecl() == OldFD);
10096           // FIXME: We need an update record for this AST mutation.
10097           OldFD->setDeletedAsWritten(false);
10098         }
10099       }
10100 
10101     } else {
10102       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10103         auto *OldFD = cast<FunctionDecl>(OldDecl);
10104         // This needs to happen first so that 'inline' propagates.
10105         NewFD->setPreviousDeclaration(OldFD);
10106         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10107         if (NewFD->isCXXClassMember())
10108           NewFD->setAccess(OldFD->getAccess());
10109       }
10110     }
10111   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10112              !NewFD->getAttr<OverloadableAttr>()) {
10113     assert((Previous.empty() ||
10114             llvm::any_of(Previous,
10115                          [](const NamedDecl *ND) {
10116                            return ND->hasAttr<OverloadableAttr>();
10117                          })) &&
10118            "Non-redecls shouldn't happen without overloadable present");
10119 
10120     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10121       const auto *FD = dyn_cast<FunctionDecl>(ND);
10122       return FD && !FD->hasAttr<OverloadableAttr>();
10123     });
10124 
10125     if (OtherUnmarkedIter != Previous.end()) {
10126       Diag(NewFD->getLocation(),
10127            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10128       Diag((*OtherUnmarkedIter)->getLocation(),
10129            diag::note_attribute_overloadable_prev_overload)
10130           << false;
10131 
10132       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10133     }
10134   }
10135 
10136   // Semantic checking for this function declaration (in isolation).
10137 
10138   if (getLangOpts().CPlusPlus) {
10139     // C++-specific checks.
10140     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10141       CheckConstructor(Constructor);
10142     } else if (CXXDestructorDecl *Destructor =
10143                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10144       CXXRecordDecl *Record = Destructor->getParent();
10145       QualType ClassType = Context.getTypeDeclType(Record);
10146 
10147       // FIXME: Shouldn't we be able to perform this check even when the class
10148       // type is dependent? Both gcc and edg can handle that.
10149       if (!ClassType->isDependentType()) {
10150         DeclarationName Name
10151           = Context.DeclarationNames.getCXXDestructorName(
10152                                         Context.getCanonicalType(ClassType));
10153         if (NewFD->getDeclName() != Name) {
10154           Diag(NewFD->getLocation(), diag::err_destructor_name);
10155           NewFD->setInvalidDecl();
10156           return Redeclaration;
10157         }
10158       }
10159     } else if (CXXConversionDecl *Conversion
10160                = dyn_cast<CXXConversionDecl>(NewFD)) {
10161       ActOnConversionDeclarator(Conversion);
10162     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10163       if (auto *TD = Guide->getDescribedFunctionTemplate())
10164         CheckDeductionGuideTemplate(TD);
10165 
10166       // A deduction guide is not on the list of entities that can be
10167       // explicitly specialized.
10168       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10169         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10170             << /*explicit specialization*/ 1;
10171     }
10172 
10173     // Find any virtual functions that this function overrides.
10174     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10175       if (!Method->isFunctionTemplateSpecialization() &&
10176           !Method->getDescribedFunctionTemplate() &&
10177           Method->isCanonicalDecl()) {
10178         if (AddOverriddenMethods(Method->getParent(), Method)) {
10179           // If the function was marked as "static", we have a problem.
10180           if (NewFD->getStorageClass() == SC_Static) {
10181             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10182           }
10183         }
10184       }
10185 
10186       if (Method->isStatic())
10187         checkThisInStaticMemberFunctionType(Method);
10188     }
10189 
10190     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10191     if (NewFD->isOverloadedOperator() &&
10192         CheckOverloadedOperatorDeclaration(NewFD)) {
10193       NewFD->setInvalidDecl();
10194       return Redeclaration;
10195     }
10196 
10197     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10198     if (NewFD->getLiteralIdentifier() &&
10199         CheckLiteralOperatorDeclaration(NewFD)) {
10200       NewFD->setInvalidDecl();
10201       return Redeclaration;
10202     }
10203 
10204     // In C++, check default arguments now that we have merged decls. Unless
10205     // the lexical context is the class, because in this case this is done
10206     // during delayed parsing anyway.
10207     if (!CurContext->isRecord())
10208       CheckCXXDefaultArguments(NewFD);
10209 
10210     // If this function declares a builtin function, check the type of this
10211     // declaration against the expected type for the builtin.
10212     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10213       ASTContext::GetBuiltinTypeError Error;
10214       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10215       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10216       // If the type of the builtin differs only in its exception
10217       // specification, that's OK.
10218       // FIXME: If the types do differ in this way, it would be better to
10219       // retain the 'noexcept' form of the type.
10220       if (!T.isNull() &&
10221           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10222                                                             NewFD->getType()))
10223         // The type of this function differs from the type of the builtin,
10224         // so forget about the builtin entirely.
10225         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10226     }
10227 
10228     // If this function is declared as being extern "C", then check to see if
10229     // the function returns a UDT (class, struct, or union type) that is not C
10230     // compatible, and if it does, warn the user.
10231     // But, issue any diagnostic on the first declaration only.
10232     if (Previous.empty() && NewFD->isExternC()) {
10233       QualType R = NewFD->getReturnType();
10234       if (R->isIncompleteType() && !R->isVoidType())
10235         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10236             << NewFD << R;
10237       else if (!R.isPODType(Context) && !R->isVoidType() &&
10238                !R->isObjCObjectPointerType())
10239         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10240     }
10241 
10242     // C++1z [dcl.fct]p6:
10243     //   [...] whether the function has a non-throwing exception-specification
10244     //   [is] part of the function type
10245     //
10246     // This results in an ABI break between C++14 and C++17 for functions whose
10247     // declared type includes an exception-specification in a parameter or
10248     // return type. (Exception specifications on the function itself are OK in
10249     // most cases, and exception specifications are not permitted in most other
10250     // contexts where they could make it into a mangling.)
10251     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10252       auto HasNoexcept = [&](QualType T) -> bool {
10253         // Strip off declarator chunks that could be between us and a function
10254         // type. We don't need to look far, exception specifications are very
10255         // restricted prior to C++17.
10256         if (auto *RT = T->getAs<ReferenceType>())
10257           T = RT->getPointeeType();
10258         else if (T->isAnyPointerType())
10259           T = T->getPointeeType();
10260         else if (auto *MPT = T->getAs<MemberPointerType>())
10261           T = MPT->getPointeeType();
10262         if (auto *FPT = T->getAs<FunctionProtoType>())
10263           if (FPT->isNothrow())
10264             return true;
10265         return false;
10266       };
10267 
10268       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10269       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10270       for (QualType T : FPT->param_types())
10271         AnyNoexcept |= HasNoexcept(T);
10272       if (AnyNoexcept)
10273         Diag(NewFD->getLocation(),
10274              diag::warn_cxx17_compat_exception_spec_in_signature)
10275             << NewFD;
10276     }
10277 
10278     if (!Redeclaration && LangOpts.CUDA)
10279       checkCUDATargetOverload(NewFD, Previous);
10280   }
10281   return Redeclaration;
10282 }
10283 
10284 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10285   // C++11 [basic.start.main]p3:
10286   //   A program that [...] declares main to be inline, static or
10287   //   constexpr is ill-formed.
10288   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10289   //   appear in a declaration of main.
10290   // static main is not an error under C99, but we should warn about it.
10291   // We accept _Noreturn main as an extension.
10292   if (FD->getStorageClass() == SC_Static)
10293     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10294          ? diag::err_static_main : diag::warn_static_main)
10295       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10296   if (FD->isInlineSpecified())
10297     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10298       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10299   if (DS.isNoreturnSpecified()) {
10300     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10301     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10302     Diag(NoreturnLoc, diag::ext_noreturn_main);
10303     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10304       << FixItHint::CreateRemoval(NoreturnRange);
10305   }
10306   if (FD->isConstexpr()) {
10307     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10308       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10309     FD->setConstexpr(false);
10310   }
10311 
10312   if (getLangOpts().OpenCL) {
10313     Diag(FD->getLocation(), diag::err_opencl_no_main)
10314         << FD->hasAttr<OpenCLKernelAttr>();
10315     FD->setInvalidDecl();
10316     return;
10317   }
10318 
10319   QualType T = FD->getType();
10320   assert(T->isFunctionType() && "function decl is not of function type");
10321   const FunctionType* FT = T->castAs<FunctionType>();
10322 
10323   // Set default calling convention for main()
10324   if (FT->getCallConv() != CC_C) {
10325     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10326     FD->setType(QualType(FT, 0));
10327     T = Context.getCanonicalType(FD->getType());
10328   }
10329 
10330   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10331     // In C with GNU extensions we allow main() to have non-integer return
10332     // type, but we should warn about the extension, and we disable the
10333     // implicit-return-zero rule.
10334 
10335     // GCC in C mode accepts qualified 'int'.
10336     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10337       FD->setHasImplicitReturnZero(true);
10338     else {
10339       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10340       SourceRange RTRange = FD->getReturnTypeSourceRange();
10341       if (RTRange.isValid())
10342         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10343             << FixItHint::CreateReplacement(RTRange, "int");
10344     }
10345   } else {
10346     // In C and C++, main magically returns 0 if you fall off the end;
10347     // set the flag which tells us that.
10348     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10349 
10350     // All the standards say that main() should return 'int'.
10351     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10352       FD->setHasImplicitReturnZero(true);
10353     else {
10354       // Otherwise, this is just a flat-out error.
10355       SourceRange RTRange = FD->getReturnTypeSourceRange();
10356       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10357           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10358                                 : FixItHint());
10359       FD->setInvalidDecl(true);
10360     }
10361   }
10362 
10363   // Treat protoless main() as nullary.
10364   if (isa<FunctionNoProtoType>(FT)) return;
10365 
10366   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10367   unsigned nparams = FTP->getNumParams();
10368   assert(FD->getNumParams() == nparams);
10369 
10370   bool HasExtraParameters = (nparams > 3);
10371 
10372   if (FTP->isVariadic()) {
10373     Diag(FD->getLocation(), diag::ext_variadic_main);
10374     // FIXME: if we had information about the location of the ellipsis, we
10375     // could add a FixIt hint to remove it as a parameter.
10376   }
10377 
10378   // Darwin passes an undocumented fourth argument of type char**.  If
10379   // other platforms start sprouting these, the logic below will start
10380   // getting shifty.
10381   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10382     HasExtraParameters = false;
10383 
10384   if (HasExtraParameters) {
10385     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10386     FD->setInvalidDecl(true);
10387     nparams = 3;
10388   }
10389 
10390   // FIXME: a lot of the following diagnostics would be improved
10391   // if we had some location information about types.
10392 
10393   QualType CharPP =
10394     Context.getPointerType(Context.getPointerType(Context.CharTy));
10395   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10396 
10397   for (unsigned i = 0; i < nparams; ++i) {
10398     QualType AT = FTP->getParamType(i);
10399 
10400     bool mismatch = true;
10401 
10402     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10403       mismatch = false;
10404     else if (Expected[i] == CharPP) {
10405       // As an extension, the following forms are okay:
10406       //   char const **
10407       //   char const * const *
10408       //   char * const *
10409 
10410       QualifierCollector qs;
10411       const PointerType* PT;
10412       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10413           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10414           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10415                               Context.CharTy)) {
10416         qs.removeConst();
10417         mismatch = !qs.empty();
10418       }
10419     }
10420 
10421     if (mismatch) {
10422       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10423       // TODO: suggest replacing given type with expected type
10424       FD->setInvalidDecl(true);
10425     }
10426   }
10427 
10428   if (nparams == 1 && !FD->isInvalidDecl()) {
10429     Diag(FD->getLocation(), diag::warn_main_one_arg);
10430   }
10431 
10432   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10433     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10434     FD->setInvalidDecl();
10435   }
10436 }
10437 
10438 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10439   QualType T = FD->getType();
10440   assert(T->isFunctionType() && "function decl is not of function type");
10441   const FunctionType *FT = T->castAs<FunctionType>();
10442 
10443   // Set an implicit return of 'zero' if the function can return some integral,
10444   // enumeration, pointer or nullptr type.
10445   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10446       FT->getReturnType()->isAnyPointerType() ||
10447       FT->getReturnType()->isNullPtrType())
10448     // DllMain is exempt because a return value of zero means it failed.
10449     if (FD->getName() != "DllMain")
10450       FD->setHasImplicitReturnZero(true);
10451 
10452   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10453     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10454     FD->setInvalidDecl();
10455   }
10456 }
10457 
10458 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10459   // FIXME: Need strict checking.  In C89, we need to check for
10460   // any assignment, increment, decrement, function-calls, or
10461   // commas outside of a sizeof.  In C99, it's the same list,
10462   // except that the aforementioned are allowed in unevaluated
10463   // expressions.  Everything else falls under the
10464   // "may accept other forms of constant expressions" exception.
10465   // (We never end up here for C++, so the constant expression
10466   // rules there don't matter.)
10467   const Expr *Culprit;
10468   if (Init->isConstantInitializer(Context, false, &Culprit))
10469     return false;
10470   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10471     << Culprit->getSourceRange();
10472   return true;
10473 }
10474 
10475 namespace {
10476   // Visits an initialization expression to see if OrigDecl is evaluated in
10477   // its own initialization and throws a warning if it does.
10478   class SelfReferenceChecker
10479       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10480     Sema &S;
10481     Decl *OrigDecl;
10482     bool isRecordType;
10483     bool isPODType;
10484     bool isReferenceType;
10485 
10486     bool isInitList;
10487     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10488 
10489   public:
10490     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10491 
10492     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10493                                                     S(S), OrigDecl(OrigDecl) {
10494       isPODType = false;
10495       isRecordType = false;
10496       isReferenceType = false;
10497       isInitList = false;
10498       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10499         isPODType = VD->getType().isPODType(S.Context);
10500         isRecordType = VD->getType()->isRecordType();
10501         isReferenceType = VD->getType()->isReferenceType();
10502       }
10503     }
10504 
10505     // For most expressions, just call the visitor.  For initializer lists,
10506     // track the index of the field being initialized since fields are
10507     // initialized in order allowing use of previously initialized fields.
10508     void CheckExpr(Expr *E) {
10509       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10510       if (!InitList) {
10511         Visit(E);
10512         return;
10513       }
10514 
10515       // Track and increment the index here.
10516       isInitList = true;
10517       InitFieldIndex.push_back(0);
10518       for (auto Child : InitList->children()) {
10519         CheckExpr(cast<Expr>(Child));
10520         ++InitFieldIndex.back();
10521       }
10522       InitFieldIndex.pop_back();
10523     }
10524 
10525     // Returns true if MemberExpr is checked and no further checking is needed.
10526     // Returns false if additional checking is required.
10527     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10528       llvm::SmallVector<FieldDecl*, 4> Fields;
10529       Expr *Base = E;
10530       bool ReferenceField = false;
10531 
10532       // Get the field members used.
10533       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10534         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10535         if (!FD)
10536           return false;
10537         Fields.push_back(FD);
10538         if (FD->getType()->isReferenceType())
10539           ReferenceField = true;
10540         Base = ME->getBase()->IgnoreParenImpCasts();
10541       }
10542 
10543       // Keep checking only if the base Decl is the same.
10544       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10545       if (!DRE || DRE->getDecl() != OrigDecl)
10546         return false;
10547 
10548       // A reference field can be bound to an unininitialized field.
10549       if (CheckReference && !ReferenceField)
10550         return true;
10551 
10552       // Convert FieldDecls to their index number.
10553       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10554       for (const FieldDecl *I : llvm::reverse(Fields))
10555         UsedFieldIndex.push_back(I->getFieldIndex());
10556 
10557       // See if a warning is needed by checking the first difference in index
10558       // numbers.  If field being used has index less than the field being
10559       // initialized, then the use is safe.
10560       for (auto UsedIter = UsedFieldIndex.begin(),
10561                 UsedEnd = UsedFieldIndex.end(),
10562                 OrigIter = InitFieldIndex.begin(),
10563                 OrigEnd = InitFieldIndex.end();
10564            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10565         if (*UsedIter < *OrigIter)
10566           return true;
10567         if (*UsedIter > *OrigIter)
10568           break;
10569       }
10570 
10571       // TODO: Add a different warning which will print the field names.
10572       HandleDeclRefExpr(DRE);
10573       return true;
10574     }
10575 
10576     // For most expressions, the cast is directly above the DeclRefExpr.
10577     // For conditional operators, the cast can be outside the conditional
10578     // operator if both expressions are DeclRefExpr's.
10579     void HandleValue(Expr *E) {
10580       E = E->IgnoreParens();
10581       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10582         HandleDeclRefExpr(DRE);
10583         return;
10584       }
10585 
10586       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10587         Visit(CO->getCond());
10588         HandleValue(CO->getTrueExpr());
10589         HandleValue(CO->getFalseExpr());
10590         return;
10591       }
10592 
10593       if (BinaryConditionalOperator *BCO =
10594               dyn_cast<BinaryConditionalOperator>(E)) {
10595         Visit(BCO->getCond());
10596         HandleValue(BCO->getFalseExpr());
10597         return;
10598       }
10599 
10600       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10601         HandleValue(OVE->getSourceExpr());
10602         return;
10603       }
10604 
10605       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10606         if (BO->getOpcode() == BO_Comma) {
10607           Visit(BO->getLHS());
10608           HandleValue(BO->getRHS());
10609           return;
10610         }
10611       }
10612 
10613       if (isa<MemberExpr>(E)) {
10614         if (isInitList) {
10615           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10616                                       false /*CheckReference*/))
10617             return;
10618         }
10619 
10620         Expr *Base = E->IgnoreParenImpCasts();
10621         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10622           // Check for static member variables and don't warn on them.
10623           if (!isa<FieldDecl>(ME->getMemberDecl()))
10624             return;
10625           Base = ME->getBase()->IgnoreParenImpCasts();
10626         }
10627         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10628           HandleDeclRefExpr(DRE);
10629         return;
10630       }
10631 
10632       Visit(E);
10633     }
10634 
10635     // Reference types not handled in HandleValue are handled here since all
10636     // uses of references are bad, not just r-value uses.
10637     void VisitDeclRefExpr(DeclRefExpr *E) {
10638       if (isReferenceType)
10639         HandleDeclRefExpr(E);
10640     }
10641 
10642     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10643       if (E->getCastKind() == CK_LValueToRValue) {
10644         HandleValue(E->getSubExpr());
10645         return;
10646       }
10647 
10648       Inherited::VisitImplicitCastExpr(E);
10649     }
10650 
10651     void VisitMemberExpr(MemberExpr *E) {
10652       if (isInitList) {
10653         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10654           return;
10655       }
10656 
10657       // Don't warn on arrays since they can be treated as pointers.
10658       if (E->getType()->canDecayToPointerType()) return;
10659 
10660       // Warn when a non-static method call is followed by non-static member
10661       // field accesses, which is followed by a DeclRefExpr.
10662       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10663       bool Warn = (MD && !MD->isStatic());
10664       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10665       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10666         if (!isa<FieldDecl>(ME->getMemberDecl()))
10667           Warn = false;
10668         Base = ME->getBase()->IgnoreParenImpCasts();
10669       }
10670 
10671       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10672         if (Warn)
10673           HandleDeclRefExpr(DRE);
10674         return;
10675       }
10676 
10677       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10678       // Visit that expression.
10679       Visit(Base);
10680     }
10681 
10682     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10683       Expr *Callee = E->getCallee();
10684 
10685       if (isa<UnresolvedLookupExpr>(Callee))
10686         return Inherited::VisitCXXOperatorCallExpr(E);
10687 
10688       Visit(Callee);
10689       for (auto Arg: E->arguments())
10690         HandleValue(Arg->IgnoreParenImpCasts());
10691     }
10692 
10693     void VisitUnaryOperator(UnaryOperator *E) {
10694       // For POD record types, addresses of its own members are well-defined.
10695       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10696           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10697         if (!isPODType)
10698           HandleValue(E->getSubExpr());
10699         return;
10700       }
10701 
10702       if (E->isIncrementDecrementOp()) {
10703         HandleValue(E->getSubExpr());
10704         return;
10705       }
10706 
10707       Inherited::VisitUnaryOperator(E);
10708     }
10709 
10710     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10711 
10712     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10713       if (E->getConstructor()->isCopyConstructor()) {
10714         Expr *ArgExpr = E->getArg(0);
10715         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10716           if (ILE->getNumInits() == 1)
10717             ArgExpr = ILE->getInit(0);
10718         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10719           if (ICE->getCastKind() == CK_NoOp)
10720             ArgExpr = ICE->getSubExpr();
10721         HandleValue(ArgExpr);
10722         return;
10723       }
10724       Inherited::VisitCXXConstructExpr(E);
10725     }
10726 
10727     void VisitCallExpr(CallExpr *E) {
10728       // Treat std::move as a use.
10729       if (E->isCallToStdMove()) {
10730         HandleValue(E->getArg(0));
10731         return;
10732       }
10733 
10734       Inherited::VisitCallExpr(E);
10735     }
10736 
10737     void VisitBinaryOperator(BinaryOperator *E) {
10738       if (E->isCompoundAssignmentOp()) {
10739         HandleValue(E->getLHS());
10740         Visit(E->getRHS());
10741         return;
10742       }
10743 
10744       Inherited::VisitBinaryOperator(E);
10745     }
10746 
10747     // A custom visitor for BinaryConditionalOperator is needed because the
10748     // regular visitor would check the condition and true expression separately
10749     // but both point to the same place giving duplicate diagnostics.
10750     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10751       Visit(E->getCond());
10752       Visit(E->getFalseExpr());
10753     }
10754 
10755     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10756       Decl* ReferenceDecl = DRE->getDecl();
10757       if (OrigDecl != ReferenceDecl) return;
10758       unsigned diag;
10759       if (isReferenceType) {
10760         diag = diag::warn_uninit_self_reference_in_reference_init;
10761       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10762         diag = diag::warn_static_self_reference_in_init;
10763       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10764                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10765                  DRE->getDecl()->getType()->isRecordType()) {
10766         diag = diag::warn_uninit_self_reference_in_init;
10767       } else {
10768         // Local variables will be handled by the CFG analysis.
10769         return;
10770       }
10771 
10772       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10773                             S.PDiag(diag)
10774                                 << DRE->getDecl() << OrigDecl->getLocation()
10775                                 << DRE->getSourceRange());
10776     }
10777   };
10778 
10779   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10780   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10781                                  bool DirectInit) {
10782     // Parameters arguments are occassionially constructed with itself,
10783     // for instance, in recursive functions.  Skip them.
10784     if (isa<ParmVarDecl>(OrigDecl))
10785       return;
10786 
10787     E = E->IgnoreParens();
10788 
10789     // Skip checking T a = a where T is not a record or reference type.
10790     // Doing so is a way to silence uninitialized warnings.
10791     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10792       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10793         if (ICE->getCastKind() == CK_LValueToRValue)
10794           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10795             if (DRE->getDecl() == OrigDecl)
10796               return;
10797 
10798     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10799   }
10800 } // end anonymous namespace
10801 
10802 namespace {
10803   // Simple wrapper to add the name of a variable or (if no variable is
10804   // available) a DeclarationName into a diagnostic.
10805   struct VarDeclOrName {
10806     VarDecl *VDecl;
10807     DeclarationName Name;
10808 
10809     friend const Sema::SemaDiagnosticBuilder &
10810     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10811       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10812     }
10813   };
10814 } // end anonymous namespace
10815 
10816 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10817                                             DeclarationName Name, QualType Type,
10818                                             TypeSourceInfo *TSI,
10819                                             SourceRange Range, bool DirectInit,
10820                                             Expr *&Init) {
10821   bool IsInitCapture = !VDecl;
10822   assert((!VDecl || !VDecl->isInitCapture()) &&
10823          "init captures are expected to be deduced prior to initialization");
10824 
10825   VarDeclOrName VN{VDecl, Name};
10826 
10827   DeducedType *Deduced = Type->getContainedDeducedType();
10828   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10829 
10830   // C++11 [dcl.spec.auto]p3
10831   if (!Init) {
10832     assert(VDecl && "no init for init capture deduction?");
10833 
10834     // Except for class argument deduction, and then for an initializing
10835     // declaration only, i.e. no static at class scope or extern.
10836     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10837         VDecl->hasExternalStorage() ||
10838         VDecl->isStaticDataMember()) {
10839       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10840         << VDecl->getDeclName() << Type;
10841       return QualType();
10842     }
10843   }
10844 
10845   ArrayRef<Expr*> DeduceInits;
10846   if (Init)
10847     DeduceInits = Init;
10848 
10849   if (DirectInit) {
10850     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10851       DeduceInits = PL->exprs();
10852   }
10853 
10854   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10855     assert(VDecl && "non-auto type for init capture deduction?");
10856     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10857     InitializationKind Kind = InitializationKind::CreateForInit(
10858         VDecl->getLocation(), DirectInit, Init);
10859     // FIXME: Initialization should not be taking a mutable list of inits.
10860     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10861     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10862                                                        InitsCopy);
10863   }
10864 
10865   if (DirectInit) {
10866     if (auto *IL = dyn_cast<InitListExpr>(Init))
10867       DeduceInits = IL->inits();
10868   }
10869 
10870   // Deduction only works if we have exactly one source expression.
10871   if (DeduceInits.empty()) {
10872     // It isn't possible to write this directly, but it is possible to
10873     // end up in this situation with "auto x(some_pack...);"
10874     Diag(Init->getBeginLoc(), IsInitCapture
10875                                   ? diag::err_init_capture_no_expression
10876                                   : diag::err_auto_var_init_no_expression)
10877         << VN << Type << Range;
10878     return QualType();
10879   }
10880 
10881   if (DeduceInits.size() > 1) {
10882     Diag(DeduceInits[1]->getBeginLoc(),
10883          IsInitCapture ? diag::err_init_capture_multiple_expressions
10884                        : diag::err_auto_var_init_multiple_expressions)
10885         << VN << Type << Range;
10886     return QualType();
10887   }
10888 
10889   Expr *DeduceInit = DeduceInits[0];
10890   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10891     Diag(Init->getBeginLoc(), IsInitCapture
10892                                   ? diag::err_init_capture_paren_braces
10893                                   : diag::err_auto_var_init_paren_braces)
10894         << isa<InitListExpr>(Init) << VN << Type << Range;
10895     return QualType();
10896   }
10897 
10898   // Expressions default to 'id' when we're in a debugger.
10899   bool DefaultedAnyToId = false;
10900   if (getLangOpts().DebuggerCastResultToId &&
10901       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10902     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10903     if (Result.isInvalid()) {
10904       return QualType();
10905     }
10906     Init = Result.get();
10907     DefaultedAnyToId = true;
10908   }
10909 
10910   // C++ [dcl.decomp]p1:
10911   //   If the assignment-expression [...] has array type A and no ref-qualifier
10912   //   is present, e has type cv A
10913   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10914       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10915       DeduceInit->getType()->isConstantArrayType())
10916     return Context.getQualifiedType(DeduceInit->getType(),
10917                                     Type.getQualifiers());
10918 
10919   QualType DeducedType;
10920   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10921     if (!IsInitCapture)
10922       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10923     else if (isa<InitListExpr>(Init))
10924       Diag(Range.getBegin(),
10925            diag::err_init_capture_deduction_failure_from_init_list)
10926           << VN
10927           << (DeduceInit->getType().isNull() ? TSI->getType()
10928                                              : DeduceInit->getType())
10929           << DeduceInit->getSourceRange();
10930     else
10931       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10932           << VN << TSI->getType()
10933           << (DeduceInit->getType().isNull() ? TSI->getType()
10934                                              : DeduceInit->getType())
10935           << DeduceInit->getSourceRange();
10936   } else
10937     Init = DeduceInit;
10938 
10939   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10940   // 'id' instead of a specific object type prevents most of our usual
10941   // checks.
10942   // We only want to warn outside of template instantiations, though:
10943   // inside a template, the 'id' could have come from a parameter.
10944   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10945       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10946     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10947     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10948   }
10949 
10950   return DeducedType;
10951 }
10952 
10953 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10954                                          Expr *&Init) {
10955   QualType DeducedType = deduceVarTypeFromInitializer(
10956       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10957       VDecl->getSourceRange(), DirectInit, Init);
10958   if (DeducedType.isNull()) {
10959     VDecl->setInvalidDecl();
10960     return true;
10961   }
10962 
10963   VDecl->setType(DeducedType);
10964   assert(VDecl->isLinkageValid());
10965 
10966   // In ARC, infer lifetime.
10967   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10968     VDecl->setInvalidDecl();
10969 
10970   // If this is a redeclaration, check that the type we just deduced matches
10971   // the previously declared type.
10972   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10973     // We never need to merge the type, because we cannot form an incomplete
10974     // array of auto, nor deduce such a type.
10975     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10976   }
10977 
10978   // Check the deduced type is valid for a variable declaration.
10979   CheckVariableDeclarationType(VDecl);
10980   return VDecl->isInvalidDecl();
10981 }
10982 
10983 /// AddInitializerToDecl - Adds the initializer Init to the
10984 /// declaration dcl. If DirectInit is true, this is C++ direct
10985 /// initialization rather than copy initialization.
10986 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10987   // If there is no declaration, there was an error parsing it.  Just ignore
10988   // the initializer.
10989   if (!RealDecl || RealDecl->isInvalidDecl()) {
10990     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10991     return;
10992   }
10993 
10994   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10995     // Pure-specifiers are handled in ActOnPureSpecifier.
10996     Diag(Method->getLocation(), diag::err_member_function_initialization)
10997       << Method->getDeclName() << Init->getSourceRange();
10998     Method->setInvalidDecl();
10999     return;
11000   }
11001 
11002   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11003   if (!VDecl) {
11004     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11005     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11006     RealDecl->setInvalidDecl();
11007     return;
11008   }
11009 
11010   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11011   if (VDecl->getType()->isUndeducedType()) {
11012     // Attempt typo correction early so that the type of the init expression can
11013     // be deduced based on the chosen correction if the original init contains a
11014     // TypoExpr.
11015     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11016     if (!Res.isUsable()) {
11017       RealDecl->setInvalidDecl();
11018       return;
11019     }
11020     Init = Res.get();
11021 
11022     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11023       return;
11024   }
11025 
11026   // dllimport cannot be used on variable definitions.
11027   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11028     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11029     VDecl->setInvalidDecl();
11030     return;
11031   }
11032 
11033   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11034     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11035     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11036     VDecl->setInvalidDecl();
11037     return;
11038   }
11039 
11040   if (!VDecl->getType()->isDependentType()) {
11041     // A definition must end up with a complete type, which means it must be
11042     // complete with the restriction that an array type might be completed by
11043     // the initializer; note that later code assumes this restriction.
11044     QualType BaseDeclType = VDecl->getType();
11045     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11046       BaseDeclType = Array->getElementType();
11047     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11048                             diag::err_typecheck_decl_incomplete_type)) {
11049       RealDecl->setInvalidDecl();
11050       return;
11051     }
11052 
11053     // The variable can not have an abstract class type.
11054     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11055                                diag::err_abstract_type_in_decl,
11056                                AbstractVariableType))
11057       VDecl->setInvalidDecl();
11058   }
11059 
11060   // If adding the initializer will turn this declaration into a definition,
11061   // and we already have a definition for this variable, diagnose or otherwise
11062   // handle the situation.
11063   VarDecl *Def;
11064   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11065       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11066       !VDecl->isThisDeclarationADemotedDefinition() &&
11067       checkVarDeclRedefinition(Def, VDecl))
11068     return;
11069 
11070   if (getLangOpts().CPlusPlus) {
11071     // C++ [class.static.data]p4
11072     //   If a static data member is of const integral or const
11073     //   enumeration type, its declaration in the class definition can
11074     //   specify a constant-initializer which shall be an integral
11075     //   constant expression (5.19). In that case, the member can appear
11076     //   in integral constant expressions. The member shall still be
11077     //   defined in a namespace scope if it is used in the program and the
11078     //   namespace scope definition shall not contain an initializer.
11079     //
11080     // We already performed a redefinition check above, but for static
11081     // data members we also need to check whether there was an in-class
11082     // declaration with an initializer.
11083     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11084       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11085           << VDecl->getDeclName();
11086       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11087            diag::note_previous_initializer)
11088           << 0;
11089       return;
11090     }
11091 
11092     if (VDecl->hasLocalStorage())
11093       setFunctionHasBranchProtectedScope();
11094 
11095     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11096       VDecl->setInvalidDecl();
11097       return;
11098     }
11099   }
11100 
11101   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11102   // a kernel function cannot be initialized."
11103   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11104     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11105     VDecl->setInvalidDecl();
11106     return;
11107   }
11108 
11109   // Get the decls type and save a reference for later, since
11110   // CheckInitializerTypes may change it.
11111   QualType DclT = VDecl->getType(), SavT = DclT;
11112 
11113   // Expressions default to 'id' when we're in a debugger
11114   // and we are assigning it to a variable of Objective-C pointer type.
11115   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11116       Init->getType() == Context.UnknownAnyTy) {
11117     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11118     if (Result.isInvalid()) {
11119       VDecl->setInvalidDecl();
11120       return;
11121     }
11122     Init = Result.get();
11123   }
11124 
11125   // Perform the initialization.
11126   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11127   if (!VDecl->isInvalidDecl()) {
11128     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11129     InitializationKind Kind = InitializationKind::CreateForInit(
11130         VDecl->getLocation(), DirectInit, Init);
11131 
11132     MultiExprArg Args = Init;
11133     if (CXXDirectInit)
11134       Args = MultiExprArg(CXXDirectInit->getExprs(),
11135                           CXXDirectInit->getNumExprs());
11136 
11137     // Try to correct any TypoExprs in the initialization arguments.
11138     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11139       ExprResult Res = CorrectDelayedTyposInExpr(
11140           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11141             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11142             return Init.Failed() ? ExprError() : E;
11143           });
11144       if (Res.isInvalid()) {
11145         VDecl->setInvalidDecl();
11146       } else if (Res.get() != Args[Idx]) {
11147         Args[Idx] = Res.get();
11148       }
11149     }
11150     if (VDecl->isInvalidDecl())
11151       return;
11152 
11153     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11154                                    /*TopLevelOfInitList=*/false,
11155                                    /*TreatUnavailableAsInvalid=*/false);
11156     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11157     if (Result.isInvalid()) {
11158       VDecl->setInvalidDecl();
11159       return;
11160     }
11161 
11162     Init = Result.getAs<Expr>();
11163   }
11164 
11165   // Check for self-references within variable initializers.
11166   // Variables declared within a function/method body (except for references)
11167   // are handled by a dataflow analysis.
11168   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11169       VDecl->getType()->isReferenceType()) {
11170     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11171   }
11172 
11173   // If the type changed, it means we had an incomplete type that was
11174   // completed by the initializer. For example:
11175   //   int ary[] = { 1, 3, 5 };
11176   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11177   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11178     VDecl->setType(DclT);
11179 
11180   if (!VDecl->isInvalidDecl()) {
11181     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11182 
11183     if (VDecl->hasAttr<BlocksAttr>())
11184       checkRetainCycles(VDecl, Init);
11185 
11186     // It is safe to assign a weak reference into a strong variable.
11187     // Although this code can still have problems:
11188     //   id x = self.weakProp;
11189     //   id y = self.weakProp;
11190     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11191     // paths through the function. This should be revisited if
11192     // -Wrepeated-use-of-weak is made flow-sensitive.
11193     if (FunctionScopeInfo *FSI = getCurFunction())
11194       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11195            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11196           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11197                            Init->getBeginLoc()))
11198         FSI->markSafeWeakUse(Init);
11199   }
11200 
11201   // The initialization is usually a full-expression.
11202   //
11203   // FIXME: If this is a braced initialization of an aggregate, it is not
11204   // an expression, and each individual field initializer is a separate
11205   // full-expression. For instance, in:
11206   //
11207   //   struct Temp { ~Temp(); };
11208   //   struct S { S(Temp); };
11209   //   struct T { S a, b; } t = { Temp(), Temp() }
11210   //
11211   // we should destroy the first Temp before constructing the second.
11212   ExprResult Result =
11213       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11214                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11215   if (Result.isInvalid()) {
11216     VDecl->setInvalidDecl();
11217     return;
11218   }
11219   Init = Result.get();
11220 
11221   // Attach the initializer to the decl.
11222   VDecl->setInit(Init);
11223 
11224   if (VDecl->isLocalVarDecl()) {
11225     // Don't check the initializer if the declaration is malformed.
11226     if (VDecl->isInvalidDecl()) {
11227       // do nothing
11228 
11229     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11230     // This is true even in OpenCL C++.
11231     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11232       CheckForConstantInitializer(Init, DclT);
11233 
11234     // Otherwise, C++ does not restrict the initializer.
11235     } else if (getLangOpts().CPlusPlus) {
11236       // do nothing
11237 
11238     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11239     // static storage duration shall be constant expressions or string literals.
11240     } else if (VDecl->getStorageClass() == SC_Static) {
11241       CheckForConstantInitializer(Init, DclT);
11242 
11243     // C89 is stricter than C99 for aggregate initializers.
11244     // C89 6.5.7p3: All the expressions [...] in an initializer list
11245     // for an object that has aggregate or union type shall be
11246     // constant expressions.
11247     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11248                isa<InitListExpr>(Init)) {
11249       const Expr *Culprit;
11250       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11251         Diag(Culprit->getExprLoc(),
11252              diag::ext_aggregate_init_not_constant)
11253           << Culprit->getSourceRange();
11254       }
11255     }
11256   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11257              VDecl->getLexicalDeclContext()->isRecord()) {
11258     // This is an in-class initialization for a static data member, e.g.,
11259     //
11260     // struct S {
11261     //   static const int value = 17;
11262     // };
11263 
11264     // C++ [class.mem]p4:
11265     //   A member-declarator can contain a constant-initializer only
11266     //   if it declares a static member (9.4) of const integral or
11267     //   const enumeration type, see 9.4.2.
11268     //
11269     // C++11 [class.static.data]p3:
11270     //   If a non-volatile non-inline const static data member is of integral
11271     //   or enumeration type, its declaration in the class definition can
11272     //   specify a brace-or-equal-initializer in which every initializer-clause
11273     //   that is an assignment-expression is a constant expression. A static
11274     //   data member of literal type can be declared in the class definition
11275     //   with the constexpr specifier; if so, its declaration shall specify a
11276     //   brace-or-equal-initializer in which every initializer-clause that is
11277     //   an assignment-expression is a constant expression.
11278 
11279     // Do nothing on dependent types.
11280     if (DclT->isDependentType()) {
11281 
11282     // Allow any 'static constexpr' members, whether or not they are of literal
11283     // type. We separately check that every constexpr variable is of literal
11284     // type.
11285     } else if (VDecl->isConstexpr()) {
11286 
11287     // Require constness.
11288     } else if (!DclT.isConstQualified()) {
11289       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11290         << Init->getSourceRange();
11291       VDecl->setInvalidDecl();
11292 
11293     // We allow integer constant expressions in all cases.
11294     } else if (DclT->isIntegralOrEnumerationType()) {
11295       // Check whether the expression is a constant expression.
11296       SourceLocation Loc;
11297       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11298         // In C++11, a non-constexpr const static data member with an
11299         // in-class initializer cannot be volatile.
11300         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11301       else if (Init->isValueDependent())
11302         ; // Nothing to check.
11303       else if (Init->isIntegerConstantExpr(Context, &Loc))
11304         ; // Ok, it's an ICE!
11305       else if (Init->getType()->isScopedEnumeralType() &&
11306                Init->isCXX11ConstantExpr(Context))
11307         ; // Ok, it is a scoped-enum constant expression.
11308       else if (Init->isEvaluatable(Context)) {
11309         // If we can constant fold the initializer through heroics, accept it,
11310         // but report this as a use of an extension for -pedantic.
11311         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11312           << Init->getSourceRange();
11313       } else {
11314         // Otherwise, this is some crazy unknown case.  Report the issue at the
11315         // location provided by the isIntegerConstantExpr failed check.
11316         Diag(Loc, diag::err_in_class_initializer_non_constant)
11317           << Init->getSourceRange();
11318         VDecl->setInvalidDecl();
11319       }
11320 
11321     // We allow foldable floating-point constants as an extension.
11322     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11323       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11324       // it anyway and provide a fixit to add the 'constexpr'.
11325       if (getLangOpts().CPlusPlus11) {
11326         Diag(VDecl->getLocation(),
11327              diag::ext_in_class_initializer_float_type_cxx11)
11328             << DclT << Init->getSourceRange();
11329         Diag(VDecl->getBeginLoc(),
11330              diag::note_in_class_initializer_float_type_cxx11)
11331             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11332       } else {
11333         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11334           << DclT << Init->getSourceRange();
11335 
11336         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11337           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11338             << Init->getSourceRange();
11339           VDecl->setInvalidDecl();
11340         }
11341       }
11342 
11343     // Suggest adding 'constexpr' in C++11 for literal types.
11344     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11345       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11346           << DclT << Init->getSourceRange()
11347           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11348       VDecl->setConstexpr(true);
11349 
11350     } else {
11351       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11352         << DclT << Init->getSourceRange();
11353       VDecl->setInvalidDecl();
11354     }
11355   } else if (VDecl->isFileVarDecl()) {
11356     // In C, extern is typically used to avoid tentative definitions when
11357     // declaring variables in headers, but adding an intializer makes it a
11358     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11359     // In C++, extern is often used to give implictly static const variables
11360     // external linkage, so don't warn in that case. If selectany is present,
11361     // this might be header code intended for C and C++ inclusion, so apply the
11362     // C++ rules.
11363     if (VDecl->getStorageClass() == SC_Extern &&
11364         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11365          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11366         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11367         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11368       Diag(VDecl->getLocation(), diag::warn_extern_init);
11369 
11370     // C99 6.7.8p4. All file scoped initializers need to be constant.
11371     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11372       CheckForConstantInitializer(Init, DclT);
11373   }
11374 
11375   // We will represent direct-initialization similarly to copy-initialization:
11376   //    int x(1);  -as-> int x = 1;
11377   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11378   //
11379   // Clients that want to distinguish between the two forms, can check for
11380   // direct initializer using VarDecl::getInitStyle().
11381   // A major benefit is that clients that don't particularly care about which
11382   // exactly form was it (like the CodeGen) can handle both cases without
11383   // special case code.
11384 
11385   // C++ 8.5p11:
11386   // The form of initialization (using parentheses or '=') is generally
11387   // insignificant, but does matter when the entity being initialized has a
11388   // class type.
11389   if (CXXDirectInit) {
11390     assert(DirectInit && "Call-style initializer must be direct init.");
11391     VDecl->setInitStyle(VarDecl::CallInit);
11392   } else if (DirectInit) {
11393     // This must be list-initialization. No other way is direct-initialization.
11394     VDecl->setInitStyle(VarDecl::ListInit);
11395   }
11396 
11397   CheckCompleteVariableDeclaration(VDecl);
11398 }
11399 
11400 /// ActOnInitializerError - Given that there was an error parsing an
11401 /// initializer for the given declaration, try to return to some form
11402 /// of sanity.
11403 void Sema::ActOnInitializerError(Decl *D) {
11404   // Our main concern here is re-establishing invariants like "a
11405   // variable's type is either dependent or complete".
11406   if (!D || D->isInvalidDecl()) return;
11407 
11408   VarDecl *VD = dyn_cast<VarDecl>(D);
11409   if (!VD) return;
11410 
11411   // Bindings are not usable if we can't make sense of the initializer.
11412   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11413     for (auto *BD : DD->bindings())
11414       BD->setInvalidDecl();
11415 
11416   // Auto types are meaningless if we can't make sense of the initializer.
11417   if (ParsingInitForAutoVars.count(D)) {
11418     D->setInvalidDecl();
11419     return;
11420   }
11421 
11422   QualType Ty = VD->getType();
11423   if (Ty->isDependentType()) return;
11424 
11425   // Require a complete type.
11426   if (RequireCompleteType(VD->getLocation(),
11427                           Context.getBaseElementType(Ty),
11428                           diag::err_typecheck_decl_incomplete_type)) {
11429     VD->setInvalidDecl();
11430     return;
11431   }
11432 
11433   // Require a non-abstract type.
11434   if (RequireNonAbstractType(VD->getLocation(), Ty,
11435                              diag::err_abstract_type_in_decl,
11436                              AbstractVariableType)) {
11437     VD->setInvalidDecl();
11438     return;
11439   }
11440 
11441   // Don't bother complaining about constructors or destructors,
11442   // though.
11443 }
11444 
11445 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11446   // If there is no declaration, there was an error parsing it. Just ignore it.
11447   if (!RealDecl)
11448     return;
11449 
11450   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11451     QualType Type = Var->getType();
11452 
11453     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11454     if (isa<DecompositionDecl>(RealDecl)) {
11455       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11456       Var->setInvalidDecl();
11457       return;
11458     }
11459 
11460     Expr *TmpInit = nullptr;
11461     if (Type->isUndeducedType() &&
11462         DeduceVariableDeclarationType(Var, false, TmpInit))
11463       return;
11464 
11465     // C++11 [class.static.data]p3: A static data member can be declared with
11466     // the constexpr specifier; if so, its declaration shall specify
11467     // a brace-or-equal-initializer.
11468     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11469     // the definition of a variable [...] or the declaration of a static data
11470     // member.
11471     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11472         !Var->isThisDeclarationADemotedDefinition()) {
11473       if (Var->isStaticDataMember()) {
11474         // C++1z removes the relevant rule; the in-class declaration is always
11475         // a definition there.
11476         if (!getLangOpts().CPlusPlus17) {
11477           Diag(Var->getLocation(),
11478                diag::err_constexpr_static_mem_var_requires_init)
11479             << Var->getDeclName();
11480           Var->setInvalidDecl();
11481           return;
11482         }
11483       } else {
11484         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11485         Var->setInvalidDecl();
11486         return;
11487       }
11488     }
11489 
11490     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11491     // be initialized.
11492     if (!Var->isInvalidDecl() &&
11493         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11494         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11495       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11496       Var->setInvalidDecl();
11497       return;
11498     }
11499 
11500     switch (Var->isThisDeclarationADefinition()) {
11501     case VarDecl::Definition:
11502       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11503         break;
11504 
11505       // We have an out-of-line definition of a static data member
11506       // that has an in-class initializer, so we type-check this like
11507       // a declaration.
11508       //
11509       LLVM_FALLTHROUGH;
11510 
11511     case VarDecl::DeclarationOnly:
11512       // It's only a declaration.
11513 
11514       // Block scope. C99 6.7p7: If an identifier for an object is
11515       // declared with no linkage (C99 6.2.2p6), the type for the
11516       // object shall be complete.
11517       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11518           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11519           RequireCompleteType(Var->getLocation(), Type,
11520                               diag::err_typecheck_decl_incomplete_type))
11521         Var->setInvalidDecl();
11522 
11523       // Make sure that the type is not abstract.
11524       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11525           RequireNonAbstractType(Var->getLocation(), Type,
11526                                  diag::err_abstract_type_in_decl,
11527                                  AbstractVariableType))
11528         Var->setInvalidDecl();
11529       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11530           Var->getStorageClass() == SC_PrivateExtern) {
11531         Diag(Var->getLocation(), diag::warn_private_extern);
11532         Diag(Var->getLocation(), diag::note_private_extern);
11533       }
11534 
11535       return;
11536 
11537     case VarDecl::TentativeDefinition:
11538       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11539       // object that has file scope without an initializer, and without a
11540       // storage-class specifier or with the storage-class specifier "static",
11541       // constitutes a tentative definition. Note: A tentative definition with
11542       // external linkage is valid (C99 6.2.2p5).
11543       if (!Var->isInvalidDecl()) {
11544         if (const IncompleteArrayType *ArrayT
11545                                     = Context.getAsIncompleteArrayType(Type)) {
11546           if (RequireCompleteType(Var->getLocation(),
11547                                   ArrayT->getElementType(),
11548                                   diag::err_illegal_decl_array_incomplete_type))
11549             Var->setInvalidDecl();
11550         } else if (Var->getStorageClass() == SC_Static) {
11551           // C99 6.9.2p3: If the declaration of an identifier for an object is
11552           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11553           // declared type shall not be an incomplete type.
11554           // NOTE: code such as the following
11555           //     static struct s;
11556           //     struct s { int a; };
11557           // is accepted by gcc. Hence here we issue a warning instead of
11558           // an error and we do not invalidate the static declaration.
11559           // NOTE: to avoid multiple warnings, only check the first declaration.
11560           if (Var->isFirstDecl())
11561             RequireCompleteType(Var->getLocation(), Type,
11562                                 diag::ext_typecheck_decl_incomplete_type);
11563         }
11564       }
11565 
11566       // Record the tentative definition; we're done.
11567       if (!Var->isInvalidDecl())
11568         TentativeDefinitions.push_back(Var);
11569       return;
11570     }
11571 
11572     // Provide a specific diagnostic for uninitialized variable
11573     // definitions with incomplete array type.
11574     if (Type->isIncompleteArrayType()) {
11575       Diag(Var->getLocation(),
11576            diag::err_typecheck_incomplete_array_needs_initializer);
11577       Var->setInvalidDecl();
11578       return;
11579     }
11580 
11581     // Provide a specific diagnostic for uninitialized variable
11582     // definitions with reference type.
11583     if (Type->isReferenceType()) {
11584       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11585         << Var->getDeclName()
11586         << SourceRange(Var->getLocation(), Var->getLocation());
11587       Var->setInvalidDecl();
11588       return;
11589     }
11590 
11591     // Do not attempt to type-check the default initializer for a
11592     // variable with dependent type.
11593     if (Type->isDependentType())
11594       return;
11595 
11596     if (Var->isInvalidDecl())
11597       return;
11598 
11599     if (!Var->hasAttr<AliasAttr>()) {
11600       if (RequireCompleteType(Var->getLocation(),
11601                               Context.getBaseElementType(Type),
11602                               diag::err_typecheck_decl_incomplete_type)) {
11603         Var->setInvalidDecl();
11604         return;
11605       }
11606     } else {
11607       return;
11608     }
11609 
11610     // The variable can not have an abstract class type.
11611     if (RequireNonAbstractType(Var->getLocation(), Type,
11612                                diag::err_abstract_type_in_decl,
11613                                AbstractVariableType)) {
11614       Var->setInvalidDecl();
11615       return;
11616     }
11617 
11618     // Check for jumps past the implicit initializer.  C++0x
11619     // clarifies that this applies to a "variable with automatic
11620     // storage duration", not a "local variable".
11621     // C++11 [stmt.dcl]p3
11622     //   A program that jumps from a point where a variable with automatic
11623     //   storage duration is not in scope to a point where it is in scope is
11624     //   ill-formed unless the variable has scalar type, class type with a
11625     //   trivial default constructor and a trivial destructor, a cv-qualified
11626     //   version of one of these types, or an array of one of the preceding
11627     //   types and is declared without an initializer.
11628     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11629       if (const RecordType *Record
11630             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11631         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11632         // Mark the function (if we're in one) for further checking even if the
11633         // looser rules of C++11 do not require such checks, so that we can
11634         // diagnose incompatibilities with C++98.
11635         if (!CXXRecord->isPOD())
11636           setFunctionHasBranchProtectedScope();
11637       }
11638     }
11639 
11640     // C++03 [dcl.init]p9:
11641     //   If no initializer is specified for an object, and the
11642     //   object is of (possibly cv-qualified) non-POD class type (or
11643     //   array thereof), the object shall be default-initialized; if
11644     //   the object is of const-qualified type, the underlying class
11645     //   type shall have a user-declared default
11646     //   constructor. Otherwise, if no initializer is specified for
11647     //   a non- static object, the object and its subobjects, if
11648     //   any, have an indeterminate initial value); if the object
11649     //   or any of its subobjects are of const-qualified type, the
11650     //   program is ill-formed.
11651     // C++0x [dcl.init]p11:
11652     //   If no initializer is specified for an object, the object is
11653     //   default-initialized; [...].
11654     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11655     InitializationKind Kind
11656       = InitializationKind::CreateDefault(Var->getLocation());
11657 
11658     InitializationSequence InitSeq(*this, Entity, Kind, None);
11659     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11660     if (Init.isInvalid())
11661       Var->setInvalidDecl();
11662     else if (Init.get()) {
11663       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11664       // This is important for template substitution.
11665       Var->setInitStyle(VarDecl::CallInit);
11666     }
11667 
11668     CheckCompleteVariableDeclaration(Var);
11669   }
11670 }
11671 
11672 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11673   // If there is no declaration, there was an error parsing it. Ignore it.
11674   if (!D)
11675     return;
11676 
11677   VarDecl *VD = dyn_cast<VarDecl>(D);
11678   if (!VD) {
11679     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11680     D->setInvalidDecl();
11681     return;
11682   }
11683 
11684   VD->setCXXForRangeDecl(true);
11685 
11686   // for-range-declaration cannot be given a storage class specifier.
11687   int Error = -1;
11688   switch (VD->getStorageClass()) {
11689   case SC_None:
11690     break;
11691   case SC_Extern:
11692     Error = 0;
11693     break;
11694   case SC_Static:
11695     Error = 1;
11696     break;
11697   case SC_PrivateExtern:
11698     Error = 2;
11699     break;
11700   case SC_Auto:
11701     Error = 3;
11702     break;
11703   case SC_Register:
11704     Error = 4;
11705     break;
11706   }
11707   if (Error != -1) {
11708     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11709       << VD->getDeclName() << Error;
11710     D->setInvalidDecl();
11711   }
11712 }
11713 
11714 StmtResult
11715 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11716                                  IdentifierInfo *Ident,
11717                                  ParsedAttributes &Attrs,
11718                                  SourceLocation AttrEnd) {
11719   // C++1y [stmt.iter]p1:
11720   //   A range-based for statement of the form
11721   //      for ( for-range-identifier : for-range-initializer ) statement
11722   //   is equivalent to
11723   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11724   DeclSpec DS(Attrs.getPool().getFactory());
11725 
11726   const char *PrevSpec;
11727   unsigned DiagID;
11728   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11729                      getPrintingPolicy());
11730 
11731   Declarator D(DS, DeclaratorContext::ForContext);
11732   D.SetIdentifier(Ident, IdentLoc);
11733   D.takeAttributes(Attrs, AttrEnd);
11734 
11735   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11736   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11737                 IdentLoc);
11738   Decl *Var = ActOnDeclarator(S, D);
11739   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11740   FinalizeDeclaration(Var);
11741   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11742                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11743 }
11744 
11745 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11746   if (var->isInvalidDecl()) return;
11747 
11748   if (getLangOpts().OpenCL) {
11749     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11750     // initialiser
11751     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11752         !var->hasInit()) {
11753       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11754           << 1 /*Init*/;
11755       var->setInvalidDecl();
11756       return;
11757     }
11758   }
11759 
11760   // In Objective-C, don't allow jumps past the implicit initialization of a
11761   // local retaining variable.
11762   if (getLangOpts().ObjC &&
11763       var->hasLocalStorage()) {
11764     switch (var->getType().getObjCLifetime()) {
11765     case Qualifiers::OCL_None:
11766     case Qualifiers::OCL_ExplicitNone:
11767     case Qualifiers::OCL_Autoreleasing:
11768       break;
11769 
11770     case Qualifiers::OCL_Weak:
11771     case Qualifiers::OCL_Strong:
11772       setFunctionHasBranchProtectedScope();
11773       break;
11774     }
11775   }
11776 
11777   if (var->hasLocalStorage() &&
11778       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11779     setFunctionHasBranchProtectedScope();
11780 
11781   // Warn about externally-visible variables being defined without a
11782   // prior declaration.  We only want to do this for global
11783   // declarations, but we also specifically need to avoid doing it for
11784   // class members because the linkage of an anonymous class can
11785   // change if it's later given a typedef name.
11786   if (var->isThisDeclarationADefinition() &&
11787       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11788       var->isExternallyVisible() && var->hasLinkage() &&
11789       !var->isInline() && !var->getDescribedVarTemplate() &&
11790       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11791       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11792                                   var->getLocation())) {
11793     // Find a previous declaration that's not a definition.
11794     VarDecl *prev = var->getPreviousDecl();
11795     while (prev && prev->isThisDeclarationADefinition())
11796       prev = prev->getPreviousDecl();
11797 
11798     if (!prev)
11799       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11800   }
11801 
11802   // Cache the result of checking for constant initialization.
11803   Optional<bool> CacheHasConstInit;
11804   const Expr *CacheCulprit;
11805   auto checkConstInit = [&]() mutable {
11806     if (!CacheHasConstInit)
11807       CacheHasConstInit = var->getInit()->isConstantInitializer(
11808             Context, var->getType()->isReferenceType(), &CacheCulprit);
11809     return *CacheHasConstInit;
11810   };
11811 
11812   if (var->getTLSKind() == VarDecl::TLS_Static) {
11813     if (var->getType().isDestructedType()) {
11814       // GNU C++98 edits for __thread, [basic.start.term]p3:
11815       //   The type of an object with thread storage duration shall not
11816       //   have a non-trivial destructor.
11817       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11818       if (getLangOpts().CPlusPlus11)
11819         Diag(var->getLocation(), diag::note_use_thread_local);
11820     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11821       if (!checkConstInit()) {
11822         // GNU C++98 edits for __thread, [basic.start.init]p4:
11823         //   An object of thread storage duration shall not require dynamic
11824         //   initialization.
11825         // FIXME: Need strict checking here.
11826         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11827           << CacheCulprit->getSourceRange();
11828         if (getLangOpts().CPlusPlus11)
11829           Diag(var->getLocation(), diag::note_use_thread_local);
11830       }
11831     }
11832   }
11833 
11834   // Apply section attributes and pragmas to global variables.
11835   bool GlobalStorage = var->hasGlobalStorage();
11836   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11837       !inTemplateInstantiation()) {
11838     PragmaStack<StringLiteral *> *Stack = nullptr;
11839     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11840     if (var->getType().isConstQualified())
11841       Stack = &ConstSegStack;
11842     else if (!var->getInit()) {
11843       Stack = &BSSSegStack;
11844       SectionFlags |= ASTContext::PSF_Write;
11845     } else {
11846       Stack = &DataSegStack;
11847       SectionFlags |= ASTContext::PSF_Write;
11848     }
11849     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11850       var->addAttr(SectionAttr::CreateImplicit(
11851           Context, SectionAttr::Declspec_allocate,
11852           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11853     }
11854     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11855       if (UnifySection(SA->getName(), SectionFlags, var))
11856         var->dropAttr<SectionAttr>();
11857 
11858     // Apply the init_seg attribute if this has an initializer.  If the
11859     // initializer turns out to not be dynamic, we'll end up ignoring this
11860     // attribute.
11861     if (CurInitSeg && var->getInit())
11862       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11863                                                CurInitSegLoc));
11864   }
11865 
11866   // All the following checks are C++ only.
11867   if (!getLangOpts().CPlusPlus) {
11868       // If this variable must be emitted, add it as an initializer for the
11869       // current module.
11870      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11871        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11872      return;
11873   }
11874 
11875   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11876     CheckCompleteDecompositionDeclaration(DD);
11877 
11878   QualType type = var->getType();
11879   if (type->isDependentType()) return;
11880 
11881   if (var->hasAttr<BlocksAttr>())
11882     getCurFunction()->addByrefBlockVar(var);
11883 
11884   Expr *Init = var->getInit();
11885   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11886   QualType baseType = Context.getBaseElementType(type);
11887 
11888   if (Init && !Init->isValueDependent()) {
11889     if (var->isConstexpr()) {
11890       SmallVector<PartialDiagnosticAt, 8> Notes;
11891       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11892         SourceLocation DiagLoc = var->getLocation();
11893         // If the note doesn't add any useful information other than a source
11894         // location, fold it into the primary diagnostic.
11895         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11896               diag::note_invalid_subexpr_in_const_expr) {
11897           DiagLoc = Notes[0].first;
11898           Notes.clear();
11899         }
11900         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11901           << var << Init->getSourceRange();
11902         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11903           Diag(Notes[I].first, Notes[I].second);
11904       }
11905     } else if (var->isUsableInConstantExpressions(Context)) {
11906       // Check whether the initializer of a const variable of integral or
11907       // enumeration type is an ICE now, since we can't tell whether it was
11908       // initialized by a constant expression if we check later.
11909       var->checkInitIsICE();
11910     }
11911 
11912     // Don't emit further diagnostics about constexpr globals since they
11913     // were just diagnosed.
11914     if (!var->isConstexpr() && GlobalStorage &&
11915             var->hasAttr<RequireConstantInitAttr>()) {
11916       // FIXME: Need strict checking in C++03 here.
11917       bool DiagErr = getLangOpts().CPlusPlus11
11918           ? !var->checkInitIsICE() : !checkConstInit();
11919       if (DiagErr) {
11920         auto attr = var->getAttr<RequireConstantInitAttr>();
11921         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11922           << Init->getSourceRange();
11923         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11924           << attr->getRange();
11925         if (getLangOpts().CPlusPlus11) {
11926           APValue Value;
11927           SmallVector<PartialDiagnosticAt, 8> Notes;
11928           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11929           for (auto &it : Notes)
11930             Diag(it.first, it.second);
11931         } else {
11932           Diag(CacheCulprit->getExprLoc(),
11933                diag::note_invalid_subexpr_in_const_expr)
11934               << CacheCulprit->getSourceRange();
11935         }
11936       }
11937     }
11938     else if (!var->isConstexpr() && IsGlobal &&
11939              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11940                                     var->getLocation())) {
11941       // Warn about globals which don't have a constant initializer.  Don't
11942       // warn about globals with a non-trivial destructor because we already
11943       // warned about them.
11944       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11945       if (!(RD && !RD->hasTrivialDestructor())) {
11946         if (!checkConstInit())
11947           Diag(var->getLocation(), diag::warn_global_constructor)
11948             << Init->getSourceRange();
11949       }
11950     }
11951   }
11952 
11953   // Require the destructor.
11954   if (const RecordType *recordType = baseType->getAs<RecordType>())
11955     FinalizeVarWithDestructor(var, recordType);
11956 
11957   // If this variable must be emitted, add it as an initializer for the current
11958   // module.
11959   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11960     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11961 }
11962 
11963 /// Determines if a variable's alignment is dependent.
11964 static bool hasDependentAlignment(VarDecl *VD) {
11965   if (VD->getType()->isDependentType())
11966     return true;
11967   for (auto *I : VD->specific_attrs<AlignedAttr>())
11968     if (I->isAlignmentDependent())
11969       return true;
11970   return false;
11971 }
11972 
11973 /// Check if VD needs to be dllexport/dllimport due to being in a
11974 /// dllexport/import function.
11975 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
11976   assert(VD->isStaticLocal());
11977 
11978   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11979 
11980   // Find outermost function when VD is in lambda function.
11981   while (FD && !getDLLAttr(FD) &&
11982          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
11983          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
11984     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
11985   }
11986 
11987   if (!FD)
11988     return;
11989 
11990   // Static locals inherit dll attributes from their function.
11991   if (Attr *A = getDLLAttr(FD)) {
11992     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11993     NewAttr->setInherited(true);
11994     VD->addAttr(NewAttr);
11995   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
11996     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
11997                                                           getASTContext(),
11998                                                           A->getSpellingListIndex());
11999     NewAttr->setInherited(true);
12000     VD->addAttr(NewAttr);
12001 
12002     // Export this function to enforce exporting this static variable even
12003     // if it is not used in this compilation unit.
12004     if (!FD->hasAttr<DLLExportAttr>())
12005       FD->addAttr(NewAttr);
12006 
12007   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12008     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12009                                                           getASTContext(),
12010                                                           A->getSpellingListIndex());
12011     NewAttr->setInherited(true);
12012     VD->addAttr(NewAttr);
12013   }
12014 }
12015 
12016 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12017 /// any semantic actions necessary after any initializer has been attached.
12018 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12019   // Note that we are no longer parsing the initializer for this declaration.
12020   ParsingInitForAutoVars.erase(ThisDecl);
12021 
12022   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12023   if (!VD)
12024     return;
12025 
12026   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12027   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12028       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12029     if (PragmaClangBSSSection.Valid)
12030       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12031                                                             PragmaClangBSSSection.SectionName,
12032                                                             PragmaClangBSSSection.PragmaLocation));
12033     if (PragmaClangDataSection.Valid)
12034       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12035                                                              PragmaClangDataSection.SectionName,
12036                                                              PragmaClangDataSection.PragmaLocation));
12037     if (PragmaClangRodataSection.Valid)
12038       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12039                                                                PragmaClangRodataSection.SectionName,
12040                                                                PragmaClangRodataSection.PragmaLocation));
12041   }
12042 
12043   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12044     for (auto *BD : DD->bindings()) {
12045       FinalizeDeclaration(BD);
12046     }
12047   }
12048 
12049   checkAttributesAfterMerging(*this, *VD);
12050 
12051   // Perform TLS alignment check here after attributes attached to the variable
12052   // which may affect the alignment have been processed. Only perform the check
12053   // if the target has a maximum TLS alignment (zero means no constraints).
12054   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12055     // Protect the check so that it's not performed on dependent types and
12056     // dependent alignments (we can't determine the alignment in that case).
12057     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12058         !VD->isInvalidDecl()) {
12059       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12060       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12061         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12062           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12063           << (unsigned)MaxAlignChars.getQuantity();
12064       }
12065     }
12066   }
12067 
12068   if (VD->isStaticLocal()) {
12069     CheckStaticLocalForDllExport(VD);
12070 
12071     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12072       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12073       // function, only __shared__ variables or variables without any device
12074       // memory qualifiers may be declared with static storage class.
12075       // Note: It is unclear how a function-scope non-const static variable
12076       // without device memory qualifier is implemented, therefore only static
12077       // const variable without device memory qualifier is allowed.
12078       [&]() {
12079         if (!getLangOpts().CUDA)
12080           return;
12081         if (VD->hasAttr<CUDASharedAttr>())
12082           return;
12083         if (VD->getType().isConstQualified() &&
12084             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12085           return;
12086         if (CUDADiagIfDeviceCode(VD->getLocation(),
12087                                  diag::err_device_static_local_var)
12088             << CurrentCUDATarget())
12089           VD->setInvalidDecl();
12090       }();
12091     }
12092   }
12093 
12094   // Perform check for initializers of device-side global variables.
12095   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12096   // 7.5). We must also apply the same checks to all __shared__
12097   // variables whether they are local or not. CUDA also allows
12098   // constant initializers for __constant__ and __device__ variables.
12099   if (getLangOpts().CUDA)
12100     checkAllowedCUDAInitializer(VD);
12101 
12102   // Grab the dllimport or dllexport attribute off of the VarDecl.
12103   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12104 
12105   // Imported static data members cannot be defined out-of-line.
12106   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12107     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12108         VD->isThisDeclarationADefinition()) {
12109       // We allow definitions of dllimport class template static data members
12110       // with a warning.
12111       CXXRecordDecl *Context =
12112         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12113       bool IsClassTemplateMember =
12114           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12115           Context->getDescribedClassTemplate();
12116 
12117       Diag(VD->getLocation(),
12118            IsClassTemplateMember
12119                ? diag::warn_attribute_dllimport_static_field_definition
12120                : diag::err_attribute_dllimport_static_field_definition);
12121       Diag(IA->getLocation(), diag::note_attribute);
12122       if (!IsClassTemplateMember)
12123         VD->setInvalidDecl();
12124     }
12125   }
12126 
12127   // dllimport/dllexport variables cannot be thread local, their TLS index
12128   // isn't exported with the variable.
12129   if (DLLAttr && VD->getTLSKind()) {
12130     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12131     if (F && getDLLAttr(F)) {
12132       assert(VD->isStaticLocal());
12133       // But if this is a static local in a dlimport/dllexport function, the
12134       // function will never be inlined, which means the var would never be
12135       // imported, so having it marked import/export is safe.
12136     } else {
12137       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12138                                                                     << DLLAttr;
12139       VD->setInvalidDecl();
12140     }
12141   }
12142 
12143   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12144     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12145       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12146       VD->dropAttr<UsedAttr>();
12147     }
12148   }
12149 
12150   const DeclContext *DC = VD->getDeclContext();
12151   // If there's a #pragma GCC visibility in scope, and this isn't a class
12152   // member, set the visibility of this variable.
12153   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12154     AddPushedVisibilityAttribute(VD);
12155 
12156   // FIXME: Warn on unused var template partial specializations.
12157   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12158     MarkUnusedFileScopedDecl(VD);
12159 
12160   // Now we have parsed the initializer and can update the table of magic
12161   // tag values.
12162   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12163       !VD->getType()->isIntegralOrEnumerationType())
12164     return;
12165 
12166   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12167     const Expr *MagicValueExpr = VD->getInit();
12168     if (!MagicValueExpr) {
12169       continue;
12170     }
12171     llvm::APSInt MagicValueInt;
12172     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12173       Diag(I->getRange().getBegin(),
12174            diag::err_type_tag_for_datatype_not_ice)
12175         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12176       continue;
12177     }
12178     if (MagicValueInt.getActiveBits() > 64) {
12179       Diag(I->getRange().getBegin(),
12180            diag::err_type_tag_for_datatype_too_large)
12181         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12182       continue;
12183     }
12184     uint64_t MagicValue = MagicValueInt.getZExtValue();
12185     RegisterTypeTagForDatatype(I->getArgumentKind(),
12186                                MagicValue,
12187                                I->getMatchingCType(),
12188                                I->getLayoutCompatible(),
12189                                I->getMustBeNull());
12190   }
12191 }
12192 
12193 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12194   auto *VD = dyn_cast<VarDecl>(DD);
12195   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12196 }
12197 
12198 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12199                                                    ArrayRef<Decl *> Group) {
12200   SmallVector<Decl*, 8> Decls;
12201 
12202   if (DS.isTypeSpecOwned())
12203     Decls.push_back(DS.getRepAsDecl());
12204 
12205   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12206   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12207   bool DiagnosedMultipleDecomps = false;
12208   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12209   bool DiagnosedNonDeducedAuto = false;
12210 
12211   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12212     if (Decl *D = Group[i]) {
12213       // For declarators, there are some additional syntactic-ish checks we need
12214       // to perform.
12215       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12216         if (!FirstDeclaratorInGroup)
12217           FirstDeclaratorInGroup = DD;
12218         if (!FirstDecompDeclaratorInGroup)
12219           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12220         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12221             !hasDeducedAuto(DD))
12222           FirstNonDeducedAutoInGroup = DD;
12223 
12224         if (FirstDeclaratorInGroup != DD) {
12225           // A decomposition declaration cannot be combined with any other
12226           // declaration in the same group.
12227           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12228             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12229                  diag::err_decomp_decl_not_alone)
12230                 << FirstDeclaratorInGroup->getSourceRange()
12231                 << DD->getSourceRange();
12232             DiagnosedMultipleDecomps = true;
12233           }
12234 
12235           // A declarator that uses 'auto' in any way other than to declare a
12236           // variable with a deduced type cannot be combined with any other
12237           // declarator in the same group.
12238           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12239             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12240                  diag::err_auto_non_deduced_not_alone)
12241                 << FirstNonDeducedAutoInGroup->getType()
12242                        ->hasAutoForTrailingReturnType()
12243                 << FirstDeclaratorInGroup->getSourceRange()
12244                 << DD->getSourceRange();
12245             DiagnosedNonDeducedAuto = true;
12246           }
12247         }
12248       }
12249 
12250       Decls.push_back(D);
12251     }
12252   }
12253 
12254   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12255     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12256       handleTagNumbering(Tag, S);
12257       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12258           getLangOpts().CPlusPlus)
12259         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12260     }
12261   }
12262 
12263   return BuildDeclaratorGroup(Decls);
12264 }
12265 
12266 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12267 /// group, performing any necessary semantic checking.
12268 Sema::DeclGroupPtrTy
12269 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12270   // C++14 [dcl.spec.auto]p7: (DR1347)
12271   //   If the type that replaces the placeholder type is not the same in each
12272   //   deduction, the program is ill-formed.
12273   if (Group.size() > 1) {
12274     QualType Deduced;
12275     VarDecl *DeducedDecl = nullptr;
12276     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12277       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12278       if (!D || D->isInvalidDecl())
12279         break;
12280       DeducedType *DT = D->getType()->getContainedDeducedType();
12281       if (!DT || DT->getDeducedType().isNull())
12282         continue;
12283       if (Deduced.isNull()) {
12284         Deduced = DT->getDeducedType();
12285         DeducedDecl = D;
12286       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12287         auto *AT = dyn_cast<AutoType>(DT);
12288         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12289              diag::err_auto_different_deductions)
12290           << (AT ? (unsigned)AT->getKeyword() : 3)
12291           << Deduced << DeducedDecl->getDeclName()
12292           << DT->getDeducedType() << D->getDeclName()
12293           << DeducedDecl->getInit()->getSourceRange()
12294           << D->getInit()->getSourceRange();
12295         D->setInvalidDecl();
12296         break;
12297       }
12298     }
12299   }
12300 
12301   ActOnDocumentableDecls(Group);
12302 
12303   return DeclGroupPtrTy::make(
12304       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12305 }
12306 
12307 void Sema::ActOnDocumentableDecl(Decl *D) {
12308   ActOnDocumentableDecls(D);
12309 }
12310 
12311 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12312   // Don't parse the comment if Doxygen diagnostics are ignored.
12313   if (Group.empty() || !Group[0])
12314     return;
12315 
12316   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12317                       Group[0]->getLocation()) &&
12318       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12319                       Group[0]->getLocation()))
12320     return;
12321 
12322   if (Group.size() >= 2) {
12323     // This is a decl group.  Normally it will contain only declarations
12324     // produced from declarator list.  But in case we have any definitions or
12325     // additional declaration references:
12326     //   'typedef struct S {} S;'
12327     //   'typedef struct S *S;'
12328     //   'struct S *pS;'
12329     // FinalizeDeclaratorGroup adds these as separate declarations.
12330     Decl *MaybeTagDecl = Group[0];
12331     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12332       Group = Group.slice(1);
12333     }
12334   }
12335 
12336   // See if there are any new comments that are not attached to a decl.
12337   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12338   if (!Comments.empty() &&
12339       !Comments.back()->isAttached()) {
12340     // There is at least one comment that not attached to a decl.
12341     // Maybe it should be attached to one of these decls?
12342     //
12343     // Note that this way we pick up not only comments that precede the
12344     // declaration, but also comments that *follow* the declaration -- thanks to
12345     // the lookahead in the lexer: we've consumed the semicolon and looked
12346     // ahead through comments.
12347     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12348       Context.getCommentForDecl(Group[i], &PP);
12349   }
12350 }
12351 
12352 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12353 /// to introduce parameters into function prototype scope.
12354 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12355   const DeclSpec &DS = D.getDeclSpec();
12356 
12357   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12358 
12359   // C++03 [dcl.stc]p2 also permits 'auto'.
12360   StorageClass SC = SC_None;
12361   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12362     SC = SC_Register;
12363     // In C++11, the 'register' storage class specifier is deprecated.
12364     // In C++17, it is not allowed, but we tolerate it as an extension.
12365     if (getLangOpts().CPlusPlus11) {
12366       Diag(DS.getStorageClassSpecLoc(),
12367            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12368                                      : diag::warn_deprecated_register)
12369         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12370     }
12371   } else if (getLangOpts().CPlusPlus &&
12372              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12373     SC = SC_Auto;
12374   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12375     Diag(DS.getStorageClassSpecLoc(),
12376          diag::err_invalid_storage_class_in_func_decl);
12377     D.getMutableDeclSpec().ClearStorageClassSpecs();
12378   }
12379 
12380   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12381     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12382       << DeclSpec::getSpecifierName(TSCS);
12383   if (DS.isInlineSpecified())
12384     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12385         << getLangOpts().CPlusPlus17;
12386   if (DS.isConstexprSpecified())
12387     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12388       << 0;
12389 
12390   DiagnoseFunctionSpecifiers(DS);
12391 
12392   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12393   QualType parmDeclType = TInfo->getType();
12394 
12395   if (getLangOpts().CPlusPlus) {
12396     // Check that there are no default arguments inside the type of this
12397     // parameter.
12398     CheckExtraCXXDefaultArguments(D);
12399 
12400     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12401     if (D.getCXXScopeSpec().isSet()) {
12402       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12403         << D.getCXXScopeSpec().getRange();
12404       D.getCXXScopeSpec().clear();
12405     }
12406   }
12407 
12408   // Ensure we have a valid name
12409   IdentifierInfo *II = nullptr;
12410   if (D.hasName()) {
12411     II = D.getIdentifier();
12412     if (!II) {
12413       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12414         << GetNameForDeclarator(D).getName();
12415       D.setInvalidType(true);
12416     }
12417   }
12418 
12419   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12420   if (II) {
12421     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12422                    ForVisibleRedeclaration);
12423     LookupName(R, S);
12424     if (R.isSingleResult()) {
12425       NamedDecl *PrevDecl = R.getFoundDecl();
12426       if (PrevDecl->isTemplateParameter()) {
12427         // Maybe we will complain about the shadowed template parameter.
12428         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12429         // Just pretend that we didn't see the previous declaration.
12430         PrevDecl = nullptr;
12431       } else if (S->isDeclScope(PrevDecl)) {
12432         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12433         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12434 
12435         // Recover by removing the name
12436         II = nullptr;
12437         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12438         D.setInvalidType(true);
12439       }
12440     }
12441   }
12442 
12443   // Temporarily put parameter variables in the translation unit, not
12444   // the enclosing context.  This prevents them from accidentally
12445   // looking like class members in C++.
12446   ParmVarDecl *New =
12447       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12448                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12449 
12450   if (D.isInvalidType())
12451     New->setInvalidDecl();
12452 
12453   assert(S->isFunctionPrototypeScope());
12454   assert(S->getFunctionPrototypeDepth() >= 1);
12455   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12456                     S->getNextFunctionPrototypeIndex());
12457 
12458   // Add the parameter declaration into this scope.
12459   S->AddDecl(New);
12460   if (II)
12461     IdResolver.AddDecl(New);
12462 
12463   ProcessDeclAttributes(S, New, D);
12464 
12465   if (D.getDeclSpec().isModulePrivateSpecified())
12466     Diag(New->getLocation(), diag::err_module_private_local)
12467       << 1 << New->getDeclName()
12468       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12469       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12470 
12471   if (New->hasAttr<BlocksAttr>()) {
12472     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12473   }
12474   return New;
12475 }
12476 
12477 /// Synthesizes a variable for a parameter arising from a
12478 /// typedef.
12479 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12480                                               SourceLocation Loc,
12481                                               QualType T) {
12482   /* FIXME: setting StartLoc == Loc.
12483      Would it be worth to modify callers so as to provide proper source
12484      location for the unnamed parameters, embedding the parameter's type? */
12485   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12486                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12487                                            SC_None, nullptr);
12488   Param->setImplicit();
12489   return Param;
12490 }
12491 
12492 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12493   // Don't diagnose unused-parameter errors in template instantiations; we
12494   // will already have done so in the template itself.
12495   if (inTemplateInstantiation())
12496     return;
12497 
12498   for (const ParmVarDecl *Parameter : Parameters) {
12499     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12500         !Parameter->hasAttr<UnusedAttr>()) {
12501       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12502         << Parameter->getDeclName();
12503     }
12504   }
12505 }
12506 
12507 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12508     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12509   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12510     return;
12511 
12512   // Warn if the return value is pass-by-value and larger than the specified
12513   // threshold.
12514   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12515     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12516     if (Size > LangOpts.NumLargeByValueCopy)
12517       Diag(D->getLocation(), diag::warn_return_value_size)
12518           << D->getDeclName() << Size;
12519   }
12520 
12521   // Warn if any parameter is pass-by-value and larger than the specified
12522   // threshold.
12523   for (const ParmVarDecl *Parameter : Parameters) {
12524     QualType T = Parameter->getType();
12525     if (T->isDependentType() || !T.isPODType(Context))
12526       continue;
12527     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12528     if (Size > LangOpts.NumLargeByValueCopy)
12529       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12530           << Parameter->getDeclName() << Size;
12531   }
12532 }
12533 
12534 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12535                                   SourceLocation NameLoc, IdentifierInfo *Name,
12536                                   QualType T, TypeSourceInfo *TSInfo,
12537                                   StorageClass SC) {
12538   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12539   if (getLangOpts().ObjCAutoRefCount &&
12540       T.getObjCLifetime() == Qualifiers::OCL_None &&
12541       T->isObjCLifetimeType()) {
12542 
12543     Qualifiers::ObjCLifetime lifetime;
12544 
12545     // Special cases for arrays:
12546     //   - if it's const, use __unsafe_unretained
12547     //   - otherwise, it's an error
12548     if (T->isArrayType()) {
12549       if (!T.isConstQualified()) {
12550         if (DelayedDiagnostics.shouldDelayDiagnostics())
12551           DelayedDiagnostics.add(
12552               sema::DelayedDiagnostic::makeForbiddenType(
12553               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12554         else
12555           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12556               << TSInfo->getTypeLoc().getSourceRange();
12557       }
12558       lifetime = Qualifiers::OCL_ExplicitNone;
12559     } else {
12560       lifetime = T->getObjCARCImplicitLifetime();
12561     }
12562     T = Context.getLifetimeQualifiedType(T, lifetime);
12563   }
12564 
12565   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12566                                          Context.getAdjustedParameterType(T),
12567                                          TSInfo, SC, nullptr);
12568 
12569   // Parameters can not be abstract class types.
12570   // For record types, this is done by the AbstractClassUsageDiagnoser once
12571   // the class has been completely parsed.
12572   if (!CurContext->isRecord() &&
12573       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12574                              AbstractParamType))
12575     New->setInvalidDecl();
12576 
12577   // Parameter declarators cannot be interface types. All ObjC objects are
12578   // passed by reference.
12579   if (T->isObjCObjectType()) {
12580     SourceLocation TypeEndLoc =
12581         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12582     Diag(NameLoc,
12583          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12584       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12585     T = Context.getObjCObjectPointerType(T);
12586     New->setType(T);
12587   }
12588 
12589   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12590   // duration shall not be qualified by an address-space qualifier."
12591   // Since all parameters have automatic store duration, they can not have
12592   // an address space.
12593   if (T.getAddressSpace() != LangAS::Default &&
12594       // OpenCL allows function arguments declared to be an array of a type
12595       // to be qualified with an address space.
12596       !(getLangOpts().OpenCL &&
12597         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12598     Diag(NameLoc, diag::err_arg_with_address_space);
12599     New->setInvalidDecl();
12600   }
12601 
12602   return New;
12603 }
12604 
12605 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12606                                            SourceLocation LocAfterDecls) {
12607   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12608 
12609   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12610   // for a K&R function.
12611   if (!FTI.hasPrototype) {
12612     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12613       --i;
12614       if (FTI.Params[i].Param == nullptr) {
12615         SmallString<256> Code;
12616         llvm::raw_svector_ostream(Code)
12617             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12618         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12619             << FTI.Params[i].Ident
12620             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12621 
12622         // Implicitly declare the argument as type 'int' for lack of a better
12623         // type.
12624         AttributeFactory attrs;
12625         DeclSpec DS(attrs);
12626         const char* PrevSpec; // unused
12627         unsigned DiagID; // unused
12628         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12629                            DiagID, Context.getPrintingPolicy());
12630         // Use the identifier location for the type source range.
12631         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12632         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12633         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12634         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12635         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12636       }
12637     }
12638   }
12639 }
12640 
12641 Decl *
12642 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12643                               MultiTemplateParamsArg TemplateParameterLists,
12644                               SkipBodyInfo *SkipBody) {
12645   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12646   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12647   Scope *ParentScope = FnBodyScope->getParent();
12648 
12649   D.setFunctionDefinitionKind(FDK_Definition);
12650   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12651   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12652 }
12653 
12654 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12655   Consumer.HandleInlineFunctionDefinition(D);
12656 }
12657 
12658 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12659                              const FunctionDecl*& PossibleZeroParamPrototype) {
12660   // Don't warn about invalid declarations.
12661   if (FD->isInvalidDecl())
12662     return false;
12663 
12664   // Or declarations that aren't global.
12665   if (!FD->isGlobal())
12666     return false;
12667 
12668   // Don't warn about C++ member functions.
12669   if (isa<CXXMethodDecl>(FD))
12670     return false;
12671 
12672   // Don't warn about 'main'.
12673   if (FD->isMain())
12674     return false;
12675 
12676   // Don't warn about inline functions.
12677   if (FD->isInlined())
12678     return false;
12679 
12680   // Don't warn about function templates.
12681   if (FD->getDescribedFunctionTemplate())
12682     return false;
12683 
12684   // Don't warn about function template specializations.
12685   if (FD->isFunctionTemplateSpecialization())
12686     return false;
12687 
12688   // Don't warn for OpenCL kernels.
12689   if (FD->hasAttr<OpenCLKernelAttr>())
12690     return false;
12691 
12692   // Don't warn on explicitly deleted functions.
12693   if (FD->isDeleted())
12694     return false;
12695 
12696   bool MissingPrototype = true;
12697   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12698        Prev; Prev = Prev->getPreviousDecl()) {
12699     // Ignore any declarations that occur in function or method
12700     // scope, because they aren't visible from the header.
12701     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12702       continue;
12703 
12704     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12705     if (FD->getNumParams() == 0)
12706       PossibleZeroParamPrototype = Prev;
12707     break;
12708   }
12709 
12710   return MissingPrototype;
12711 }
12712 
12713 void
12714 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12715                                    const FunctionDecl *EffectiveDefinition,
12716                                    SkipBodyInfo *SkipBody) {
12717   const FunctionDecl *Definition = EffectiveDefinition;
12718   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12719     // If this is a friend function defined in a class template, it does not
12720     // have a body until it is used, nevertheless it is a definition, see
12721     // [temp.inst]p2:
12722     //
12723     // ... for the purpose of determining whether an instantiated redeclaration
12724     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12725     // corresponds to a definition in the template is considered to be a
12726     // definition.
12727     //
12728     // The following code must produce redefinition error:
12729     //
12730     //     template<typename T> struct C20 { friend void func_20() {} };
12731     //     C20<int> c20i;
12732     //     void func_20() {}
12733     //
12734     for (auto I : FD->redecls()) {
12735       if (I != FD && !I->isInvalidDecl() &&
12736           I->getFriendObjectKind() != Decl::FOK_None) {
12737         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12738           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12739             // A merged copy of the same function, instantiated as a member of
12740             // the same class, is OK.
12741             if (declaresSameEntity(OrigFD, Original) &&
12742                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12743                                    cast<Decl>(FD->getLexicalDeclContext())))
12744               continue;
12745           }
12746 
12747           if (Original->isThisDeclarationADefinition()) {
12748             Definition = I;
12749             break;
12750           }
12751         }
12752       }
12753     }
12754   }
12755 
12756   if (!Definition)
12757     // Similar to friend functions a friend function template may be a
12758     // definition and do not have a body if it is instantiated in a class
12759     // template.
12760     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12761       for (auto I : FTD->redecls()) {
12762         auto D = cast<FunctionTemplateDecl>(I);
12763         if (D != FTD) {
12764           assert(!D->isThisDeclarationADefinition() &&
12765                  "More than one definition in redeclaration chain");
12766           if (D->getFriendObjectKind() != Decl::FOK_None)
12767             if (FunctionTemplateDecl *FT =
12768                                        D->getInstantiatedFromMemberTemplate()) {
12769               if (FT->isThisDeclarationADefinition()) {
12770                 Definition = D->getTemplatedDecl();
12771                 break;
12772               }
12773             }
12774         }
12775       }
12776     }
12777 
12778   if (!Definition)
12779     return;
12780 
12781   if (canRedefineFunction(Definition, getLangOpts()))
12782     return;
12783 
12784   // Don't emit an error when this is redefinition of a typo-corrected
12785   // definition.
12786   if (TypoCorrectedFunctionDefinitions.count(Definition))
12787     return;
12788 
12789   // If we don't have a visible definition of the function, and it's inline or
12790   // a template, skip the new definition.
12791   if (SkipBody && !hasVisibleDefinition(Definition) &&
12792       (Definition->getFormalLinkage() == InternalLinkage ||
12793        Definition->isInlined() ||
12794        Definition->getDescribedFunctionTemplate() ||
12795        Definition->getNumTemplateParameterLists())) {
12796     SkipBody->ShouldSkip = true;
12797     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12798     if (auto *TD = Definition->getDescribedFunctionTemplate())
12799       makeMergedDefinitionVisible(TD);
12800     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12801     return;
12802   }
12803 
12804   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12805       Definition->getStorageClass() == SC_Extern)
12806     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12807         << FD->getDeclName() << getLangOpts().CPlusPlus;
12808   else
12809     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12810 
12811   Diag(Definition->getLocation(), diag::note_previous_definition);
12812   FD->setInvalidDecl();
12813 }
12814 
12815 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12816                                    Sema &S) {
12817   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12818 
12819   LambdaScopeInfo *LSI = S.PushLambdaScope();
12820   LSI->CallOperator = CallOperator;
12821   LSI->Lambda = LambdaClass;
12822   LSI->ReturnType = CallOperator->getReturnType();
12823   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12824 
12825   if (LCD == LCD_None)
12826     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12827   else if (LCD == LCD_ByCopy)
12828     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12829   else if (LCD == LCD_ByRef)
12830     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12831   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12832 
12833   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12834   LSI->Mutable = !CallOperator->isConst();
12835 
12836   // Add the captures to the LSI so they can be noted as already
12837   // captured within tryCaptureVar.
12838   auto I = LambdaClass->field_begin();
12839   for (const auto &C : LambdaClass->captures()) {
12840     if (C.capturesVariable()) {
12841       VarDecl *VD = C.getCapturedVar();
12842       if (VD->isInitCapture())
12843         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12844       QualType CaptureType = VD->getType();
12845       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12846       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12847           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12848           /*EllipsisLoc*/C.isPackExpansion()
12849                          ? C.getEllipsisLoc() : SourceLocation(),
12850           CaptureType, /*Expr*/ nullptr);
12851 
12852     } else if (C.capturesThis()) {
12853       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12854                               /*Expr*/ nullptr,
12855                               C.getCaptureKind() == LCK_StarThis);
12856     } else {
12857       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12858     }
12859     ++I;
12860   }
12861 }
12862 
12863 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12864                                     SkipBodyInfo *SkipBody) {
12865   if (!D) {
12866     // Parsing the function declaration failed in some way. Push on a fake scope
12867     // anyway so we can try to parse the function body.
12868     PushFunctionScope();
12869     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12870     return D;
12871   }
12872 
12873   FunctionDecl *FD = nullptr;
12874 
12875   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12876     FD = FunTmpl->getTemplatedDecl();
12877   else
12878     FD = cast<FunctionDecl>(D);
12879 
12880   // Do not push if it is a lambda because one is already pushed when building
12881   // the lambda in ActOnStartOfLambdaDefinition().
12882   if (!isLambdaCallOperator(FD))
12883     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12884 
12885   // Check for defining attributes before the check for redefinition.
12886   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12887     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12888     FD->dropAttr<AliasAttr>();
12889     FD->setInvalidDecl();
12890   }
12891   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12892     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12893     FD->dropAttr<IFuncAttr>();
12894     FD->setInvalidDecl();
12895   }
12896 
12897   // See if this is a redefinition. If 'will have body' is already set, then
12898   // these checks were already performed when it was set.
12899   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12900     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12901 
12902     // If we're skipping the body, we're done. Don't enter the scope.
12903     if (SkipBody && SkipBody->ShouldSkip)
12904       return D;
12905   }
12906 
12907   // Mark this function as "will have a body eventually".  This lets users to
12908   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12909   // this function.
12910   FD->setWillHaveBody();
12911 
12912   // If we are instantiating a generic lambda call operator, push
12913   // a LambdaScopeInfo onto the function stack.  But use the information
12914   // that's already been calculated (ActOnLambdaExpr) to prime the current
12915   // LambdaScopeInfo.
12916   // When the template operator is being specialized, the LambdaScopeInfo,
12917   // has to be properly restored so that tryCaptureVariable doesn't try
12918   // and capture any new variables. In addition when calculating potential
12919   // captures during transformation of nested lambdas, it is necessary to
12920   // have the LSI properly restored.
12921   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12922     assert(inTemplateInstantiation() &&
12923            "There should be an active template instantiation on the stack "
12924            "when instantiating a generic lambda!");
12925     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12926   } else {
12927     // Enter a new function scope
12928     PushFunctionScope();
12929   }
12930 
12931   // Builtin functions cannot be defined.
12932   if (unsigned BuiltinID = FD->getBuiltinID()) {
12933     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12934         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12935       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12936       FD->setInvalidDecl();
12937     }
12938   }
12939 
12940   // The return type of a function definition must be complete
12941   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12942   QualType ResultType = FD->getReturnType();
12943   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12944       !FD->isInvalidDecl() &&
12945       RequireCompleteType(FD->getLocation(), ResultType,
12946                           diag::err_func_def_incomplete_result))
12947     FD->setInvalidDecl();
12948 
12949   if (FnBodyScope)
12950     PushDeclContext(FnBodyScope, FD);
12951 
12952   // Check the validity of our function parameters
12953   CheckParmsForFunctionDef(FD->parameters(),
12954                            /*CheckParameterNames=*/true);
12955 
12956   // Add non-parameter declarations already in the function to the current
12957   // scope.
12958   if (FnBodyScope) {
12959     for (Decl *NPD : FD->decls()) {
12960       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12961       if (!NonParmDecl)
12962         continue;
12963       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12964              "parameters should not be in newly created FD yet");
12965 
12966       // If the decl has a name, make it accessible in the current scope.
12967       if (NonParmDecl->getDeclName())
12968         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12969 
12970       // Similarly, dive into enums and fish their constants out, making them
12971       // accessible in this scope.
12972       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12973         for (auto *EI : ED->enumerators())
12974           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12975       }
12976     }
12977   }
12978 
12979   // Introduce our parameters into the function scope
12980   for (auto Param : FD->parameters()) {
12981     Param->setOwningFunction(FD);
12982 
12983     // If this has an identifier, add it to the scope stack.
12984     if (Param->getIdentifier() && FnBodyScope) {
12985       CheckShadow(FnBodyScope, Param);
12986 
12987       PushOnScopeChains(Param, FnBodyScope);
12988     }
12989   }
12990 
12991   // Ensure that the function's exception specification is instantiated.
12992   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12993     ResolveExceptionSpec(D->getLocation(), FPT);
12994 
12995   // dllimport cannot be applied to non-inline function definitions.
12996   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12997       !FD->isTemplateInstantiation()) {
12998     assert(!FD->hasAttr<DLLExportAttr>());
12999     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13000     FD->setInvalidDecl();
13001     return D;
13002   }
13003   // We want to attach documentation to original Decl (which might be
13004   // a function template).
13005   ActOnDocumentableDecl(D);
13006   if (getCurLexicalContext()->isObjCContainer() &&
13007       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13008       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13009     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13010 
13011   return D;
13012 }
13013 
13014 /// Given the set of return statements within a function body,
13015 /// compute the variables that are subject to the named return value
13016 /// optimization.
13017 ///
13018 /// Each of the variables that is subject to the named return value
13019 /// optimization will be marked as NRVO variables in the AST, and any
13020 /// return statement that has a marked NRVO variable as its NRVO candidate can
13021 /// use the named return value optimization.
13022 ///
13023 /// This function applies a very simplistic algorithm for NRVO: if every return
13024 /// statement in the scope of a variable has the same NRVO candidate, that
13025 /// candidate is an NRVO variable.
13026 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13027   ReturnStmt **Returns = Scope->Returns.data();
13028 
13029   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13030     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13031       if (!NRVOCandidate->isNRVOVariable())
13032         Returns[I]->setNRVOCandidate(nullptr);
13033     }
13034   }
13035 }
13036 
13037 bool Sema::canDelayFunctionBody(const Declarator &D) {
13038   // We can't delay parsing the body of a constexpr function template (yet).
13039   if (D.getDeclSpec().isConstexprSpecified())
13040     return false;
13041 
13042   // We can't delay parsing the body of a function template with a deduced
13043   // return type (yet).
13044   if (D.getDeclSpec().hasAutoTypeSpec()) {
13045     // If the placeholder introduces a non-deduced trailing return type,
13046     // we can still delay parsing it.
13047     if (D.getNumTypeObjects()) {
13048       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13049       if (Outer.Kind == DeclaratorChunk::Function &&
13050           Outer.Fun.hasTrailingReturnType()) {
13051         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13052         return Ty.isNull() || !Ty->isUndeducedType();
13053       }
13054     }
13055     return false;
13056   }
13057 
13058   return true;
13059 }
13060 
13061 bool Sema::canSkipFunctionBody(Decl *D) {
13062   // We cannot skip the body of a function (or function template) which is
13063   // constexpr, since we may need to evaluate its body in order to parse the
13064   // rest of the file.
13065   // We cannot skip the body of a function with an undeduced return type,
13066   // because any callers of that function need to know the type.
13067   if (const FunctionDecl *FD = D->getAsFunction()) {
13068     if (FD->isConstexpr())
13069       return false;
13070     // We can't simply call Type::isUndeducedType here, because inside template
13071     // auto can be deduced to a dependent type, which is not considered
13072     // "undeduced".
13073     if (FD->getReturnType()->getContainedDeducedType())
13074       return false;
13075   }
13076   return Consumer.shouldSkipFunctionBody(D);
13077 }
13078 
13079 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13080   if (!Decl)
13081     return nullptr;
13082   if (FunctionDecl *FD = Decl->getAsFunction())
13083     FD->setHasSkippedBody();
13084   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13085     MD->setHasSkippedBody();
13086   return Decl;
13087 }
13088 
13089 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13090   return ActOnFinishFunctionBody(D, BodyArg, false);
13091 }
13092 
13093 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13094 /// body.
13095 class ExitFunctionBodyRAII {
13096 public:
13097   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13098   ~ExitFunctionBodyRAII() {
13099     if (!IsLambda)
13100       S.PopExpressionEvaluationContext();
13101   }
13102 
13103 private:
13104   Sema &S;
13105   bool IsLambda = false;
13106 };
13107 
13108 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13109                                     bool IsInstantiation) {
13110   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13111 
13112   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13113   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13114 
13115   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
13116     CheckCompletedCoroutineBody(FD, Body);
13117 
13118   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13119   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13120   // meant to pop the context added in ActOnStartOfFunctionDef().
13121   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13122 
13123   if (FD) {
13124     FD->setBody(Body);
13125     FD->setWillHaveBody(false);
13126 
13127     if (getLangOpts().CPlusPlus14) {
13128       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13129           FD->getReturnType()->isUndeducedType()) {
13130         // If the function has a deduced result type but contains no 'return'
13131         // statements, the result type as written must be exactly 'auto', and
13132         // the deduced result type is 'void'.
13133         if (!FD->getReturnType()->getAs<AutoType>()) {
13134           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13135               << FD->getReturnType();
13136           FD->setInvalidDecl();
13137         } else {
13138           // Substitute 'void' for the 'auto' in the type.
13139           TypeLoc ResultType = getReturnTypeLoc(FD);
13140           Context.adjustDeducedFunctionResultType(
13141               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13142         }
13143       }
13144     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13145       // In C++11, we don't use 'auto' deduction rules for lambda call
13146       // operators because we don't support return type deduction.
13147       auto *LSI = getCurLambda();
13148       if (LSI->HasImplicitReturnType) {
13149         deduceClosureReturnType(*LSI);
13150 
13151         // C++11 [expr.prim.lambda]p4:
13152         //   [...] if there are no return statements in the compound-statement
13153         //   [the deduced type is] the type void
13154         QualType RetType =
13155             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13156 
13157         // Update the return type to the deduced type.
13158         const FunctionProtoType *Proto =
13159             FD->getType()->getAs<FunctionProtoType>();
13160         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13161                                             Proto->getExtProtoInfo()));
13162       }
13163     }
13164 
13165     // If the function implicitly returns zero (like 'main') or is naked,
13166     // don't complain about missing return statements.
13167     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13168       WP.disableCheckFallThrough();
13169 
13170     // MSVC permits the use of pure specifier (=0) on function definition,
13171     // defined at class scope, warn about this non-standard construct.
13172     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13173       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13174 
13175     if (!FD->isInvalidDecl()) {
13176       // Don't diagnose unused parameters of defaulted or deleted functions.
13177       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13178         DiagnoseUnusedParameters(FD->parameters());
13179       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13180                                              FD->getReturnType(), FD);
13181 
13182       // If this is a structor, we need a vtable.
13183       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13184         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13185       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13186         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13187 
13188       // Try to apply the named return value optimization. We have to check
13189       // if we can do this here because lambdas keep return statements around
13190       // to deduce an implicit return type.
13191       if (FD->getReturnType()->isRecordType() &&
13192           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13193         computeNRVO(Body, getCurFunction());
13194     }
13195 
13196     // GNU warning -Wmissing-prototypes:
13197     //   Warn if a global function is defined without a previous
13198     //   prototype declaration. This warning is issued even if the
13199     //   definition itself provides a prototype. The aim is to detect
13200     //   global functions that fail to be declared in header files.
13201     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13202     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13203       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13204 
13205       if (PossibleZeroParamPrototype) {
13206         // We found a declaration that is not a prototype,
13207         // but that could be a zero-parameter prototype
13208         if (TypeSourceInfo *TI =
13209                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13210           TypeLoc TL = TI->getTypeLoc();
13211           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13212             Diag(PossibleZeroParamPrototype->getLocation(),
13213                  diag::note_declaration_not_a_prototype)
13214                 << PossibleZeroParamPrototype
13215                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13216         }
13217       }
13218 
13219       // GNU warning -Wstrict-prototypes
13220       //   Warn if K&R function is defined without a previous declaration.
13221       //   This warning is issued only if the definition itself does not provide
13222       //   a prototype. Only K&R definitions do not provide a prototype.
13223       //   An empty list in a function declarator that is part of a definition
13224       //   of that function specifies that the function has no parameters
13225       //   (C99 6.7.5.3p14)
13226       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13227           !LangOpts.CPlusPlus) {
13228         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13229         TypeLoc TL = TI->getTypeLoc();
13230         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13231         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13232       }
13233     }
13234 
13235     // Warn on CPUDispatch with an actual body.
13236     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13237       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13238         if (!CmpndBody->body_empty())
13239           Diag(CmpndBody->body_front()->getBeginLoc(),
13240                diag::warn_dispatch_body_ignored);
13241 
13242     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13243       const CXXMethodDecl *KeyFunction;
13244       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13245           MD->isVirtual() &&
13246           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13247           MD == KeyFunction->getCanonicalDecl()) {
13248         // Update the key-function state if necessary for this ABI.
13249         if (FD->isInlined() &&
13250             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13251           Context.setNonKeyFunction(MD);
13252 
13253           // If the newly-chosen key function is already defined, then we
13254           // need to mark the vtable as used retroactively.
13255           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13256           const FunctionDecl *Definition;
13257           if (KeyFunction && KeyFunction->isDefined(Definition))
13258             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13259         } else {
13260           // We just defined they key function; mark the vtable as used.
13261           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13262         }
13263       }
13264     }
13265 
13266     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13267            "Function parsing confused");
13268   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13269     assert(MD == getCurMethodDecl() && "Method parsing confused");
13270     MD->setBody(Body);
13271     if (!MD->isInvalidDecl()) {
13272       if (!MD->hasSkippedBody())
13273         DiagnoseUnusedParameters(MD->parameters());
13274       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13275                                              MD->getReturnType(), MD);
13276 
13277       if (Body)
13278         computeNRVO(Body, getCurFunction());
13279     }
13280     if (getCurFunction()->ObjCShouldCallSuper) {
13281       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13282           << MD->getSelector().getAsString();
13283       getCurFunction()->ObjCShouldCallSuper = false;
13284     }
13285     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13286       const ObjCMethodDecl *InitMethod = nullptr;
13287       bool isDesignated =
13288           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13289       assert(isDesignated && InitMethod);
13290       (void)isDesignated;
13291 
13292       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13293         auto IFace = MD->getClassInterface();
13294         if (!IFace)
13295           return false;
13296         auto SuperD = IFace->getSuperClass();
13297         if (!SuperD)
13298           return false;
13299         return SuperD->getIdentifier() ==
13300             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13301       };
13302       // Don't issue this warning for unavailable inits or direct subclasses
13303       // of NSObject.
13304       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13305         Diag(MD->getLocation(),
13306              diag::warn_objc_designated_init_missing_super_call);
13307         Diag(InitMethod->getLocation(),
13308              diag::note_objc_designated_init_marked_here);
13309       }
13310       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13311     }
13312     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13313       // Don't issue this warning for unavaialable inits.
13314       if (!MD->isUnavailable())
13315         Diag(MD->getLocation(),
13316              diag::warn_objc_secondary_init_missing_init_call);
13317       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13318     }
13319   } else {
13320     // Parsing the function declaration failed in some way. Pop the fake scope
13321     // we pushed on.
13322     PopFunctionScopeInfo(ActivePolicy, dcl);
13323     return nullptr;
13324   }
13325 
13326   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13327     DiagnoseUnguardedAvailabilityViolations(dcl);
13328 
13329   assert(!getCurFunction()->ObjCShouldCallSuper &&
13330          "This should only be set for ObjC methods, which should have been "
13331          "handled in the block above.");
13332 
13333   // Verify and clean out per-function state.
13334   if (Body && (!FD || !FD->isDefaulted())) {
13335     // C++ constructors that have function-try-blocks can't have return
13336     // statements in the handlers of that block. (C++ [except.handle]p14)
13337     // Verify this.
13338     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13339       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13340 
13341     // Verify that gotos and switch cases don't jump into scopes illegally.
13342     if (getCurFunction()->NeedsScopeChecking() &&
13343         !PP.isCodeCompletionEnabled())
13344       DiagnoseInvalidJumps(Body);
13345 
13346     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13347       if (!Destructor->getParent()->isDependentType())
13348         CheckDestructor(Destructor);
13349 
13350       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13351                                              Destructor->getParent());
13352     }
13353 
13354     // If any errors have occurred, clear out any temporaries that may have
13355     // been leftover. This ensures that these temporaries won't be picked up for
13356     // deletion in some later function.
13357     if (getDiagnostics().hasErrorOccurred() ||
13358         getDiagnostics().getSuppressAllDiagnostics()) {
13359       DiscardCleanupsInEvaluationContext();
13360     }
13361     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13362         !isa<FunctionTemplateDecl>(dcl)) {
13363       // Since the body is valid, issue any analysis-based warnings that are
13364       // enabled.
13365       ActivePolicy = &WP;
13366     }
13367 
13368     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13369         (!CheckConstexprFunctionDecl(FD) ||
13370          !CheckConstexprFunctionBody(FD, Body)))
13371       FD->setInvalidDecl();
13372 
13373     if (FD && FD->hasAttr<NakedAttr>()) {
13374       for (const Stmt *S : Body->children()) {
13375         // Allow local register variables without initializer as they don't
13376         // require prologue.
13377         bool RegisterVariables = false;
13378         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13379           for (const auto *Decl : DS->decls()) {
13380             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13381               RegisterVariables =
13382                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13383               if (!RegisterVariables)
13384                 break;
13385             }
13386           }
13387         }
13388         if (RegisterVariables)
13389           continue;
13390         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13391           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13392           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13393           FD->setInvalidDecl();
13394           break;
13395         }
13396       }
13397     }
13398 
13399     assert(ExprCleanupObjects.size() ==
13400                ExprEvalContexts.back().NumCleanupObjects &&
13401            "Leftover temporaries in function");
13402     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13403     assert(MaybeODRUseExprs.empty() &&
13404            "Leftover expressions for odr-use checking");
13405   }
13406 
13407   if (!IsInstantiation)
13408     PopDeclContext();
13409 
13410   PopFunctionScopeInfo(ActivePolicy, dcl);
13411   // If any errors have occurred, clear out any temporaries that may have
13412   // been leftover. This ensures that these temporaries won't be picked up for
13413   // deletion in some later function.
13414   if (getDiagnostics().hasErrorOccurred()) {
13415     DiscardCleanupsInEvaluationContext();
13416   }
13417 
13418   return dcl;
13419 }
13420 
13421 /// When we finish delayed parsing of an attribute, we must attach it to the
13422 /// relevant Decl.
13423 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13424                                        ParsedAttributes &Attrs) {
13425   // Always attach attributes to the underlying decl.
13426   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13427     D = TD->getTemplatedDecl();
13428   ProcessDeclAttributeList(S, D, Attrs);
13429 
13430   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13431     if (Method->isStatic())
13432       checkThisInStaticMemberFunctionAttributes(Method);
13433 }
13434 
13435 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13436 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13437 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13438                                           IdentifierInfo &II, Scope *S) {
13439   // Find the scope in which the identifier is injected and the corresponding
13440   // DeclContext.
13441   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13442   // In that case, we inject the declaration into the translation unit scope
13443   // instead.
13444   Scope *BlockScope = S;
13445   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13446     BlockScope = BlockScope->getParent();
13447 
13448   Scope *ContextScope = BlockScope;
13449   while (!ContextScope->getEntity())
13450     ContextScope = ContextScope->getParent();
13451   ContextRAII SavedContext(*this, ContextScope->getEntity());
13452 
13453   // Before we produce a declaration for an implicitly defined
13454   // function, see whether there was a locally-scoped declaration of
13455   // this name as a function or variable. If so, use that
13456   // (non-visible) declaration, and complain about it.
13457   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13458   if (ExternCPrev) {
13459     // We still need to inject the function into the enclosing block scope so
13460     // that later (non-call) uses can see it.
13461     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13462 
13463     // C89 footnote 38:
13464     //   If in fact it is not defined as having type "function returning int",
13465     //   the behavior is undefined.
13466     if (!isa<FunctionDecl>(ExternCPrev) ||
13467         !Context.typesAreCompatible(
13468             cast<FunctionDecl>(ExternCPrev)->getType(),
13469             Context.getFunctionNoProtoType(Context.IntTy))) {
13470       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13471           << ExternCPrev << !getLangOpts().C99;
13472       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13473       return ExternCPrev;
13474     }
13475   }
13476 
13477   // Extension in C99.  Legal in C90, but warn about it.
13478   unsigned diag_id;
13479   if (II.getName().startswith("__builtin_"))
13480     diag_id = diag::warn_builtin_unknown;
13481   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13482   else if (getLangOpts().OpenCL)
13483     diag_id = diag::err_opencl_implicit_function_decl;
13484   else if (getLangOpts().C99)
13485     diag_id = diag::ext_implicit_function_decl;
13486   else
13487     diag_id = diag::warn_implicit_function_decl;
13488   Diag(Loc, diag_id) << &II;
13489 
13490   // If we found a prior declaration of this function, don't bother building
13491   // another one. We've already pushed that one into scope, so there's nothing
13492   // more to do.
13493   if (ExternCPrev)
13494     return ExternCPrev;
13495 
13496   // Because typo correction is expensive, only do it if the implicit
13497   // function declaration is going to be treated as an error.
13498   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13499     TypoCorrection Corrected;
13500     if (S &&
13501         (Corrected = CorrectTypo(
13502              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13503              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13504       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13505                    /*ErrorRecovery*/false);
13506   }
13507 
13508   // Set a Declarator for the implicit definition: int foo();
13509   const char *Dummy;
13510   AttributeFactory attrFactory;
13511   DeclSpec DS(attrFactory);
13512   unsigned DiagID;
13513   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13514                                   Context.getPrintingPolicy());
13515   (void)Error; // Silence warning.
13516   assert(!Error && "Error setting up implicit decl!");
13517   SourceLocation NoLoc;
13518   Declarator D(DS, DeclaratorContext::BlockContext);
13519   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13520                                              /*IsAmbiguous=*/false,
13521                                              /*LParenLoc=*/NoLoc,
13522                                              /*Params=*/nullptr,
13523                                              /*NumParams=*/0,
13524                                              /*EllipsisLoc=*/NoLoc,
13525                                              /*RParenLoc=*/NoLoc,
13526                                              /*RefQualifierIsLvalueRef=*/true,
13527                                              /*RefQualifierLoc=*/NoLoc,
13528                                              /*MutableLoc=*/NoLoc, EST_None,
13529                                              /*ESpecRange=*/SourceRange(),
13530                                              /*Exceptions=*/nullptr,
13531                                              /*ExceptionRanges=*/nullptr,
13532                                              /*NumExceptions=*/0,
13533                                              /*NoexceptExpr=*/nullptr,
13534                                              /*ExceptionSpecTokens=*/nullptr,
13535                                              /*DeclsInPrototype=*/None, Loc,
13536                                              Loc, D),
13537                 std::move(DS.getAttributes()), SourceLocation());
13538   D.SetIdentifier(&II, Loc);
13539 
13540   // Insert this function into the enclosing block scope.
13541   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13542   FD->setImplicit();
13543 
13544   AddKnownFunctionAttributes(FD);
13545 
13546   return FD;
13547 }
13548 
13549 /// Adds any function attributes that we know a priori based on
13550 /// the declaration of this function.
13551 ///
13552 /// These attributes can apply both to implicitly-declared builtins
13553 /// (like __builtin___printf_chk) or to library-declared functions
13554 /// like NSLog or printf.
13555 ///
13556 /// We need to check for duplicate attributes both here and where user-written
13557 /// attributes are applied to declarations.
13558 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13559   if (FD->isInvalidDecl())
13560     return;
13561 
13562   // If this is a built-in function, map its builtin attributes to
13563   // actual attributes.
13564   if (unsigned BuiltinID = FD->getBuiltinID()) {
13565     // Handle printf-formatting attributes.
13566     unsigned FormatIdx;
13567     bool HasVAListArg;
13568     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13569       if (!FD->hasAttr<FormatAttr>()) {
13570         const char *fmt = "printf";
13571         unsigned int NumParams = FD->getNumParams();
13572         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13573             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13574           fmt = "NSString";
13575         FD->addAttr(FormatAttr::CreateImplicit(Context,
13576                                                &Context.Idents.get(fmt),
13577                                                FormatIdx+1,
13578                                                HasVAListArg ? 0 : FormatIdx+2,
13579                                                FD->getLocation()));
13580       }
13581     }
13582     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13583                                              HasVAListArg)) {
13584      if (!FD->hasAttr<FormatAttr>())
13585        FD->addAttr(FormatAttr::CreateImplicit(Context,
13586                                               &Context.Idents.get("scanf"),
13587                                               FormatIdx+1,
13588                                               HasVAListArg ? 0 : FormatIdx+2,
13589                                               FD->getLocation()));
13590     }
13591 
13592     // Handle automatically recognized callbacks.
13593     SmallVector<int, 4> Encoding;
13594     if (!FD->hasAttr<CallbackAttr>() &&
13595         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13596       FD->addAttr(CallbackAttr::CreateImplicit(
13597           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13598 
13599     // Mark const if we don't care about errno and that is the only thing
13600     // preventing the function from being const. This allows IRgen to use LLVM
13601     // intrinsics for such functions.
13602     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13603         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13604       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13605 
13606     // We make "fma" on some platforms const because we know it does not set
13607     // errno in those environments even though it could set errno based on the
13608     // C standard.
13609     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13610     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13611         !FD->hasAttr<ConstAttr>()) {
13612       switch (BuiltinID) {
13613       case Builtin::BI__builtin_fma:
13614       case Builtin::BI__builtin_fmaf:
13615       case Builtin::BI__builtin_fmal:
13616       case Builtin::BIfma:
13617       case Builtin::BIfmaf:
13618       case Builtin::BIfmal:
13619         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13620         break;
13621       default:
13622         break;
13623       }
13624     }
13625 
13626     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13627         !FD->hasAttr<ReturnsTwiceAttr>())
13628       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13629                                          FD->getLocation()));
13630     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13631       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13632     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13633       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13634     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13635       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13636     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13637         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13638       // Add the appropriate attribute, depending on the CUDA compilation mode
13639       // and which target the builtin belongs to. For example, during host
13640       // compilation, aux builtins are __device__, while the rest are __host__.
13641       if (getLangOpts().CUDAIsDevice !=
13642           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13643         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13644       else
13645         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13646     }
13647   }
13648 
13649   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13650   // throw, add an implicit nothrow attribute to any extern "C" function we come
13651   // across.
13652   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13653       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13654     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13655     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13656       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13657   }
13658 
13659   IdentifierInfo *Name = FD->getIdentifier();
13660   if (!Name)
13661     return;
13662   if ((!getLangOpts().CPlusPlus &&
13663        FD->getDeclContext()->isTranslationUnit()) ||
13664       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13665        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13666        LinkageSpecDecl::lang_c)) {
13667     // Okay: this could be a libc/libm/Objective-C function we know
13668     // about.
13669   } else
13670     return;
13671 
13672   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13673     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13674     // target-specific builtins, perhaps?
13675     if (!FD->hasAttr<FormatAttr>())
13676       FD->addAttr(FormatAttr::CreateImplicit(Context,
13677                                              &Context.Idents.get("printf"), 2,
13678                                              Name->isStr("vasprintf") ? 0 : 3,
13679                                              FD->getLocation()));
13680   }
13681 
13682   if (Name->isStr("__CFStringMakeConstantString")) {
13683     // We already have a __builtin___CFStringMakeConstantString,
13684     // but builds that use -fno-constant-cfstrings don't go through that.
13685     if (!FD->hasAttr<FormatArgAttr>())
13686       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13687                                                 FD->getLocation()));
13688   }
13689 }
13690 
13691 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13692                                     TypeSourceInfo *TInfo) {
13693   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13694   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13695 
13696   if (!TInfo) {
13697     assert(D.isInvalidType() && "no declarator info for valid type");
13698     TInfo = Context.getTrivialTypeSourceInfo(T);
13699   }
13700 
13701   // Scope manipulation handled by caller.
13702   TypedefDecl *NewTD =
13703       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13704                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13705 
13706   // Bail out immediately if we have an invalid declaration.
13707   if (D.isInvalidType()) {
13708     NewTD->setInvalidDecl();
13709     return NewTD;
13710   }
13711 
13712   if (D.getDeclSpec().isModulePrivateSpecified()) {
13713     if (CurContext->isFunctionOrMethod())
13714       Diag(NewTD->getLocation(), diag::err_module_private_local)
13715         << 2 << NewTD->getDeclName()
13716         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13717         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13718     else
13719       NewTD->setModulePrivate();
13720   }
13721 
13722   // C++ [dcl.typedef]p8:
13723   //   If the typedef declaration defines an unnamed class (or
13724   //   enum), the first typedef-name declared by the declaration
13725   //   to be that class type (or enum type) is used to denote the
13726   //   class type (or enum type) for linkage purposes only.
13727   // We need to check whether the type was declared in the declaration.
13728   switch (D.getDeclSpec().getTypeSpecType()) {
13729   case TST_enum:
13730   case TST_struct:
13731   case TST_interface:
13732   case TST_union:
13733   case TST_class: {
13734     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13735     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13736     break;
13737   }
13738 
13739   default:
13740     break;
13741   }
13742 
13743   return NewTD;
13744 }
13745 
13746 /// Check that this is a valid underlying type for an enum declaration.
13747 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13748   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13749   QualType T = TI->getType();
13750 
13751   if (T->isDependentType())
13752     return false;
13753 
13754   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13755     if (BT->isInteger())
13756       return false;
13757 
13758   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13759   return true;
13760 }
13761 
13762 /// Check whether this is a valid redeclaration of a previous enumeration.
13763 /// \return true if the redeclaration was invalid.
13764 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13765                                   QualType EnumUnderlyingTy, bool IsFixed,
13766                                   const EnumDecl *Prev) {
13767   if (IsScoped != Prev->isScoped()) {
13768     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13769       << Prev->isScoped();
13770     Diag(Prev->getLocation(), diag::note_previous_declaration);
13771     return true;
13772   }
13773 
13774   if (IsFixed && Prev->isFixed()) {
13775     if (!EnumUnderlyingTy->isDependentType() &&
13776         !Prev->getIntegerType()->isDependentType() &&
13777         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13778                                         Prev->getIntegerType())) {
13779       // TODO: Highlight the underlying type of the redeclaration.
13780       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13781         << EnumUnderlyingTy << Prev->getIntegerType();
13782       Diag(Prev->getLocation(), diag::note_previous_declaration)
13783           << Prev->getIntegerTypeRange();
13784       return true;
13785     }
13786   } else if (IsFixed != Prev->isFixed()) {
13787     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13788       << Prev->isFixed();
13789     Diag(Prev->getLocation(), diag::note_previous_declaration);
13790     return true;
13791   }
13792 
13793   return false;
13794 }
13795 
13796 /// Get diagnostic %select index for tag kind for
13797 /// redeclaration diagnostic message.
13798 /// WARNING: Indexes apply to particular diagnostics only!
13799 ///
13800 /// \returns diagnostic %select index.
13801 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13802   switch (Tag) {
13803   case TTK_Struct: return 0;
13804   case TTK_Interface: return 1;
13805   case TTK_Class:  return 2;
13806   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13807   }
13808 }
13809 
13810 /// Determine if tag kind is a class-key compatible with
13811 /// class for redeclaration (class, struct, or __interface).
13812 ///
13813 /// \returns true iff the tag kind is compatible.
13814 static bool isClassCompatTagKind(TagTypeKind Tag)
13815 {
13816   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13817 }
13818 
13819 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13820                                              TagTypeKind TTK) {
13821   if (isa<TypedefDecl>(PrevDecl))
13822     return NTK_Typedef;
13823   else if (isa<TypeAliasDecl>(PrevDecl))
13824     return NTK_TypeAlias;
13825   else if (isa<ClassTemplateDecl>(PrevDecl))
13826     return NTK_Template;
13827   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13828     return NTK_TypeAliasTemplate;
13829   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13830     return NTK_TemplateTemplateArgument;
13831   switch (TTK) {
13832   case TTK_Struct:
13833   case TTK_Interface:
13834   case TTK_Class:
13835     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13836   case TTK_Union:
13837     return NTK_NonUnion;
13838   case TTK_Enum:
13839     return NTK_NonEnum;
13840   }
13841   llvm_unreachable("invalid TTK");
13842 }
13843 
13844 /// Determine whether a tag with a given kind is acceptable
13845 /// as a redeclaration of the given tag declaration.
13846 ///
13847 /// \returns true if the new tag kind is acceptable, false otherwise.
13848 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13849                                         TagTypeKind NewTag, bool isDefinition,
13850                                         SourceLocation NewTagLoc,
13851                                         const IdentifierInfo *Name) {
13852   // C++ [dcl.type.elab]p3:
13853   //   The class-key or enum keyword present in the
13854   //   elaborated-type-specifier shall agree in kind with the
13855   //   declaration to which the name in the elaborated-type-specifier
13856   //   refers. This rule also applies to the form of
13857   //   elaborated-type-specifier that declares a class-name or
13858   //   friend class since it can be construed as referring to the
13859   //   definition of the class. Thus, in any
13860   //   elaborated-type-specifier, the enum keyword shall be used to
13861   //   refer to an enumeration (7.2), the union class-key shall be
13862   //   used to refer to a union (clause 9), and either the class or
13863   //   struct class-key shall be used to refer to a class (clause 9)
13864   //   declared using the class or struct class-key.
13865   TagTypeKind OldTag = Previous->getTagKind();
13866   if (OldTag != NewTag &&
13867       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
13868     return false;
13869 
13870   // Tags are compatible, but we might still want to warn on mismatched tags.
13871   // Non-class tags can't be mismatched at this point.
13872   if (!isClassCompatTagKind(NewTag))
13873     return true;
13874 
13875   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
13876   // by our warning analysis. We don't want to warn about mismatches with (eg)
13877   // declarations in system headers that are designed to be specialized, but if
13878   // a user asks us to warn, we should warn if their code contains mismatched
13879   // declarations.
13880   auto IsIgnoredLoc = [&](SourceLocation Loc) {
13881     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
13882                                       Loc);
13883   };
13884   if (IsIgnoredLoc(NewTagLoc))
13885     return true;
13886 
13887   auto IsIgnored = [&](const TagDecl *Tag) {
13888     return IsIgnoredLoc(Tag->getLocation());
13889   };
13890   while (IsIgnored(Previous)) {
13891     Previous = Previous->getPreviousDecl();
13892     if (!Previous)
13893       return true;
13894     OldTag = Previous->getTagKind();
13895   }
13896 
13897   bool isTemplate = false;
13898   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13899     isTemplate = Record->getDescribedClassTemplate();
13900 
13901   if (inTemplateInstantiation()) {
13902     if (OldTag != NewTag) {
13903       // In a template instantiation, do not offer fix-its for tag mismatches
13904       // since they usually mess up the template instead of fixing the problem.
13905       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13906         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13907         << getRedeclDiagFromTagKind(OldTag);
13908       // FIXME: Note previous location?
13909     }
13910     return true;
13911   }
13912 
13913   if (isDefinition) {
13914     // On definitions, check all previous tags and issue a fix-it for each
13915     // one that doesn't match the current tag.
13916     if (Previous->getDefinition()) {
13917       // Don't suggest fix-its for redefinitions.
13918       return true;
13919     }
13920 
13921     bool previousMismatch = false;
13922     for (const TagDecl *I : Previous->redecls()) {
13923       if (I->getTagKind() != NewTag) {
13924         // Ignore previous declarations for which the warning was disabled.
13925         if (IsIgnored(I))
13926           continue;
13927 
13928         if (!previousMismatch) {
13929           previousMismatch = true;
13930           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13931             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13932             << getRedeclDiagFromTagKind(I->getTagKind());
13933         }
13934         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13935           << getRedeclDiagFromTagKind(NewTag)
13936           << FixItHint::CreateReplacement(I->getInnerLocStart(),
13937                TypeWithKeyword::getTagTypeKindName(NewTag));
13938       }
13939     }
13940     return true;
13941   }
13942 
13943   // Identify the prevailing tag kind: this is the kind of the definition (if
13944   // there is a non-ignored definition), or otherwise the kind of the prior
13945   // (non-ignored) declaration.
13946   const TagDecl *PrevDef = Previous->getDefinition();
13947   if (PrevDef && IsIgnored(PrevDef))
13948     PrevDef = nullptr;
13949   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
13950   if (Redecl->getTagKind() != NewTag) {
13951     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13952       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13953       << getRedeclDiagFromTagKind(OldTag);
13954     Diag(Redecl->getLocation(), diag::note_previous_use);
13955 
13956     // If there is a previous definition, suggest a fix-it.
13957     if (PrevDef) {
13958       Diag(NewTagLoc, diag::note_struct_class_suggestion)
13959         << getRedeclDiagFromTagKind(Redecl->getTagKind())
13960         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13961              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13962     }
13963   }
13964 
13965   return true;
13966 }
13967 
13968 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13969 /// from an outer enclosing namespace or file scope inside a friend declaration.
13970 /// This should provide the commented out code in the following snippet:
13971 ///   namespace N {
13972 ///     struct X;
13973 ///     namespace M {
13974 ///       struct Y { friend struct /*N::*/ X; };
13975 ///     }
13976 ///   }
13977 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13978                                          SourceLocation NameLoc) {
13979   // While the decl is in a namespace, do repeated lookup of that name and see
13980   // if we get the same namespace back.  If we do not, continue until
13981   // translation unit scope, at which point we have a fully qualified NNS.
13982   SmallVector<IdentifierInfo *, 4> Namespaces;
13983   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13984   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13985     // This tag should be declared in a namespace, which can only be enclosed by
13986     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13987     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13988     if (!Namespace || Namespace->isAnonymousNamespace())
13989       return FixItHint();
13990     IdentifierInfo *II = Namespace->getIdentifier();
13991     Namespaces.push_back(II);
13992     NamedDecl *Lookup = SemaRef.LookupSingleName(
13993         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13994     if (Lookup == Namespace)
13995       break;
13996   }
13997 
13998   // Once we have all the namespaces, reverse them to go outermost first, and
13999   // build an NNS.
14000   SmallString<64> Insertion;
14001   llvm::raw_svector_ostream OS(Insertion);
14002   if (DC->isTranslationUnit())
14003     OS << "::";
14004   std::reverse(Namespaces.begin(), Namespaces.end());
14005   for (auto *II : Namespaces)
14006     OS << II->getName() << "::";
14007   return FixItHint::CreateInsertion(NameLoc, Insertion);
14008 }
14009 
14010 /// Determine whether a tag originally declared in context \p OldDC can
14011 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14012 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14013 /// using-declaration).
14014 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14015                                          DeclContext *NewDC) {
14016   OldDC = OldDC->getRedeclContext();
14017   NewDC = NewDC->getRedeclContext();
14018 
14019   if (OldDC->Equals(NewDC))
14020     return true;
14021 
14022   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14023   // encloses the other).
14024   if (S.getLangOpts().MSVCCompat &&
14025       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14026     return true;
14027 
14028   return false;
14029 }
14030 
14031 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14032 /// former case, Name will be non-null.  In the later case, Name will be null.
14033 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14034 /// reference/declaration/definition of a tag.
14035 ///
14036 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14037 /// trailing-type-specifier) other than one in an alias-declaration.
14038 ///
14039 /// \param SkipBody If non-null, will be set to indicate if the caller should
14040 /// skip the definition of this tag and treat it as if it were a declaration.
14041 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14042                      SourceLocation KWLoc, CXXScopeSpec &SS,
14043                      IdentifierInfo *Name, SourceLocation NameLoc,
14044                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14045                      SourceLocation ModulePrivateLoc,
14046                      MultiTemplateParamsArg TemplateParameterLists,
14047                      bool &OwnedDecl, bool &IsDependent,
14048                      SourceLocation ScopedEnumKWLoc,
14049                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14050                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14051                      SkipBodyInfo *SkipBody) {
14052   // If this is not a definition, it must have a name.
14053   IdentifierInfo *OrigName = Name;
14054   assert((Name != nullptr || TUK == TUK_Definition) &&
14055          "Nameless record must be a definition!");
14056   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14057 
14058   OwnedDecl = false;
14059   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14060   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14061 
14062   // FIXME: Check member specializations more carefully.
14063   bool isMemberSpecialization = false;
14064   bool Invalid = false;
14065 
14066   // We only need to do this matching if we have template parameters
14067   // or a scope specifier, which also conveniently avoids this work
14068   // for non-C++ cases.
14069   if (TemplateParameterLists.size() > 0 ||
14070       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14071     if (TemplateParameterList *TemplateParams =
14072             MatchTemplateParametersToScopeSpecifier(
14073                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14074                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14075       if (Kind == TTK_Enum) {
14076         Diag(KWLoc, diag::err_enum_template);
14077         return nullptr;
14078       }
14079 
14080       if (TemplateParams->size() > 0) {
14081         // This is a declaration or definition of a class template (which may
14082         // be a member of another template).
14083 
14084         if (Invalid)
14085           return nullptr;
14086 
14087         OwnedDecl = false;
14088         DeclResult Result = CheckClassTemplate(
14089             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14090             AS, ModulePrivateLoc,
14091             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14092             TemplateParameterLists.data(), SkipBody);
14093         return Result.get();
14094       } else {
14095         // The "template<>" header is extraneous.
14096         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14097           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14098         isMemberSpecialization = true;
14099       }
14100     }
14101   }
14102 
14103   // Figure out the underlying type if this a enum declaration. We need to do
14104   // this early, because it's needed to detect if this is an incompatible
14105   // redeclaration.
14106   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14107   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14108 
14109   if (Kind == TTK_Enum) {
14110     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14111       // No underlying type explicitly specified, or we failed to parse the
14112       // type, default to int.
14113       EnumUnderlying = Context.IntTy.getTypePtr();
14114     } else if (UnderlyingType.get()) {
14115       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14116       // integral type; any cv-qualification is ignored.
14117       TypeSourceInfo *TI = nullptr;
14118       GetTypeFromParser(UnderlyingType.get(), &TI);
14119       EnumUnderlying = TI;
14120 
14121       if (CheckEnumUnderlyingType(TI))
14122         // Recover by falling back to int.
14123         EnumUnderlying = Context.IntTy.getTypePtr();
14124 
14125       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14126                                           UPPC_FixedUnderlyingType))
14127         EnumUnderlying = Context.IntTy.getTypePtr();
14128 
14129     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14130       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14131       // of 'int'. However, if this is an unfixed forward declaration, don't set
14132       // the underlying type unless the user enables -fms-compatibility. This
14133       // makes unfixed forward declared enums incomplete and is more conforming.
14134       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14135         EnumUnderlying = Context.IntTy.getTypePtr();
14136     }
14137   }
14138 
14139   DeclContext *SearchDC = CurContext;
14140   DeclContext *DC = CurContext;
14141   bool isStdBadAlloc = false;
14142   bool isStdAlignValT = false;
14143 
14144   RedeclarationKind Redecl = forRedeclarationInCurContext();
14145   if (TUK == TUK_Friend || TUK == TUK_Reference)
14146     Redecl = NotForRedeclaration;
14147 
14148   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14149   /// implemented asks for structural equivalence checking, the returned decl
14150   /// here is passed back to the parser, allowing the tag body to be parsed.
14151   auto createTagFromNewDecl = [&]() -> TagDecl * {
14152     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14153     // If there is an identifier, use the location of the identifier as the
14154     // location of the decl, otherwise use the location of the struct/union
14155     // keyword.
14156     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14157     TagDecl *New = nullptr;
14158 
14159     if (Kind == TTK_Enum) {
14160       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14161                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14162       // If this is an undefined enum, bail.
14163       if (TUK != TUK_Definition && !Invalid)
14164         return nullptr;
14165       if (EnumUnderlying) {
14166         EnumDecl *ED = cast<EnumDecl>(New);
14167         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14168           ED->setIntegerTypeSourceInfo(TI);
14169         else
14170           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14171         ED->setPromotionType(ED->getIntegerType());
14172       }
14173     } else { // struct/union
14174       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14175                                nullptr);
14176     }
14177 
14178     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14179       // Add alignment attributes if necessary; these attributes are checked
14180       // when the ASTContext lays out the structure.
14181       //
14182       // It is important for implementing the correct semantics that this
14183       // happen here (in ActOnTag). The #pragma pack stack is
14184       // maintained as a result of parser callbacks which can occur at
14185       // many points during the parsing of a struct declaration (because
14186       // the #pragma tokens are effectively skipped over during the
14187       // parsing of the struct).
14188       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14189         AddAlignmentAttributesForRecord(RD);
14190         AddMsStructLayoutForRecord(RD);
14191       }
14192     }
14193     New->setLexicalDeclContext(CurContext);
14194     return New;
14195   };
14196 
14197   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14198   if (Name && SS.isNotEmpty()) {
14199     // We have a nested-name tag ('struct foo::bar').
14200 
14201     // Check for invalid 'foo::'.
14202     if (SS.isInvalid()) {
14203       Name = nullptr;
14204       goto CreateNewDecl;
14205     }
14206 
14207     // If this is a friend or a reference to a class in a dependent
14208     // context, don't try to make a decl for it.
14209     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14210       DC = computeDeclContext(SS, false);
14211       if (!DC) {
14212         IsDependent = true;
14213         return nullptr;
14214       }
14215     } else {
14216       DC = computeDeclContext(SS, true);
14217       if (!DC) {
14218         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14219           << SS.getRange();
14220         return nullptr;
14221       }
14222     }
14223 
14224     if (RequireCompleteDeclContext(SS, DC))
14225       return nullptr;
14226 
14227     SearchDC = DC;
14228     // Look-up name inside 'foo::'.
14229     LookupQualifiedName(Previous, DC);
14230 
14231     if (Previous.isAmbiguous())
14232       return nullptr;
14233 
14234     if (Previous.empty()) {
14235       // Name lookup did not find anything. However, if the
14236       // nested-name-specifier refers to the current instantiation,
14237       // and that current instantiation has any dependent base
14238       // classes, we might find something at instantiation time: treat
14239       // this as a dependent elaborated-type-specifier.
14240       // But this only makes any sense for reference-like lookups.
14241       if (Previous.wasNotFoundInCurrentInstantiation() &&
14242           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14243         IsDependent = true;
14244         return nullptr;
14245       }
14246 
14247       // A tag 'foo::bar' must already exist.
14248       Diag(NameLoc, diag::err_not_tag_in_scope)
14249         << Kind << Name << DC << SS.getRange();
14250       Name = nullptr;
14251       Invalid = true;
14252       goto CreateNewDecl;
14253     }
14254   } else if (Name) {
14255     // C++14 [class.mem]p14:
14256     //   If T is the name of a class, then each of the following shall have a
14257     //   name different from T:
14258     //    -- every member of class T that is itself a type
14259     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14260         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14261       return nullptr;
14262 
14263     // If this is a named struct, check to see if there was a previous forward
14264     // declaration or definition.
14265     // FIXME: We're looking into outer scopes here, even when we
14266     // shouldn't be. Doing so can result in ambiguities that we
14267     // shouldn't be diagnosing.
14268     LookupName(Previous, S);
14269 
14270     // When declaring or defining a tag, ignore ambiguities introduced
14271     // by types using'ed into this scope.
14272     if (Previous.isAmbiguous() &&
14273         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14274       LookupResult::Filter F = Previous.makeFilter();
14275       while (F.hasNext()) {
14276         NamedDecl *ND = F.next();
14277         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14278                 SearchDC->getRedeclContext()))
14279           F.erase();
14280       }
14281       F.done();
14282     }
14283 
14284     // C++11 [namespace.memdef]p3:
14285     //   If the name in a friend declaration is neither qualified nor
14286     //   a template-id and the declaration is a function or an
14287     //   elaborated-type-specifier, the lookup to determine whether
14288     //   the entity has been previously declared shall not consider
14289     //   any scopes outside the innermost enclosing namespace.
14290     //
14291     // MSVC doesn't implement the above rule for types, so a friend tag
14292     // declaration may be a redeclaration of a type declared in an enclosing
14293     // scope.  They do implement this rule for friend functions.
14294     //
14295     // Does it matter that this should be by scope instead of by
14296     // semantic context?
14297     if (!Previous.empty() && TUK == TUK_Friend) {
14298       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14299       LookupResult::Filter F = Previous.makeFilter();
14300       bool FriendSawTagOutsideEnclosingNamespace = false;
14301       while (F.hasNext()) {
14302         NamedDecl *ND = F.next();
14303         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14304         if (DC->isFileContext() &&
14305             !EnclosingNS->Encloses(ND->getDeclContext())) {
14306           if (getLangOpts().MSVCCompat)
14307             FriendSawTagOutsideEnclosingNamespace = true;
14308           else
14309             F.erase();
14310         }
14311       }
14312       F.done();
14313 
14314       // Diagnose this MSVC extension in the easy case where lookup would have
14315       // unambiguously found something outside the enclosing namespace.
14316       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14317         NamedDecl *ND = Previous.getFoundDecl();
14318         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14319             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14320       }
14321     }
14322 
14323     // Note:  there used to be some attempt at recovery here.
14324     if (Previous.isAmbiguous())
14325       return nullptr;
14326 
14327     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14328       // FIXME: This makes sure that we ignore the contexts associated
14329       // with C structs, unions, and enums when looking for a matching
14330       // tag declaration or definition. See the similar lookup tweak
14331       // in Sema::LookupName; is there a better way to deal with this?
14332       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14333         SearchDC = SearchDC->getParent();
14334     }
14335   }
14336 
14337   if (Previous.isSingleResult() &&
14338       Previous.getFoundDecl()->isTemplateParameter()) {
14339     // Maybe we will complain about the shadowed template parameter.
14340     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14341     // Just pretend that we didn't see the previous declaration.
14342     Previous.clear();
14343   }
14344 
14345   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14346       DC->Equals(getStdNamespace())) {
14347     if (Name->isStr("bad_alloc")) {
14348       // This is a declaration of or a reference to "std::bad_alloc".
14349       isStdBadAlloc = true;
14350 
14351       // If std::bad_alloc has been implicitly declared (but made invisible to
14352       // name lookup), fill in this implicit declaration as the previous
14353       // declaration, so that the declarations get chained appropriately.
14354       if (Previous.empty() && StdBadAlloc)
14355         Previous.addDecl(getStdBadAlloc());
14356     } else if (Name->isStr("align_val_t")) {
14357       isStdAlignValT = true;
14358       if (Previous.empty() && StdAlignValT)
14359         Previous.addDecl(getStdAlignValT());
14360     }
14361   }
14362 
14363   // If we didn't find a previous declaration, and this is a reference
14364   // (or friend reference), move to the correct scope.  In C++, we
14365   // also need to do a redeclaration lookup there, just in case
14366   // there's a shadow friend decl.
14367   if (Name && Previous.empty() &&
14368       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14369     if (Invalid) goto CreateNewDecl;
14370     assert(SS.isEmpty());
14371 
14372     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14373       // C++ [basic.scope.pdecl]p5:
14374       //   -- for an elaborated-type-specifier of the form
14375       //
14376       //          class-key identifier
14377       //
14378       //      if the elaborated-type-specifier is used in the
14379       //      decl-specifier-seq or parameter-declaration-clause of a
14380       //      function defined in namespace scope, the identifier is
14381       //      declared as a class-name in the namespace that contains
14382       //      the declaration; otherwise, except as a friend
14383       //      declaration, the identifier is declared in the smallest
14384       //      non-class, non-function-prototype scope that contains the
14385       //      declaration.
14386       //
14387       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14388       // C structs and unions.
14389       //
14390       // It is an error in C++ to declare (rather than define) an enum
14391       // type, including via an elaborated type specifier.  We'll
14392       // diagnose that later; for now, declare the enum in the same
14393       // scope as we would have picked for any other tag type.
14394       //
14395       // GNU C also supports this behavior as part of its incomplete
14396       // enum types extension, while GNU C++ does not.
14397       //
14398       // Find the context where we'll be declaring the tag.
14399       // FIXME: We would like to maintain the current DeclContext as the
14400       // lexical context,
14401       SearchDC = getTagInjectionContext(SearchDC);
14402 
14403       // Find the scope where we'll be declaring the tag.
14404       S = getTagInjectionScope(S, getLangOpts());
14405     } else {
14406       assert(TUK == TUK_Friend);
14407       // C++ [namespace.memdef]p3:
14408       //   If a friend declaration in a non-local class first declares a
14409       //   class or function, the friend class or function is a member of
14410       //   the innermost enclosing namespace.
14411       SearchDC = SearchDC->getEnclosingNamespaceContext();
14412     }
14413 
14414     // In C++, we need to do a redeclaration lookup to properly
14415     // diagnose some problems.
14416     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14417     // hidden declaration so that we don't get ambiguity errors when using a
14418     // type declared by an elaborated-type-specifier.  In C that is not correct
14419     // and we should instead merge compatible types found by lookup.
14420     if (getLangOpts().CPlusPlus) {
14421       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14422       LookupQualifiedName(Previous, SearchDC);
14423     } else {
14424       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14425       LookupName(Previous, S);
14426     }
14427   }
14428 
14429   // If we have a known previous declaration to use, then use it.
14430   if (Previous.empty() && SkipBody && SkipBody->Previous)
14431     Previous.addDecl(SkipBody->Previous);
14432 
14433   if (!Previous.empty()) {
14434     NamedDecl *PrevDecl = Previous.getFoundDecl();
14435     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14436 
14437     // It's okay to have a tag decl in the same scope as a typedef
14438     // which hides a tag decl in the same scope.  Finding this
14439     // insanity with a redeclaration lookup can only actually happen
14440     // in C++.
14441     //
14442     // This is also okay for elaborated-type-specifiers, which is
14443     // technically forbidden by the current standard but which is
14444     // okay according to the likely resolution of an open issue;
14445     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14446     if (getLangOpts().CPlusPlus) {
14447       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14448         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14449           TagDecl *Tag = TT->getDecl();
14450           if (Tag->getDeclName() == Name &&
14451               Tag->getDeclContext()->getRedeclContext()
14452                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14453             PrevDecl = Tag;
14454             Previous.clear();
14455             Previous.addDecl(Tag);
14456             Previous.resolveKind();
14457           }
14458         }
14459       }
14460     }
14461 
14462     // If this is a redeclaration of a using shadow declaration, it must
14463     // declare a tag in the same context. In MSVC mode, we allow a
14464     // redefinition if either context is within the other.
14465     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14466       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14467       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14468           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14469           !(OldTag && isAcceptableTagRedeclContext(
14470                           *this, OldTag->getDeclContext(), SearchDC))) {
14471         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14472         Diag(Shadow->getTargetDecl()->getLocation(),
14473              diag::note_using_decl_target);
14474         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14475             << 0;
14476         // Recover by ignoring the old declaration.
14477         Previous.clear();
14478         goto CreateNewDecl;
14479       }
14480     }
14481 
14482     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14483       // If this is a use of a previous tag, or if the tag is already declared
14484       // in the same scope (so that the definition/declaration completes or
14485       // rementions the tag), reuse the decl.
14486       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14487           isDeclInScope(DirectPrevDecl, SearchDC, S,
14488                         SS.isNotEmpty() || isMemberSpecialization)) {
14489         // Make sure that this wasn't declared as an enum and now used as a
14490         // struct or something similar.
14491         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14492                                           TUK == TUK_Definition, KWLoc,
14493                                           Name)) {
14494           bool SafeToContinue
14495             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14496                Kind != TTK_Enum);
14497           if (SafeToContinue)
14498             Diag(KWLoc, diag::err_use_with_wrong_tag)
14499               << Name
14500               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14501                                               PrevTagDecl->getKindName());
14502           else
14503             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14504           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14505 
14506           if (SafeToContinue)
14507             Kind = PrevTagDecl->getTagKind();
14508           else {
14509             // Recover by making this an anonymous redefinition.
14510             Name = nullptr;
14511             Previous.clear();
14512             Invalid = true;
14513           }
14514         }
14515 
14516         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14517           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14518 
14519           // If this is an elaborated-type-specifier for a scoped enumeration,
14520           // the 'class' keyword is not necessary and not permitted.
14521           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14522             if (ScopedEnum)
14523               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14524                 << PrevEnum->isScoped()
14525                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14526             return PrevTagDecl;
14527           }
14528 
14529           QualType EnumUnderlyingTy;
14530           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14531             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14532           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14533             EnumUnderlyingTy = QualType(T, 0);
14534 
14535           // All conflicts with previous declarations are recovered by
14536           // returning the previous declaration, unless this is a definition,
14537           // in which case we want the caller to bail out.
14538           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14539                                      ScopedEnum, EnumUnderlyingTy,
14540                                      IsFixed, PrevEnum))
14541             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14542         }
14543 
14544         // C++11 [class.mem]p1:
14545         //   A member shall not be declared twice in the member-specification,
14546         //   except that a nested class or member class template can be declared
14547         //   and then later defined.
14548         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14549             S->isDeclScope(PrevDecl)) {
14550           Diag(NameLoc, diag::ext_member_redeclared);
14551           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14552         }
14553 
14554         if (!Invalid) {
14555           // If this is a use, just return the declaration we found, unless
14556           // we have attributes.
14557           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14558             if (!Attrs.empty()) {
14559               // FIXME: Diagnose these attributes. For now, we create a new
14560               // declaration to hold them.
14561             } else if (TUK == TUK_Reference &&
14562                        (PrevTagDecl->getFriendObjectKind() ==
14563                             Decl::FOK_Undeclared ||
14564                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14565                        SS.isEmpty()) {
14566               // This declaration is a reference to an existing entity, but
14567               // has different visibility from that entity: it either makes
14568               // a friend visible or it makes a type visible in a new module.
14569               // In either case, create a new declaration. We only do this if
14570               // the declaration would have meant the same thing if no prior
14571               // declaration were found, that is, if it was found in the same
14572               // scope where we would have injected a declaration.
14573               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14574                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14575                 return PrevTagDecl;
14576               // This is in the injected scope, create a new declaration in
14577               // that scope.
14578               S = getTagInjectionScope(S, getLangOpts());
14579             } else {
14580               return PrevTagDecl;
14581             }
14582           }
14583 
14584           // Diagnose attempts to redefine a tag.
14585           if (TUK == TUK_Definition) {
14586             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14587               // If we're defining a specialization and the previous definition
14588               // is from an implicit instantiation, don't emit an error
14589               // here; we'll catch this in the general case below.
14590               bool IsExplicitSpecializationAfterInstantiation = false;
14591               if (isMemberSpecialization) {
14592                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14593                   IsExplicitSpecializationAfterInstantiation =
14594                     RD->getTemplateSpecializationKind() !=
14595                     TSK_ExplicitSpecialization;
14596                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14597                   IsExplicitSpecializationAfterInstantiation =
14598                     ED->getTemplateSpecializationKind() !=
14599                     TSK_ExplicitSpecialization;
14600               }
14601 
14602               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14603               // not keep more that one definition around (merge them). However,
14604               // ensure the decl passes the structural compatibility check in
14605               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14606               NamedDecl *Hidden = nullptr;
14607               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14608                 // There is a definition of this tag, but it is not visible. We
14609                 // explicitly make use of C++'s one definition rule here, and
14610                 // assume that this definition is identical to the hidden one
14611                 // we already have. Make the existing definition visible and
14612                 // use it in place of this one.
14613                 if (!getLangOpts().CPlusPlus) {
14614                   // Postpone making the old definition visible until after we
14615                   // complete parsing the new one and do the structural
14616                   // comparison.
14617                   SkipBody->CheckSameAsPrevious = true;
14618                   SkipBody->New = createTagFromNewDecl();
14619                   SkipBody->Previous = Def;
14620                   return Def;
14621                 } else {
14622                   SkipBody->ShouldSkip = true;
14623                   SkipBody->Previous = Def;
14624                   makeMergedDefinitionVisible(Hidden);
14625                   // Carry on and handle it like a normal definition. We'll
14626                   // skip starting the definitiion later.
14627                 }
14628               } else if (!IsExplicitSpecializationAfterInstantiation) {
14629                 // A redeclaration in function prototype scope in C isn't
14630                 // visible elsewhere, so merely issue a warning.
14631                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14632                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14633                 else
14634                   Diag(NameLoc, diag::err_redefinition) << Name;
14635                 notePreviousDefinition(Def,
14636                                        NameLoc.isValid() ? NameLoc : KWLoc);
14637                 // If this is a redefinition, recover by making this
14638                 // struct be anonymous, which will make any later
14639                 // references get the previous definition.
14640                 Name = nullptr;
14641                 Previous.clear();
14642                 Invalid = true;
14643               }
14644             } else {
14645               // If the type is currently being defined, complain
14646               // about a nested redefinition.
14647               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14648               if (TD->isBeingDefined()) {
14649                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14650                 Diag(PrevTagDecl->getLocation(),
14651                      diag::note_previous_definition);
14652                 Name = nullptr;
14653                 Previous.clear();
14654                 Invalid = true;
14655               }
14656             }
14657 
14658             // Okay, this is definition of a previously declared or referenced
14659             // tag. We're going to create a new Decl for it.
14660           }
14661 
14662           // Okay, we're going to make a redeclaration.  If this is some kind
14663           // of reference, make sure we build the redeclaration in the same DC
14664           // as the original, and ignore the current access specifier.
14665           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14666             SearchDC = PrevTagDecl->getDeclContext();
14667             AS = AS_none;
14668           }
14669         }
14670         // If we get here we have (another) forward declaration or we
14671         // have a definition.  Just create a new decl.
14672 
14673       } else {
14674         // If we get here, this is a definition of a new tag type in a nested
14675         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14676         // new decl/type.  We set PrevDecl to NULL so that the entities
14677         // have distinct types.
14678         Previous.clear();
14679       }
14680       // If we get here, we're going to create a new Decl. If PrevDecl
14681       // is non-NULL, it's a definition of the tag declared by
14682       // PrevDecl. If it's NULL, we have a new definition.
14683 
14684     // Otherwise, PrevDecl is not a tag, but was found with tag
14685     // lookup.  This is only actually possible in C++, where a few
14686     // things like templates still live in the tag namespace.
14687     } else {
14688       // Use a better diagnostic if an elaborated-type-specifier
14689       // found the wrong kind of type on the first
14690       // (non-redeclaration) lookup.
14691       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14692           !Previous.isForRedeclaration()) {
14693         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14694         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14695                                                        << Kind;
14696         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14697         Invalid = true;
14698 
14699       // Otherwise, only diagnose if the declaration is in scope.
14700       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14701                                 SS.isNotEmpty() || isMemberSpecialization)) {
14702         // do nothing
14703 
14704       // Diagnose implicit declarations introduced by elaborated types.
14705       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14706         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14707         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14708         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14709         Invalid = true;
14710 
14711       // Otherwise it's a declaration.  Call out a particularly common
14712       // case here.
14713       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14714         unsigned Kind = 0;
14715         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14716         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14717           << Name << Kind << TND->getUnderlyingType();
14718         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14719         Invalid = true;
14720 
14721       // Otherwise, diagnose.
14722       } else {
14723         // The tag name clashes with something else in the target scope,
14724         // issue an error and recover by making this tag be anonymous.
14725         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14726         notePreviousDefinition(PrevDecl, NameLoc);
14727         Name = nullptr;
14728         Invalid = true;
14729       }
14730 
14731       // The existing declaration isn't relevant to us; we're in a
14732       // new scope, so clear out the previous declaration.
14733       Previous.clear();
14734     }
14735   }
14736 
14737 CreateNewDecl:
14738 
14739   TagDecl *PrevDecl = nullptr;
14740   if (Previous.isSingleResult())
14741     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14742 
14743   // If there is an identifier, use the location of the identifier as the
14744   // location of the decl, otherwise use the location of the struct/union
14745   // keyword.
14746   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14747 
14748   // Otherwise, create a new declaration. If there is a previous
14749   // declaration of the same entity, the two will be linked via
14750   // PrevDecl.
14751   TagDecl *New;
14752 
14753   if (Kind == TTK_Enum) {
14754     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14755     // enum X { A, B, C } D;    D should chain to X.
14756     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14757                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14758                            ScopedEnumUsesClassTag, IsFixed);
14759 
14760     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14761       StdAlignValT = cast<EnumDecl>(New);
14762 
14763     // If this is an undefined enum, warn.
14764     if (TUK != TUK_Definition && !Invalid) {
14765       TagDecl *Def;
14766       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14767         // C++0x: 7.2p2: opaque-enum-declaration.
14768         // Conflicts are diagnosed above. Do nothing.
14769       }
14770       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14771         Diag(Loc, diag::ext_forward_ref_enum_def)
14772           << New;
14773         Diag(Def->getLocation(), diag::note_previous_definition);
14774       } else {
14775         unsigned DiagID = diag::ext_forward_ref_enum;
14776         if (getLangOpts().MSVCCompat)
14777           DiagID = diag::ext_ms_forward_ref_enum;
14778         else if (getLangOpts().CPlusPlus)
14779           DiagID = diag::err_forward_ref_enum;
14780         Diag(Loc, DiagID);
14781       }
14782     }
14783 
14784     if (EnumUnderlying) {
14785       EnumDecl *ED = cast<EnumDecl>(New);
14786       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14787         ED->setIntegerTypeSourceInfo(TI);
14788       else
14789         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14790       ED->setPromotionType(ED->getIntegerType());
14791       assert(ED->isComplete() && "enum with type should be complete");
14792     }
14793   } else {
14794     // struct/union/class
14795 
14796     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14797     // struct X { int A; } D;    D should chain to X.
14798     if (getLangOpts().CPlusPlus) {
14799       // FIXME: Look for a way to use RecordDecl for simple structs.
14800       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14801                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14802 
14803       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14804         StdBadAlloc = cast<CXXRecordDecl>(New);
14805     } else
14806       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14807                                cast_or_null<RecordDecl>(PrevDecl));
14808   }
14809 
14810   // C++11 [dcl.type]p3:
14811   //   A type-specifier-seq shall not define a class or enumeration [...].
14812   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14813       TUK == TUK_Definition) {
14814     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14815       << Context.getTagDeclType(New);
14816     Invalid = true;
14817   }
14818 
14819   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14820       DC->getDeclKind() == Decl::Enum) {
14821     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14822       << Context.getTagDeclType(New);
14823     Invalid = true;
14824   }
14825 
14826   // Maybe add qualifier info.
14827   if (SS.isNotEmpty()) {
14828     if (SS.isSet()) {
14829       // If this is either a declaration or a definition, check the
14830       // nested-name-specifier against the current context.
14831       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14832           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14833                                        isMemberSpecialization))
14834         Invalid = true;
14835 
14836       New->setQualifierInfo(SS.getWithLocInContext(Context));
14837       if (TemplateParameterLists.size() > 0) {
14838         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14839       }
14840     }
14841     else
14842       Invalid = true;
14843   }
14844 
14845   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14846     // Add alignment attributes if necessary; these attributes are checked when
14847     // the ASTContext lays out the structure.
14848     //
14849     // It is important for implementing the correct semantics that this
14850     // happen here (in ActOnTag). The #pragma pack stack is
14851     // maintained as a result of parser callbacks which can occur at
14852     // many points during the parsing of a struct declaration (because
14853     // the #pragma tokens are effectively skipped over during the
14854     // parsing of the struct).
14855     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14856       AddAlignmentAttributesForRecord(RD);
14857       AddMsStructLayoutForRecord(RD);
14858     }
14859   }
14860 
14861   if (ModulePrivateLoc.isValid()) {
14862     if (isMemberSpecialization)
14863       Diag(New->getLocation(), diag::err_module_private_specialization)
14864         << 2
14865         << FixItHint::CreateRemoval(ModulePrivateLoc);
14866     // __module_private__ does not apply to local classes. However, we only
14867     // diagnose this as an error when the declaration specifiers are
14868     // freestanding. Here, we just ignore the __module_private__.
14869     else if (!SearchDC->isFunctionOrMethod())
14870       New->setModulePrivate();
14871   }
14872 
14873   // If this is a specialization of a member class (of a class template),
14874   // check the specialization.
14875   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14876     Invalid = true;
14877 
14878   // If we're declaring or defining a tag in function prototype scope in C,
14879   // note that this type can only be used within the function and add it to
14880   // the list of decls to inject into the function definition scope.
14881   if ((Name || Kind == TTK_Enum) &&
14882       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14883     if (getLangOpts().CPlusPlus) {
14884       // C++ [dcl.fct]p6:
14885       //   Types shall not be defined in return or parameter types.
14886       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14887         Diag(Loc, diag::err_type_defined_in_param_type)
14888             << Name;
14889         Invalid = true;
14890       }
14891     } else if (!PrevDecl) {
14892       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14893     }
14894   }
14895 
14896   if (Invalid)
14897     New->setInvalidDecl();
14898 
14899   // Set the lexical context. If the tag has a C++ scope specifier, the
14900   // lexical context will be different from the semantic context.
14901   New->setLexicalDeclContext(CurContext);
14902 
14903   // Mark this as a friend decl if applicable.
14904   // In Microsoft mode, a friend declaration also acts as a forward
14905   // declaration so we always pass true to setObjectOfFriendDecl to make
14906   // the tag name visible.
14907   if (TUK == TUK_Friend)
14908     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14909 
14910   // Set the access specifier.
14911   if (!Invalid && SearchDC->isRecord())
14912     SetMemberAccessSpecifier(New, PrevDecl, AS);
14913 
14914   if (PrevDecl)
14915     CheckRedeclarationModuleOwnership(New, PrevDecl);
14916 
14917   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14918     New->startDefinition();
14919 
14920   ProcessDeclAttributeList(S, New, Attrs);
14921   AddPragmaAttributes(S, New);
14922 
14923   // If this has an identifier, add it to the scope stack.
14924   if (TUK == TUK_Friend) {
14925     // We might be replacing an existing declaration in the lookup tables;
14926     // if so, borrow its access specifier.
14927     if (PrevDecl)
14928       New->setAccess(PrevDecl->getAccess());
14929 
14930     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14931     DC->makeDeclVisibleInContext(New);
14932     if (Name) // can be null along some error paths
14933       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14934         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14935   } else if (Name) {
14936     S = getNonFieldDeclScope(S);
14937     PushOnScopeChains(New, S, true);
14938   } else {
14939     CurContext->addDecl(New);
14940   }
14941 
14942   // If this is the C FILE type, notify the AST context.
14943   if (IdentifierInfo *II = New->getIdentifier())
14944     if (!New->isInvalidDecl() &&
14945         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14946         II->isStr("FILE"))
14947       Context.setFILEDecl(New);
14948 
14949   if (PrevDecl)
14950     mergeDeclAttributes(New, PrevDecl);
14951 
14952   // If there's a #pragma GCC visibility in scope, set the visibility of this
14953   // record.
14954   AddPushedVisibilityAttribute(New);
14955 
14956   if (isMemberSpecialization && !New->isInvalidDecl())
14957     CompleteMemberSpecialization(New, Previous);
14958 
14959   OwnedDecl = true;
14960   // In C++, don't return an invalid declaration. We can't recover well from
14961   // the cases where we make the type anonymous.
14962   if (Invalid && getLangOpts().CPlusPlus) {
14963     if (New->isBeingDefined())
14964       if (auto RD = dyn_cast<RecordDecl>(New))
14965         RD->completeDefinition();
14966     return nullptr;
14967   } else if (SkipBody && SkipBody->ShouldSkip) {
14968     return SkipBody->Previous;
14969   } else {
14970     return New;
14971   }
14972 }
14973 
14974 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14975   AdjustDeclIfTemplate(TagD);
14976   TagDecl *Tag = cast<TagDecl>(TagD);
14977 
14978   // Enter the tag context.
14979   PushDeclContext(S, Tag);
14980 
14981   ActOnDocumentableDecl(TagD);
14982 
14983   // If there's a #pragma GCC visibility in scope, set the visibility of this
14984   // record.
14985   AddPushedVisibilityAttribute(Tag);
14986 }
14987 
14988 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14989                                     SkipBodyInfo &SkipBody) {
14990   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14991     return false;
14992 
14993   // Make the previous decl visible.
14994   makeMergedDefinitionVisible(SkipBody.Previous);
14995   return true;
14996 }
14997 
14998 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14999   assert(isa<ObjCContainerDecl>(IDecl) &&
15000          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15001   DeclContext *OCD = cast<DeclContext>(IDecl);
15002   assert(getContainingDC(OCD) == CurContext &&
15003       "The next DeclContext should be lexically contained in the current one.");
15004   CurContext = OCD;
15005   return IDecl;
15006 }
15007 
15008 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15009                                            SourceLocation FinalLoc,
15010                                            bool IsFinalSpelledSealed,
15011                                            SourceLocation LBraceLoc) {
15012   AdjustDeclIfTemplate(TagD);
15013   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15014 
15015   FieldCollector->StartClass();
15016 
15017   if (!Record->getIdentifier())
15018     return;
15019 
15020   if (FinalLoc.isValid())
15021     Record->addAttr(new (Context)
15022                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15023 
15024   // C++ [class]p2:
15025   //   [...] The class-name is also inserted into the scope of the
15026   //   class itself; this is known as the injected-class-name. For
15027   //   purposes of access checking, the injected-class-name is treated
15028   //   as if it were a public member name.
15029   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15030       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15031       Record->getLocation(), Record->getIdentifier(),
15032       /*PrevDecl=*/nullptr,
15033       /*DelayTypeCreation=*/true);
15034   Context.getTypeDeclType(InjectedClassName, Record);
15035   InjectedClassName->setImplicit();
15036   InjectedClassName->setAccess(AS_public);
15037   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15038       InjectedClassName->setDescribedClassTemplate(Template);
15039   PushOnScopeChains(InjectedClassName, S);
15040   assert(InjectedClassName->isInjectedClassName() &&
15041          "Broken injected-class-name");
15042 }
15043 
15044 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15045                                     SourceRange BraceRange) {
15046   AdjustDeclIfTemplate(TagD);
15047   TagDecl *Tag = cast<TagDecl>(TagD);
15048   Tag->setBraceRange(BraceRange);
15049 
15050   // Make sure we "complete" the definition even it is invalid.
15051   if (Tag->isBeingDefined()) {
15052     assert(Tag->isInvalidDecl() && "We should already have completed it");
15053     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15054       RD->completeDefinition();
15055   }
15056 
15057   if (isa<CXXRecordDecl>(Tag)) {
15058     FieldCollector->FinishClass();
15059   }
15060 
15061   // Exit this scope of this tag's definition.
15062   PopDeclContext();
15063 
15064   if (getCurLexicalContext()->isObjCContainer() &&
15065       Tag->getDeclContext()->isFileContext())
15066     Tag->setTopLevelDeclInObjCContainer();
15067 
15068   // Notify the consumer that we've defined a tag.
15069   if (!Tag->isInvalidDecl())
15070     Consumer.HandleTagDeclDefinition(Tag);
15071 }
15072 
15073 void Sema::ActOnObjCContainerFinishDefinition() {
15074   // Exit this scope of this interface definition.
15075   PopDeclContext();
15076 }
15077 
15078 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15079   assert(DC == CurContext && "Mismatch of container contexts");
15080   OriginalLexicalContext = DC;
15081   ActOnObjCContainerFinishDefinition();
15082 }
15083 
15084 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15085   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15086   OriginalLexicalContext = nullptr;
15087 }
15088 
15089 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15090   AdjustDeclIfTemplate(TagD);
15091   TagDecl *Tag = cast<TagDecl>(TagD);
15092   Tag->setInvalidDecl();
15093 
15094   // Make sure we "complete" the definition even it is invalid.
15095   if (Tag->isBeingDefined()) {
15096     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15097       RD->completeDefinition();
15098   }
15099 
15100   // We're undoing ActOnTagStartDefinition here, not
15101   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15102   // the FieldCollector.
15103 
15104   PopDeclContext();
15105 }
15106 
15107 // Note that FieldName may be null for anonymous bitfields.
15108 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15109                                 IdentifierInfo *FieldName,
15110                                 QualType FieldTy, bool IsMsStruct,
15111                                 Expr *BitWidth, bool *ZeroWidth) {
15112   // Default to true; that shouldn't confuse checks for emptiness
15113   if (ZeroWidth)
15114     *ZeroWidth = true;
15115 
15116   // C99 6.7.2.1p4 - verify the field type.
15117   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15118   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15119     // Handle incomplete types with specific error.
15120     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15121       return ExprError();
15122     if (FieldName)
15123       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15124         << FieldName << FieldTy << BitWidth->getSourceRange();
15125     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15126       << FieldTy << BitWidth->getSourceRange();
15127   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15128                                              UPPC_BitFieldWidth))
15129     return ExprError();
15130 
15131   // If the bit-width is type- or value-dependent, don't try to check
15132   // it now.
15133   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15134     return BitWidth;
15135 
15136   llvm::APSInt Value;
15137   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15138   if (ICE.isInvalid())
15139     return ICE;
15140   BitWidth = ICE.get();
15141 
15142   if (Value != 0 && ZeroWidth)
15143     *ZeroWidth = false;
15144 
15145   // Zero-width bitfield is ok for anonymous field.
15146   if (Value == 0 && FieldName)
15147     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15148 
15149   if (Value.isSigned() && Value.isNegative()) {
15150     if (FieldName)
15151       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15152                << FieldName << Value.toString(10);
15153     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15154       << Value.toString(10);
15155   }
15156 
15157   if (!FieldTy->isDependentType()) {
15158     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15159     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15160     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15161 
15162     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15163     // ABI.
15164     bool CStdConstraintViolation =
15165         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15166     bool MSBitfieldViolation =
15167         Value.ugt(TypeStorageSize) &&
15168         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15169     if (CStdConstraintViolation || MSBitfieldViolation) {
15170       unsigned DiagWidth =
15171           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15172       if (FieldName)
15173         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15174                << FieldName << (unsigned)Value.getZExtValue()
15175                << !CStdConstraintViolation << DiagWidth;
15176 
15177       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15178              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15179              << DiagWidth;
15180     }
15181 
15182     // Warn on types where the user might conceivably expect to get all
15183     // specified bits as value bits: that's all integral types other than
15184     // 'bool'.
15185     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15186       if (FieldName)
15187         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15188             << FieldName << (unsigned)Value.getZExtValue()
15189             << (unsigned)TypeWidth;
15190       else
15191         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15192             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15193     }
15194   }
15195 
15196   return BitWidth;
15197 }
15198 
15199 /// ActOnField - Each field of a C struct/union is passed into this in order
15200 /// to create a FieldDecl object for it.
15201 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15202                        Declarator &D, Expr *BitfieldWidth) {
15203   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15204                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15205                                /*InitStyle=*/ICIS_NoInit, AS_public);
15206   return Res;
15207 }
15208 
15209 /// HandleField - Analyze a field of a C struct or a C++ data member.
15210 ///
15211 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15212                              SourceLocation DeclStart,
15213                              Declarator &D, Expr *BitWidth,
15214                              InClassInitStyle InitStyle,
15215                              AccessSpecifier AS) {
15216   if (D.isDecompositionDeclarator()) {
15217     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15218     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15219       << Decomp.getSourceRange();
15220     return nullptr;
15221   }
15222 
15223   IdentifierInfo *II = D.getIdentifier();
15224   SourceLocation Loc = DeclStart;
15225   if (II) Loc = D.getIdentifierLoc();
15226 
15227   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15228   QualType T = TInfo->getType();
15229   if (getLangOpts().CPlusPlus) {
15230     CheckExtraCXXDefaultArguments(D);
15231 
15232     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15233                                         UPPC_DataMemberType)) {
15234       D.setInvalidType();
15235       T = Context.IntTy;
15236       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15237     }
15238   }
15239 
15240   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15241 
15242   if (D.getDeclSpec().isInlineSpecified())
15243     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15244         << getLangOpts().CPlusPlus17;
15245   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15246     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15247          diag::err_invalid_thread)
15248       << DeclSpec::getSpecifierName(TSCS);
15249 
15250   // Check to see if this name was declared as a member previously
15251   NamedDecl *PrevDecl = nullptr;
15252   LookupResult Previous(*this, II, Loc, LookupMemberName,
15253                         ForVisibleRedeclaration);
15254   LookupName(Previous, S);
15255   switch (Previous.getResultKind()) {
15256     case LookupResult::Found:
15257     case LookupResult::FoundUnresolvedValue:
15258       PrevDecl = Previous.getAsSingle<NamedDecl>();
15259       break;
15260 
15261     case LookupResult::FoundOverloaded:
15262       PrevDecl = Previous.getRepresentativeDecl();
15263       break;
15264 
15265     case LookupResult::NotFound:
15266     case LookupResult::NotFoundInCurrentInstantiation:
15267     case LookupResult::Ambiguous:
15268       break;
15269   }
15270   Previous.suppressDiagnostics();
15271 
15272   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15273     // Maybe we will complain about the shadowed template parameter.
15274     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15275     // Just pretend that we didn't see the previous declaration.
15276     PrevDecl = nullptr;
15277   }
15278 
15279   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15280     PrevDecl = nullptr;
15281 
15282   bool Mutable
15283     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15284   SourceLocation TSSL = D.getBeginLoc();
15285   FieldDecl *NewFD
15286     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15287                      TSSL, AS, PrevDecl, &D);
15288 
15289   if (NewFD->isInvalidDecl())
15290     Record->setInvalidDecl();
15291 
15292   if (D.getDeclSpec().isModulePrivateSpecified())
15293     NewFD->setModulePrivate();
15294 
15295   if (NewFD->isInvalidDecl() && PrevDecl) {
15296     // Don't introduce NewFD into scope; there's already something
15297     // with the same name in the same scope.
15298   } else if (II) {
15299     PushOnScopeChains(NewFD, S);
15300   } else
15301     Record->addDecl(NewFD);
15302 
15303   return NewFD;
15304 }
15305 
15306 /// Build a new FieldDecl and check its well-formedness.
15307 ///
15308 /// This routine builds a new FieldDecl given the fields name, type,
15309 /// record, etc. \p PrevDecl should refer to any previous declaration
15310 /// with the same name and in the same scope as the field to be
15311 /// created.
15312 ///
15313 /// \returns a new FieldDecl.
15314 ///
15315 /// \todo The Declarator argument is a hack. It will be removed once
15316 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15317                                 TypeSourceInfo *TInfo,
15318                                 RecordDecl *Record, SourceLocation Loc,
15319                                 bool Mutable, Expr *BitWidth,
15320                                 InClassInitStyle InitStyle,
15321                                 SourceLocation TSSL,
15322                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15323                                 Declarator *D) {
15324   IdentifierInfo *II = Name.getAsIdentifierInfo();
15325   bool InvalidDecl = false;
15326   if (D) InvalidDecl = D->isInvalidType();
15327 
15328   // If we receive a broken type, recover by assuming 'int' and
15329   // marking this declaration as invalid.
15330   if (T.isNull()) {
15331     InvalidDecl = true;
15332     T = Context.IntTy;
15333   }
15334 
15335   QualType EltTy = Context.getBaseElementType(T);
15336   if (!EltTy->isDependentType()) {
15337     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15338       // Fields of incomplete type force their record to be invalid.
15339       Record->setInvalidDecl();
15340       InvalidDecl = true;
15341     } else {
15342       NamedDecl *Def;
15343       EltTy->isIncompleteType(&Def);
15344       if (Def && Def->isInvalidDecl()) {
15345         Record->setInvalidDecl();
15346         InvalidDecl = true;
15347       }
15348     }
15349   }
15350 
15351   // TR 18037 does not allow fields to be declared with address space
15352   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15353       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15354     Diag(Loc, diag::err_field_with_address_space);
15355     Record->setInvalidDecl();
15356     InvalidDecl = true;
15357   }
15358 
15359   if (LangOpts.OpenCL) {
15360     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15361     // used as structure or union field: image, sampler, event or block types.
15362     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15363         T->isBlockPointerType()) {
15364       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15365       Record->setInvalidDecl();
15366       InvalidDecl = true;
15367     }
15368     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15369     if (BitWidth) {
15370       Diag(Loc, diag::err_opencl_bitfields);
15371       InvalidDecl = true;
15372     }
15373   }
15374 
15375   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15376   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15377       T.hasQualifiers()) {
15378     InvalidDecl = true;
15379     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15380   }
15381 
15382   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15383   // than a variably modified type.
15384   if (!InvalidDecl && T->isVariablyModifiedType()) {
15385     bool SizeIsNegative;
15386     llvm::APSInt Oversized;
15387 
15388     TypeSourceInfo *FixedTInfo =
15389       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15390                                                     SizeIsNegative,
15391                                                     Oversized);
15392     if (FixedTInfo) {
15393       Diag(Loc, diag::warn_illegal_constant_array_size);
15394       TInfo = FixedTInfo;
15395       T = FixedTInfo->getType();
15396     } else {
15397       if (SizeIsNegative)
15398         Diag(Loc, diag::err_typecheck_negative_array_size);
15399       else if (Oversized.getBoolValue())
15400         Diag(Loc, diag::err_array_too_large)
15401           << Oversized.toString(10);
15402       else
15403         Diag(Loc, diag::err_typecheck_field_variable_size);
15404       InvalidDecl = true;
15405     }
15406   }
15407 
15408   // Fields can not have abstract class types
15409   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15410                                              diag::err_abstract_type_in_decl,
15411                                              AbstractFieldType))
15412     InvalidDecl = true;
15413 
15414   bool ZeroWidth = false;
15415   if (InvalidDecl)
15416     BitWidth = nullptr;
15417   // If this is declared as a bit-field, check the bit-field.
15418   if (BitWidth) {
15419     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15420                               &ZeroWidth).get();
15421     if (!BitWidth) {
15422       InvalidDecl = true;
15423       BitWidth = nullptr;
15424       ZeroWidth = false;
15425     }
15426   }
15427 
15428   // Check that 'mutable' is consistent with the type of the declaration.
15429   if (!InvalidDecl && Mutable) {
15430     unsigned DiagID = 0;
15431     if (T->isReferenceType())
15432       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15433                                         : diag::err_mutable_reference;
15434     else if (T.isConstQualified())
15435       DiagID = diag::err_mutable_const;
15436 
15437     if (DiagID) {
15438       SourceLocation ErrLoc = Loc;
15439       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15440         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15441       Diag(ErrLoc, DiagID);
15442       if (DiagID != diag::ext_mutable_reference) {
15443         Mutable = false;
15444         InvalidDecl = true;
15445       }
15446     }
15447   }
15448 
15449   // C++11 [class.union]p8 (DR1460):
15450   //   At most one variant member of a union may have a
15451   //   brace-or-equal-initializer.
15452   if (InitStyle != ICIS_NoInit)
15453     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15454 
15455   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15456                                        BitWidth, Mutable, InitStyle);
15457   if (InvalidDecl)
15458     NewFD->setInvalidDecl();
15459 
15460   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15461     Diag(Loc, diag::err_duplicate_member) << II;
15462     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15463     NewFD->setInvalidDecl();
15464   }
15465 
15466   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15467     if (Record->isUnion()) {
15468       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15469         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15470         if (RDecl->getDefinition()) {
15471           // C++ [class.union]p1: An object of a class with a non-trivial
15472           // constructor, a non-trivial copy constructor, a non-trivial
15473           // destructor, or a non-trivial copy assignment operator
15474           // cannot be a member of a union, nor can an array of such
15475           // objects.
15476           if (CheckNontrivialField(NewFD))
15477             NewFD->setInvalidDecl();
15478         }
15479       }
15480 
15481       // C++ [class.union]p1: If a union contains a member of reference type,
15482       // the program is ill-formed, except when compiling with MSVC extensions
15483       // enabled.
15484       if (EltTy->isReferenceType()) {
15485         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15486                                     diag::ext_union_member_of_reference_type :
15487                                     diag::err_union_member_of_reference_type)
15488           << NewFD->getDeclName() << EltTy;
15489         if (!getLangOpts().MicrosoftExt)
15490           NewFD->setInvalidDecl();
15491       }
15492     }
15493   }
15494 
15495   // FIXME: We need to pass in the attributes given an AST
15496   // representation, not a parser representation.
15497   if (D) {
15498     // FIXME: The current scope is almost... but not entirely... correct here.
15499     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15500 
15501     if (NewFD->hasAttrs())
15502       CheckAlignasUnderalignment(NewFD);
15503   }
15504 
15505   // In auto-retain/release, infer strong retension for fields of
15506   // retainable type.
15507   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15508     NewFD->setInvalidDecl();
15509 
15510   if (T.isObjCGCWeak())
15511     Diag(Loc, diag::warn_attribute_weak_on_field);
15512 
15513   NewFD->setAccess(AS);
15514   return NewFD;
15515 }
15516 
15517 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15518   assert(FD);
15519   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15520 
15521   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15522     return false;
15523 
15524   QualType EltTy = Context.getBaseElementType(FD->getType());
15525   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15526     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15527     if (RDecl->getDefinition()) {
15528       // We check for copy constructors before constructors
15529       // because otherwise we'll never get complaints about
15530       // copy constructors.
15531 
15532       CXXSpecialMember member = CXXInvalid;
15533       // We're required to check for any non-trivial constructors. Since the
15534       // implicit default constructor is suppressed if there are any
15535       // user-declared constructors, we just need to check that there is a
15536       // trivial default constructor and a trivial copy constructor. (We don't
15537       // worry about move constructors here, since this is a C++98 check.)
15538       if (RDecl->hasNonTrivialCopyConstructor())
15539         member = CXXCopyConstructor;
15540       else if (!RDecl->hasTrivialDefaultConstructor())
15541         member = CXXDefaultConstructor;
15542       else if (RDecl->hasNonTrivialCopyAssignment())
15543         member = CXXCopyAssignment;
15544       else if (RDecl->hasNonTrivialDestructor())
15545         member = CXXDestructor;
15546 
15547       if (member != CXXInvalid) {
15548         if (!getLangOpts().CPlusPlus11 &&
15549             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15550           // Objective-C++ ARC: it is an error to have a non-trivial field of
15551           // a union. However, system headers in Objective-C programs
15552           // occasionally have Objective-C lifetime objects within unions,
15553           // and rather than cause the program to fail, we make those
15554           // members unavailable.
15555           SourceLocation Loc = FD->getLocation();
15556           if (getSourceManager().isInSystemHeader(Loc)) {
15557             if (!FD->hasAttr<UnavailableAttr>())
15558               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15559                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15560             return false;
15561           }
15562         }
15563 
15564         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15565                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15566                diag::err_illegal_union_or_anon_struct_member)
15567           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15568         DiagnoseNontrivial(RDecl, member);
15569         return !getLangOpts().CPlusPlus11;
15570       }
15571     }
15572   }
15573 
15574   return false;
15575 }
15576 
15577 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15578 ///  AST enum value.
15579 static ObjCIvarDecl::AccessControl
15580 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15581   switch (ivarVisibility) {
15582   default: llvm_unreachable("Unknown visitibility kind");
15583   case tok::objc_private: return ObjCIvarDecl::Private;
15584   case tok::objc_public: return ObjCIvarDecl::Public;
15585   case tok::objc_protected: return ObjCIvarDecl::Protected;
15586   case tok::objc_package: return ObjCIvarDecl::Package;
15587   }
15588 }
15589 
15590 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15591 /// in order to create an IvarDecl object for it.
15592 Decl *Sema::ActOnIvar(Scope *S,
15593                                 SourceLocation DeclStart,
15594                                 Declarator &D, Expr *BitfieldWidth,
15595                                 tok::ObjCKeywordKind Visibility) {
15596 
15597   IdentifierInfo *II = D.getIdentifier();
15598   Expr *BitWidth = (Expr*)BitfieldWidth;
15599   SourceLocation Loc = DeclStart;
15600   if (II) Loc = D.getIdentifierLoc();
15601 
15602   // FIXME: Unnamed fields can be handled in various different ways, for
15603   // example, unnamed unions inject all members into the struct namespace!
15604 
15605   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15606   QualType T = TInfo->getType();
15607 
15608   if (BitWidth) {
15609     // 6.7.2.1p3, 6.7.2.1p4
15610     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15611     if (!BitWidth)
15612       D.setInvalidType();
15613   } else {
15614     // Not a bitfield.
15615 
15616     // validate II.
15617 
15618   }
15619   if (T->isReferenceType()) {
15620     Diag(Loc, diag::err_ivar_reference_type);
15621     D.setInvalidType();
15622   }
15623   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15624   // than a variably modified type.
15625   else if (T->isVariablyModifiedType()) {
15626     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15627     D.setInvalidType();
15628   }
15629 
15630   // Get the visibility (access control) for this ivar.
15631   ObjCIvarDecl::AccessControl ac =
15632     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15633                                         : ObjCIvarDecl::None;
15634   // Must set ivar's DeclContext to its enclosing interface.
15635   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15636   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15637     return nullptr;
15638   ObjCContainerDecl *EnclosingContext;
15639   if (ObjCImplementationDecl *IMPDecl =
15640       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15641     if (LangOpts.ObjCRuntime.isFragile()) {
15642     // Case of ivar declared in an implementation. Context is that of its class.
15643       EnclosingContext = IMPDecl->getClassInterface();
15644       assert(EnclosingContext && "Implementation has no class interface!");
15645     }
15646     else
15647       EnclosingContext = EnclosingDecl;
15648   } else {
15649     if (ObjCCategoryDecl *CDecl =
15650         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15651       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15652         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15653         return nullptr;
15654       }
15655     }
15656     EnclosingContext = EnclosingDecl;
15657   }
15658 
15659   // Construct the decl.
15660   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15661                                              DeclStart, Loc, II, T,
15662                                              TInfo, ac, (Expr *)BitfieldWidth);
15663 
15664   if (II) {
15665     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15666                                            ForVisibleRedeclaration);
15667     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15668         && !isa<TagDecl>(PrevDecl)) {
15669       Diag(Loc, diag::err_duplicate_member) << II;
15670       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15671       NewID->setInvalidDecl();
15672     }
15673   }
15674 
15675   // Process attributes attached to the ivar.
15676   ProcessDeclAttributes(S, NewID, D);
15677 
15678   if (D.isInvalidType())
15679     NewID->setInvalidDecl();
15680 
15681   // In ARC, infer 'retaining' for ivars of retainable type.
15682   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15683     NewID->setInvalidDecl();
15684 
15685   if (D.getDeclSpec().isModulePrivateSpecified())
15686     NewID->setModulePrivate();
15687 
15688   if (II) {
15689     // FIXME: When interfaces are DeclContexts, we'll need to add
15690     // these to the interface.
15691     S->AddDecl(NewID);
15692     IdResolver.AddDecl(NewID);
15693   }
15694 
15695   if (LangOpts.ObjCRuntime.isNonFragile() &&
15696       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15697     Diag(Loc, diag::warn_ivars_in_interface);
15698 
15699   return NewID;
15700 }
15701 
15702 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15703 /// class and class extensions. For every class \@interface and class
15704 /// extension \@interface, if the last ivar is a bitfield of any type,
15705 /// then add an implicit `char :0` ivar to the end of that interface.
15706 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15707                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15708   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15709     return;
15710 
15711   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15712   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15713 
15714   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15715     return;
15716   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15717   if (!ID) {
15718     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15719       if (!CD->IsClassExtension())
15720         return;
15721     }
15722     // No need to add this to end of @implementation.
15723     else
15724       return;
15725   }
15726   // All conditions are met. Add a new bitfield to the tail end of ivars.
15727   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15728   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15729 
15730   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15731                               DeclLoc, DeclLoc, nullptr,
15732                               Context.CharTy,
15733                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15734                                                                DeclLoc),
15735                               ObjCIvarDecl::Private, BW,
15736                               true);
15737   AllIvarDecls.push_back(Ivar);
15738 }
15739 
15740 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15741                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15742                        SourceLocation RBrac,
15743                        const ParsedAttributesView &Attrs) {
15744   assert(EnclosingDecl && "missing record or interface decl");
15745 
15746   // If this is an Objective-C @implementation or category and we have
15747   // new fields here we should reset the layout of the interface since
15748   // it will now change.
15749   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15750     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15751     switch (DC->getKind()) {
15752     default: break;
15753     case Decl::ObjCCategory:
15754       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15755       break;
15756     case Decl::ObjCImplementation:
15757       Context.
15758         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15759       break;
15760     }
15761   }
15762 
15763   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15764   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15765 
15766   // Start counting up the number of named members; make sure to include
15767   // members of anonymous structs and unions in the total.
15768   unsigned NumNamedMembers = 0;
15769   if (Record) {
15770     for (const auto *I : Record->decls()) {
15771       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15772         if (IFD->getDeclName())
15773           ++NumNamedMembers;
15774     }
15775   }
15776 
15777   // Verify that all the fields are okay.
15778   SmallVector<FieldDecl*, 32> RecFields;
15779 
15780   bool ObjCFieldLifetimeErrReported = false;
15781   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15782        i != end; ++i) {
15783     FieldDecl *FD = cast<FieldDecl>(*i);
15784 
15785     // Get the type for the field.
15786     const Type *FDTy = FD->getType().getTypePtr();
15787 
15788     if (!FD->isAnonymousStructOrUnion()) {
15789       // Remember all fields written by the user.
15790       RecFields.push_back(FD);
15791     }
15792 
15793     // If the field is already invalid for some reason, don't emit more
15794     // diagnostics about it.
15795     if (FD->isInvalidDecl()) {
15796       EnclosingDecl->setInvalidDecl();
15797       continue;
15798     }
15799 
15800     // C99 6.7.2.1p2:
15801     //   A structure or union shall not contain a member with
15802     //   incomplete or function type (hence, a structure shall not
15803     //   contain an instance of itself, but may contain a pointer to
15804     //   an instance of itself), except that the last member of a
15805     //   structure with more than one named member may have incomplete
15806     //   array type; such a structure (and any union containing,
15807     //   possibly recursively, a member that is such a structure)
15808     //   shall not be a member of a structure or an element of an
15809     //   array.
15810     bool IsLastField = (i + 1 == Fields.end());
15811     if (FDTy->isFunctionType()) {
15812       // Field declared as a function.
15813       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15814         << FD->getDeclName();
15815       FD->setInvalidDecl();
15816       EnclosingDecl->setInvalidDecl();
15817       continue;
15818     } else if (FDTy->isIncompleteArrayType() &&
15819                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15820       if (Record) {
15821         // Flexible array member.
15822         // Microsoft and g++ is more permissive regarding flexible array.
15823         // It will accept flexible array in union and also
15824         // as the sole element of a struct/class.
15825         unsigned DiagID = 0;
15826         if (!Record->isUnion() && !IsLastField) {
15827           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15828             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15829           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15830           FD->setInvalidDecl();
15831           EnclosingDecl->setInvalidDecl();
15832           continue;
15833         } else if (Record->isUnion())
15834           DiagID = getLangOpts().MicrosoftExt
15835                        ? diag::ext_flexible_array_union_ms
15836                        : getLangOpts().CPlusPlus
15837                              ? diag::ext_flexible_array_union_gnu
15838                              : diag::err_flexible_array_union;
15839         else if (NumNamedMembers < 1)
15840           DiagID = getLangOpts().MicrosoftExt
15841                        ? diag::ext_flexible_array_empty_aggregate_ms
15842                        : getLangOpts().CPlusPlus
15843                              ? diag::ext_flexible_array_empty_aggregate_gnu
15844                              : diag::err_flexible_array_empty_aggregate;
15845 
15846         if (DiagID)
15847           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15848                                           << Record->getTagKind();
15849         // While the layout of types that contain virtual bases is not specified
15850         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15851         // virtual bases after the derived members.  This would make a flexible
15852         // array member declared at the end of an object not adjacent to the end
15853         // of the type.
15854         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15855           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15856               << FD->getDeclName() << Record->getTagKind();
15857         if (!getLangOpts().C99)
15858           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15859             << FD->getDeclName() << Record->getTagKind();
15860 
15861         // If the element type has a non-trivial destructor, we would not
15862         // implicitly destroy the elements, so disallow it for now.
15863         //
15864         // FIXME: GCC allows this. We should probably either implicitly delete
15865         // the destructor of the containing class, or just allow this.
15866         QualType BaseElem = Context.getBaseElementType(FD->getType());
15867         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15868           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15869             << FD->getDeclName() << FD->getType();
15870           FD->setInvalidDecl();
15871           EnclosingDecl->setInvalidDecl();
15872           continue;
15873         }
15874         // Okay, we have a legal flexible array member at the end of the struct.
15875         Record->setHasFlexibleArrayMember(true);
15876       } else {
15877         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15878         // unless they are followed by another ivar. That check is done
15879         // elsewhere, after synthesized ivars are known.
15880       }
15881     } else if (!FDTy->isDependentType() &&
15882                RequireCompleteType(FD->getLocation(), FD->getType(),
15883                                    diag::err_field_incomplete)) {
15884       // Incomplete type
15885       FD->setInvalidDecl();
15886       EnclosingDecl->setInvalidDecl();
15887       continue;
15888     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15889       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15890         // A type which contains a flexible array member is considered to be a
15891         // flexible array member.
15892         Record->setHasFlexibleArrayMember(true);
15893         if (!Record->isUnion()) {
15894           // If this is a struct/class and this is not the last element, reject
15895           // it.  Note that GCC supports variable sized arrays in the middle of
15896           // structures.
15897           if (!IsLastField)
15898             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15899               << FD->getDeclName() << FD->getType();
15900           else {
15901             // We support flexible arrays at the end of structs in
15902             // other structs as an extension.
15903             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15904               << FD->getDeclName();
15905           }
15906         }
15907       }
15908       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15909           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15910                                  diag::err_abstract_type_in_decl,
15911                                  AbstractIvarType)) {
15912         // Ivars can not have abstract class types
15913         FD->setInvalidDecl();
15914       }
15915       if (Record && FDTTy->getDecl()->hasObjectMember())
15916         Record->setHasObjectMember(true);
15917       if (Record && FDTTy->getDecl()->hasVolatileMember())
15918         Record->setHasVolatileMember(true);
15919     } else if (FDTy->isObjCObjectType()) {
15920       /// A field cannot be an Objective-c object
15921       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15922         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15923       QualType T = Context.getObjCObjectPointerType(FD->getType());
15924       FD->setType(T);
15925     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15926                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
15927                !getLangOpts().CPlusPlus) {
15928       // It's an error in ARC or Weak if a field has lifetime.
15929       // We don't want to report this in a system header, though,
15930       // so we just make the field unavailable.
15931       // FIXME: that's really not sufficient; we need to make the type
15932       // itself invalid to, say, initialize or copy.
15933       QualType T = FD->getType();
15934       if (T.hasNonTrivialObjCLifetime()) {
15935         SourceLocation loc = FD->getLocation();
15936         if (getSourceManager().isInSystemHeader(loc)) {
15937           if (!FD->hasAttr<UnavailableAttr>()) {
15938             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15939                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15940           }
15941         } else {
15942           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15943             << T->isBlockPointerType() << Record->getTagKind();
15944         }
15945         ObjCFieldLifetimeErrReported = true;
15946       }
15947     } else if (getLangOpts().ObjC &&
15948                getLangOpts().getGC() != LangOptions::NonGC &&
15949                Record && !Record->hasObjectMember()) {
15950       if (FD->getType()->isObjCObjectPointerType() ||
15951           FD->getType().isObjCGCStrong())
15952         Record->setHasObjectMember(true);
15953       else if (Context.getAsArrayType(FD->getType())) {
15954         QualType BaseType = Context.getBaseElementType(FD->getType());
15955         if (BaseType->isRecordType() &&
15956             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15957           Record->setHasObjectMember(true);
15958         else if (BaseType->isObjCObjectPointerType() ||
15959                  BaseType.isObjCGCStrong())
15960                Record->setHasObjectMember(true);
15961       }
15962     }
15963 
15964     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15965       QualType FT = FD->getType();
15966       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15967         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15968       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15969       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15970         Record->setNonTrivialToPrimitiveCopy(true);
15971       if (FT.isDestructedType()) {
15972         Record->setNonTrivialToPrimitiveDestroy(true);
15973         Record->setParamDestroyedInCallee(true);
15974       }
15975 
15976       if (const auto *RT = FT->getAs<RecordType>()) {
15977         if (RT->getDecl()->getArgPassingRestrictions() ==
15978             RecordDecl::APK_CanNeverPassInRegs)
15979           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15980       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15981         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15982     }
15983 
15984     if (Record && FD->getType().isVolatileQualified())
15985       Record->setHasVolatileMember(true);
15986     // Keep track of the number of named members.
15987     if (FD->getIdentifier())
15988       ++NumNamedMembers;
15989   }
15990 
15991   // Okay, we successfully defined 'Record'.
15992   if (Record) {
15993     bool Completed = false;
15994     if (CXXRecord) {
15995       if (!CXXRecord->isInvalidDecl()) {
15996         // Set access bits correctly on the directly-declared conversions.
15997         for (CXXRecordDecl::conversion_iterator
15998                I = CXXRecord->conversion_begin(),
15999                E = CXXRecord->conversion_end(); I != E; ++I)
16000           I.setAccess((*I)->getAccess());
16001       }
16002 
16003       if (!CXXRecord->isDependentType()) {
16004         // Add any implicitly-declared members to this class.
16005         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16006 
16007         if (!CXXRecord->isInvalidDecl()) {
16008           // If we have virtual base classes, we may end up finding multiple
16009           // final overriders for a given virtual function. Check for this
16010           // problem now.
16011           if (CXXRecord->getNumVBases()) {
16012             CXXFinalOverriderMap FinalOverriders;
16013             CXXRecord->getFinalOverriders(FinalOverriders);
16014 
16015             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16016                                              MEnd = FinalOverriders.end();
16017                  M != MEnd; ++M) {
16018               for (OverridingMethods::iterator SO = M->second.begin(),
16019                                             SOEnd = M->second.end();
16020                    SO != SOEnd; ++SO) {
16021                 assert(SO->second.size() > 0 &&
16022                        "Virtual function without overriding functions?");
16023                 if (SO->second.size() == 1)
16024                   continue;
16025 
16026                 // C++ [class.virtual]p2:
16027                 //   In a derived class, if a virtual member function of a base
16028                 //   class subobject has more than one final overrider the
16029                 //   program is ill-formed.
16030                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16031                   << (const NamedDecl *)M->first << Record;
16032                 Diag(M->first->getLocation(),
16033                      diag::note_overridden_virtual_function);
16034                 for (OverridingMethods::overriding_iterator
16035                           OM = SO->second.begin(),
16036                        OMEnd = SO->second.end();
16037                      OM != OMEnd; ++OM)
16038                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16039                     << (const NamedDecl *)M->first << OM->Method->getParent();
16040 
16041                 Record->setInvalidDecl();
16042               }
16043             }
16044             CXXRecord->completeDefinition(&FinalOverriders);
16045             Completed = true;
16046           }
16047         }
16048       }
16049     }
16050 
16051     if (!Completed)
16052       Record->completeDefinition();
16053 
16054     // Handle attributes before checking the layout.
16055     ProcessDeclAttributeList(S, Record, Attrs);
16056 
16057     // We may have deferred checking for a deleted destructor. Check now.
16058     if (CXXRecord) {
16059       auto *Dtor = CXXRecord->getDestructor();
16060       if (Dtor && Dtor->isImplicit() &&
16061           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16062         CXXRecord->setImplicitDestructorIsDeleted();
16063         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16064       }
16065     }
16066 
16067     if (Record->hasAttrs()) {
16068       CheckAlignasUnderalignment(Record);
16069 
16070       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16071         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16072                                            IA->getRange(), IA->getBestCase(),
16073                                            IA->getSemanticSpelling());
16074     }
16075 
16076     // Check if the structure/union declaration is a type that can have zero
16077     // size in C. For C this is a language extension, for C++ it may cause
16078     // compatibility problems.
16079     bool CheckForZeroSize;
16080     if (!getLangOpts().CPlusPlus) {
16081       CheckForZeroSize = true;
16082     } else {
16083       // For C++ filter out types that cannot be referenced in C code.
16084       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16085       CheckForZeroSize =
16086           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16087           !CXXRecord->isDependentType() &&
16088           CXXRecord->isCLike();
16089     }
16090     if (CheckForZeroSize) {
16091       bool ZeroSize = true;
16092       bool IsEmpty = true;
16093       unsigned NonBitFields = 0;
16094       for (RecordDecl::field_iterator I = Record->field_begin(),
16095                                       E = Record->field_end();
16096            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16097         IsEmpty = false;
16098         if (I->isUnnamedBitfield()) {
16099           if (!I->isZeroLengthBitField(Context))
16100             ZeroSize = false;
16101         } else {
16102           ++NonBitFields;
16103           QualType FieldType = I->getType();
16104           if (FieldType->isIncompleteType() ||
16105               !Context.getTypeSizeInChars(FieldType).isZero())
16106             ZeroSize = false;
16107         }
16108       }
16109 
16110       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16111       // allowed in C++, but warn if its declaration is inside
16112       // extern "C" block.
16113       if (ZeroSize) {
16114         Diag(RecLoc, getLangOpts().CPlusPlus ?
16115                          diag::warn_zero_size_struct_union_in_extern_c :
16116                          diag::warn_zero_size_struct_union_compat)
16117           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16118       }
16119 
16120       // Structs without named members are extension in C (C99 6.7.2.1p7),
16121       // but are accepted by GCC.
16122       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16123         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16124                                diag::ext_no_named_members_in_struct_union)
16125           << Record->isUnion();
16126       }
16127     }
16128   } else {
16129     ObjCIvarDecl **ClsFields =
16130       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16131     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16132       ID->setEndOfDefinitionLoc(RBrac);
16133       // Add ivar's to class's DeclContext.
16134       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16135         ClsFields[i]->setLexicalDeclContext(ID);
16136         ID->addDecl(ClsFields[i]);
16137       }
16138       // Must enforce the rule that ivars in the base classes may not be
16139       // duplicates.
16140       if (ID->getSuperClass())
16141         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16142     } else if (ObjCImplementationDecl *IMPDecl =
16143                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16144       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16145       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16146         // Ivar declared in @implementation never belongs to the implementation.
16147         // Only it is in implementation's lexical context.
16148         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16149       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16150       IMPDecl->setIvarLBraceLoc(LBrac);
16151       IMPDecl->setIvarRBraceLoc(RBrac);
16152     } else if (ObjCCategoryDecl *CDecl =
16153                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16154       // case of ivars in class extension; all other cases have been
16155       // reported as errors elsewhere.
16156       // FIXME. Class extension does not have a LocEnd field.
16157       // CDecl->setLocEnd(RBrac);
16158       // Add ivar's to class extension's DeclContext.
16159       // Diagnose redeclaration of private ivars.
16160       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16161       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16162         if (IDecl) {
16163           if (const ObjCIvarDecl *ClsIvar =
16164               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16165             Diag(ClsFields[i]->getLocation(),
16166                  diag::err_duplicate_ivar_declaration);
16167             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16168             continue;
16169           }
16170           for (const auto *Ext : IDecl->known_extensions()) {
16171             if (const ObjCIvarDecl *ClsExtIvar
16172                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16173               Diag(ClsFields[i]->getLocation(),
16174                    diag::err_duplicate_ivar_declaration);
16175               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16176               continue;
16177             }
16178           }
16179         }
16180         ClsFields[i]->setLexicalDeclContext(CDecl);
16181         CDecl->addDecl(ClsFields[i]);
16182       }
16183       CDecl->setIvarLBraceLoc(LBrac);
16184       CDecl->setIvarRBraceLoc(RBrac);
16185     }
16186   }
16187 }
16188 
16189 /// Determine whether the given integral value is representable within
16190 /// the given type T.
16191 static bool isRepresentableIntegerValue(ASTContext &Context,
16192                                         llvm::APSInt &Value,
16193                                         QualType T) {
16194   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16195          "Integral type required!");
16196   unsigned BitWidth = Context.getIntWidth(T);
16197 
16198   if (Value.isUnsigned() || Value.isNonNegative()) {
16199     if (T->isSignedIntegerOrEnumerationType())
16200       --BitWidth;
16201     return Value.getActiveBits() <= BitWidth;
16202   }
16203   return Value.getMinSignedBits() <= BitWidth;
16204 }
16205 
16206 // Given an integral type, return the next larger integral type
16207 // (or a NULL type of no such type exists).
16208 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16209   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16210   // enum checking below.
16211   assert((T->isIntegralType(Context) ||
16212          T->isEnumeralType()) && "Integral type required!");
16213   const unsigned NumTypes = 4;
16214   QualType SignedIntegralTypes[NumTypes] = {
16215     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16216   };
16217   QualType UnsignedIntegralTypes[NumTypes] = {
16218     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16219     Context.UnsignedLongLongTy
16220   };
16221 
16222   unsigned BitWidth = Context.getTypeSize(T);
16223   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16224                                                         : UnsignedIntegralTypes;
16225   for (unsigned I = 0; I != NumTypes; ++I)
16226     if (Context.getTypeSize(Types[I]) > BitWidth)
16227       return Types[I];
16228 
16229   return QualType();
16230 }
16231 
16232 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16233                                           EnumConstantDecl *LastEnumConst,
16234                                           SourceLocation IdLoc,
16235                                           IdentifierInfo *Id,
16236                                           Expr *Val) {
16237   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16238   llvm::APSInt EnumVal(IntWidth);
16239   QualType EltTy;
16240 
16241   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16242     Val = nullptr;
16243 
16244   if (Val)
16245     Val = DefaultLvalueConversion(Val).get();
16246 
16247   if (Val) {
16248     if (Enum->isDependentType() || Val->isTypeDependent())
16249       EltTy = Context.DependentTy;
16250     else {
16251       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16252           !getLangOpts().MSVCCompat) {
16253         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16254         // constant-expression in the enumerator-definition shall be a converted
16255         // constant expression of the underlying type.
16256         EltTy = Enum->getIntegerType();
16257         ExprResult Converted =
16258           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16259                                            CCEK_Enumerator);
16260         if (Converted.isInvalid())
16261           Val = nullptr;
16262         else
16263           Val = Converted.get();
16264       } else if (!Val->isValueDependent() &&
16265                  !(Val = VerifyIntegerConstantExpression(Val,
16266                                                          &EnumVal).get())) {
16267         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16268       } else {
16269         if (Enum->isComplete()) {
16270           EltTy = Enum->getIntegerType();
16271 
16272           // In Obj-C and Microsoft mode, require the enumeration value to be
16273           // representable in the underlying type of the enumeration. In C++11,
16274           // we perform a non-narrowing conversion as part of converted constant
16275           // expression checking.
16276           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16277             if (getLangOpts().MSVCCompat) {
16278               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16279               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16280             } else
16281               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16282           } else
16283             Val = ImpCastExprToType(Val, EltTy,
16284                                     EltTy->isBooleanType() ?
16285                                     CK_IntegralToBoolean : CK_IntegralCast)
16286                     .get();
16287         } else if (getLangOpts().CPlusPlus) {
16288           // C++11 [dcl.enum]p5:
16289           //   If the underlying type is not fixed, the type of each enumerator
16290           //   is the type of its initializing value:
16291           //     - If an initializer is specified for an enumerator, the
16292           //       initializing value has the same type as the expression.
16293           EltTy = Val->getType();
16294         } else {
16295           // C99 6.7.2.2p2:
16296           //   The expression that defines the value of an enumeration constant
16297           //   shall be an integer constant expression that has a value
16298           //   representable as an int.
16299 
16300           // Complain if the value is not representable in an int.
16301           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16302             Diag(IdLoc, diag::ext_enum_value_not_int)
16303               << EnumVal.toString(10) << Val->getSourceRange()
16304               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16305           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16306             // Force the type of the expression to 'int'.
16307             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16308           }
16309           EltTy = Val->getType();
16310         }
16311       }
16312     }
16313   }
16314 
16315   if (!Val) {
16316     if (Enum->isDependentType())
16317       EltTy = Context.DependentTy;
16318     else if (!LastEnumConst) {
16319       // C++0x [dcl.enum]p5:
16320       //   If the underlying type is not fixed, the type of each enumerator
16321       //   is the type of its initializing value:
16322       //     - If no initializer is specified for the first enumerator, the
16323       //       initializing value has an unspecified integral type.
16324       //
16325       // GCC uses 'int' for its unspecified integral type, as does
16326       // C99 6.7.2.2p3.
16327       if (Enum->isFixed()) {
16328         EltTy = Enum->getIntegerType();
16329       }
16330       else {
16331         EltTy = Context.IntTy;
16332       }
16333     } else {
16334       // Assign the last value + 1.
16335       EnumVal = LastEnumConst->getInitVal();
16336       ++EnumVal;
16337       EltTy = LastEnumConst->getType();
16338 
16339       // Check for overflow on increment.
16340       if (EnumVal < LastEnumConst->getInitVal()) {
16341         // C++0x [dcl.enum]p5:
16342         //   If the underlying type is not fixed, the type of each enumerator
16343         //   is the type of its initializing value:
16344         //
16345         //     - Otherwise the type of the initializing value is the same as
16346         //       the type of the initializing value of the preceding enumerator
16347         //       unless the incremented value is not representable in that type,
16348         //       in which case the type is an unspecified integral type
16349         //       sufficient to contain the incremented value. If no such type
16350         //       exists, the program is ill-formed.
16351         QualType T = getNextLargerIntegralType(Context, EltTy);
16352         if (T.isNull() || Enum->isFixed()) {
16353           // There is no integral type larger enough to represent this
16354           // value. Complain, then allow the value to wrap around.
16355           EnumVal = LastEnumConst->getInitVal();
16356           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16357           ++EnumVal;
16358           if (Enum->isFixed())
16359             // When the underlying type is fixed, this is ill-formed.
16360             Diag(IdLoc, diag::err_enumerator_wrapped)
16361               << EnumVal.toString(10)
16362               << EltTy;
16363           else
16364             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16365               << EnumVal.toString(10);
16366         } else {
16367           EltTy = T;
16368         }
16369 
16370         // Retrieve the last enumerator's value, extent that type to the
16371         // type that is supposed to be large enough to represent the incremented
16372         // value, then increment.
16373         EnumVal = LastEnumConst->getInitVal();
16374         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16375         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16376         ++EnumVal;
16377 
16378         // If we're not in C++, diagnose the overflow of enumerator values,
16379         // which in C99 means that the enumerator value is not representable in
16380         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16381         // permits enumerator values that are representable in some larger
16382         // integral type.
16383         if (!getLangOpts().CPlusPlus && !T.isNull())
16384           Diag(IdLoc, diag::warn_enum_value_overflow);
16385       } else if (!getLangOpts().CPlusPlus &&
16386                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16387         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16388         Diag(IdLoc, diag::ext_enum_value_not_int)
16389           << EnumVal.toString(10) << 1;
16390       }
16391     }
16392   }
16393 
16394   if (!EltTy->isDependentType()) {
16395     // Make the enumerator value match the signedness and size of the
16396     // enumerator's type.
16397     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16398     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16399   }
16400 
16401   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16402                                   Val, EnumVal);
16403 }
16404 
16405 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16406                                                 SourceLocation IILoc) {
16407   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16408       !getLangOpts().CPlusPlus)
16409     return SkipBodyInfo();
16410 
16411   // We have an anonymous enum definition. Look up the first enumerator to
16412   // determine if we should merge the definition with an existing one and
16413   // skip the body.
16414   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16415                                          forRedeclarationInCurContext());
16416   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16417   if (!PrevECD)
16418     return SkipBodyInfo();
16419 
16420   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16421   NamedDecl *Hidden;
16422   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16423     SkipBodyInfo Skip;
16424     Skip.Previous = Hidden;
16425     return Skip;
16426   }
16427 
16428   return SkipBodyInfo();
16429 }
16430 
16431 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16432                               SourceLocation IdLoc, IdentifierInfo *Id,
16433                               const ParsedAttributesView &Attrs,
16434                               SourceLocation EqualLoc, Expr *Val) {
16435   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16436   EnumConstantDecl *LastEnumConst =
16437     cast_or_null<EnumConstantDecl>(lastEnumConst);
16438 
16439   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16440   // we find one that is.
16441   S = getNonFieldDeclScope(S);
16442 
16443   // Verify that there isn't already something declared with this name in this
16444   // scope.
16445   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16446   LookupName(R, S);
16447   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16448 
16449   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16450     // Maybe we will complain about the shadowed template parameter.
16451     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16452     // Just pretend that we didn't see the previous declaration.
16453     PrevDecl = nullptr;
16454   }
16455 
16456   // C++ [class.mem]p15:
16457   // If T is the name of a class, then each of the following shall have a name
16458   // different from T:
16459   // - every enumerator of every member of class T that is an unscoped
16460   // enumerated type
16461   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16462     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16463                             DeclarationNameInfo(Id, IdLoc));
16464 
16465   EnumConstantDecl *New =
16466     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16467   if (!New)
16468     return nullptr;
16469 
16470   if (PrevDecl) {
16471     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16472       // Check for other kinds of shadowing not already handled.
16473       CheckShadow(New, PrevDecl, R);
16474     }
16475 
16476     // When in C++, we may get a TagDecl with the same name; in this case the
16477     // enum constant will 'hide' the tag.
16478     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16479            "Received TagDecl when not in C++!");
16480     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16481       if (isa<EnumConstantDecl>(PrevDecl))
16482         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16483       else
16484         Diag(IdLoc, diag::err_redefinition) << Id;
16485       notePreviousDefinition(PrevDecl, IdLoc);
16486       return nullptr;
16487     }
16488   }
16489 
16490   // Process attributes.
16491   ProcessDeclAttributeList(S, New, Attrs);
16492   AddPragmaAttributes(S, New);
16493 
16494   // Register this decl in the current scope stack.
16495   New->setAccess(TheEnumDecl->getAccess());
16496   PushOnScopeChains(New, S);
16497 
16498   ActOnDocumentableDecl(New);
16499 
16500   return New;
16501 }
16502 
16503 // Returns true when the enum initial expression does not trigger the
16504 // duplicate enum warning.  A few common cases are exempted as follows:
16505 // Element2 = Element1
16506 // Element2 = Element1 + 1
16507 // Element2 = Element1 - 1
16508 // Where Element2 and Element1 are from the same enum.
16509 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16510   Expr *InitExpr = ECD->getInitExpr();
16511   if (!InitExpr)
16512     return true;
16513   InitExpr = InitExpr->IgnoreImpCasts();
16514 
16515   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16516     if (!BO->isAdditiveOp())
16517       return true;
16518     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16519     if (!IL)
16520       return true;
16521     if (IL->getValue() != 1)
16522       return true;
16523 
16524     InitExpr = BO->getLHS();
16525   }
16526 
16527   // This checks if the elements are from the same enum.
16528   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16529   if (!DRE)
16530     return true;
16531 
16532   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16533   if (!EnumConstant)
16534     return true;
16535 
16536   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16537       Enum)
16538     return true;
16539 
16540   return false;
16541 }
16542 
16543 // Emits a warning when an element is implicitly set a value that
16544 // a previous element has already been set to.
16545 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16546                                         EnumDecl *Enum, QualType EnumType) {
16547   // Avoid anonymous enums
16548   if (!Enum->getIdentifier())
16549     return;
16550 
16551   // Only check for small enums.
16552   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16553     return;
16554 
16555   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16556     return;
16557 
16558   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16559   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16560 
16561   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16562   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16563 
16564   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16565   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16566     llvm::APSInt Val = D->getInitVal();
16567     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16568   };
16569 
16570   DuplicatesVector DupVector;
16571   ValueToVectorMap EnumMap;
16572 
16573   // Populate the EnumMap with all values represented by enum constants without
16574   // an initializer.
16575   for (auto *Element : Elements) {
16576     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16577 
16578     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16579     // this constant.  Skip this enum since it may be ill-formed.
16580     if (!ECD) {
16581       return;
16582     }
16583 
16584     // Constants with initalizers are handled in the next loop.
16585     if (ECD->getInitExpr())
16586       continue;
16587 
16588     // Duplicate values are handled in the next loop.
16589     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16590   }
16591 
16592   if (EnumMap.size() == 0)
16593     return;
16594 
16595   // Create vectors for any values that has duplicates.
16596   for (auto *Element : Elements) {
16597     // The last loop returned if any constant was null.
16598     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16599     if (!ValidDuplicateEnum(ECD, Enum))
16600       continue;
16601 
16602     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16603     if (Iter == EnumMap.end())
16604       continue;
16605 
16606     DeclOrVector& Entry = Iter->second;
16607     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16608       // Ensure constants are different.
16609       if (D == ECD)
16610         continue;
16611 
16612       // Create new vector and push values onto it.
16613       auto Vec = llvm::make_unique<ECDVector>();
16614       Vec->push_back(D);
16615       Vec->push_back(ECD);
16616 
16617       // Update entry to point to the duplicates vector.
16618       Entry = Vec.get();
16619 
16620       // Store the vector somewhere we can consult later for quick emission of
16621       // diagnostics.
16622       DupVector.emplace_back(std::move(Vec));
16623       continue;
16624     }
16625 
16626     ECDVector *Vec = Entry.get<ECDVector*>();
16627     // Make sure constants are not added more than once.
16628     if (*Vec->begin() == ECD)
16629       continue;
16630 
16631     Vec->push_back(ECD);
16632   }
16633 
16634   // Emit diagnostics.
16635   for (const auto &Vec : DupVector) {
16636     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16637 
16638     // Emit warning for one enum constant.
16639     auto *FirstECD = Vec->front();
16640     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16641       << FirstECD << FirstECD->getInitVal().toString(10)
16642       << FirstECD->getSourceRange();
16643 
16644     // Emit one note for each of the remaining enum constants with
16645     // the same value.
16646     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16647       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16648         << ECD << ECD->getInitVal().toString(10)
16649         << ECD->getSourceRange();
16650   }
16651 }
16652 
16653 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16654                              bool AllowMask) const {
16655   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16656   assert(ED->isCompleteDefinition() && "expected enum definition");
16657 
16658   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16659   llvm::APInt &FlagBits = R.first->second;
16660 
16661   if (R.second) {
16662     for (auto *E : ED->enumerators()) {
16663       const auto &EVal = E->getInitVal();
16664       // Only single-bit enumerators introduce new flag values.
16665       if (EVal.isPowerOf2())
16666         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16667     }
16668   }
16669 
16670   // A value is in a flag enum if either its bits are a subset of the enum's
16671   // flag bits (the first condition) or we are allowing masks and the same is
16672   // true of its complement (the second condition). When masks are allowed, we
16673   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16674   //
16675   // While it's true that any value could be used as a mask, the assumption is
16676   // that a mask will have all of the insignificant bits set. Anything else is
16677   // likely a logic error.
16678   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16679   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16680 }
16681 
16682 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16683                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16684                          const ParsedAttributesView &Attrs) {
16685   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16686   QualType EnumType = Context.getTypeDeclType(Enum);
16687 
16688   ProcessDeclAttributeList(S, Enum, Attrs);
16689 
16690   if (Enum->isDependentType()) {
16691     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16692       EnumConstantDecl *ECD =
16693         cast_or_null<EnumConstantDecl>(Elements[i]);
16694       if (!ECD) continue;
16695 
16696       ECD->setType(EnumType);
16697     }
16698 
16699     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16700     return;
16701   }
16702 
16703   // TODO: If the result value doesn't fit in an int, it must be a long or long
16704   // long value.  ISO C does not support this, but GCC does as an extension,
16705   // emit a warning.
16706   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16707   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16708   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16709 
16710   // Verify that all the values are okay, compute the size of the values, and
16711   // reverse the list.
16712   unsigned NumNegativeBits = 0;
16713   unsigned NumPositiveBits = 0;
16714 
16715   // Keep track of whether all elements have type int.
16716   bool AllElementsInt = true;
16717 
16718   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16719     EnumConstantDecl *ECD =
16720       cast_or_null<EnumConstantDecl>(Elements[i]);
16721     if (!ECD) continue;  // Already issued a diagnostic.
16722 
16723     const llvm::APSInt &InitVal = ECD->getInitVal();
16724 
16725     // Keep track of the size of positive and negative values.
16726     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16727       NumPositiveBits = std::max(NumPositiveBits,
16728                                  (unsigned)InitVal.getActiveBits());
16729     else
16730       NumNegativeBits = std::max(NumNegativeBits,
16731                                  (unsigned)InitVal.getMinSignedBits());
16732 
16733     // Keep track of whether every enum element has type int (very common).
16734     if (AllElementsInt)
16735       AllElementsInt = ECD->getType() == Context.IntTy;
16736   }
16737 
16738   // Figure out the type that should be used for this enum.
16739   QualType BestType;
16740   unsigned BestWidth;
16741 
16742   // C++0x N3000 [conv.prom]p3:
16743   //   An rvalue of an unscoped enumeration type whose underlying
16744   //   type is not fixed can be converted to an rvalue of the first
16745   //   of the following types that can represent all the values of
16746   //   the enumeration: int, unsigned int, long int, unsigned long
16747   //   int, long long int, or unsigned long long int.
16748   // C99 6.4.4.3p2:
16749   //   An identifier declared as an enumeration constant has type int.
16750   // The C99 rule is modified by a gcc extension
16751   QualType BestPromotionType;
16752 
16753   bool Packed = Enum->hasAttr<PackedAttr>();
16754   // -fshort-enums is the equivalent to specifying the packed attribute on all
16755   // enum definitions.
16756   if (LangOpts.ShortEnums)
16757     Packed = true;
16758 
16759   // If the enum already has a type because it is fixed or dictated by the
16760   // target, promote that type instead of analyzing the enumerators.
16761   if (Enum->isComplete()) {
16762     BestType = Enum->getIntegerType();
16763     if (BestType->isPromotableIntegerType())
16764       BestPromotionType = Context.getPromotedIntegerType(BestType);
16765     else
16766       BestPromotionType = BestType;
16767 
16768     BestWidth = Context.getIntWidth(BestType);
16769   }
16770   else if (NumNegativeBits) {
16771     // If there is a negative value, figure out the smallest integer type (of
16772     // int/long/longlong) that fits.
16773     // If it's packed, check also if it fits a char or a short.
16774     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16775       BestType = Context.SignedCharTy;
16776       BestWidth = CharWidth;
16777     } else if (Packed && NumNegativeBits <= ShortWidth &&
16778                NumPositiveBits < ShortWidth) {
16779       BestType = Context.ShortTy;
16780       BestWidth = ShortWidth;
16781     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16782       BestType = Context.IntTy;
16783       BestWidth = IntWidth;
16784     } else {
16785       BestWidth = Context.getTargetInfo().getLongWidth();
16786 
16787       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16788         BestType = Context.LongTy;
16789       } else {
16790         BestWidth = Context.getTargetInfo().getLongLongWidth();
16791 
16792         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16793           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16794         BestType = Context.LongLongTy;
16795       }
16796     }
16797     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16798   } else {
16799     // If there is no negative value, figure out the smallest type that fits
16800     // all of the enumerator values.
16801     // If it's packed, check also if it fits a char or a short.
16802     if (Packed && NumPositiveBits <= CharWidth) {
16803       BestType = Context.UnsignedCharTy;
16804       BestPromotionType = Context.IntTy;
16805       BestWidth = CharWidth;
16806     } else if (Packed && NumPositiveBits <= ShortWidth) {
16807       BestType = Context.UnsignedShortTy;
16808       BestPromotionType = Context.IntTy;
16809       BestWidth = ShortWidth;
16810     } else if (NumPositiveBits <= IntWidth) {
16811       BestType = Context.UnsignedIntTy;
16812       BestWidth = IntWidth;
16813       BestPromotionType
16814         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16815                            ? Context.UnsignedIntTy : Context.IntTy;
16816     } else if (NumPositiveBits <=
16817                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16818       BestType = Context.UnsignedLongTy;
16819       BestPromotionType
16820         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16821                            ? Context.UnsignedLongTy : Context.LongTy;
16822     } else {
16823       BestWidth = Context.getTargetInfo().getLongLongWidth();
16824       assert(NumPositiveBits <= BestWidth &&
16825              "How could an initializer get larger than ULL?");
16826       BestType = Context.UnsignedLongLongTy;
16827       BestPromotionType
16828         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16829                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16830     }
16831   }
16832 
16833   // Loop over all of the enumerator constants, changing their types to match
16834   // the type of the enum if needed.
16835   for (auto *D : Elements) {
16836     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16837     if (!ECD) continue;  // Already issued a diagnostic.
16838 
16839     // Standard C says the enumerators have int type, but we allow, as an
16840     // extension, the enumerators to be larger than int size.  If each
16841     // enumerator value fits in an int, type it as an int, otherwise type it the
16842     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16843     // that X has type 'int', not 'unsigned'.
16844 
16845     // Determine whether the value fits into an int.
16846     llvm::APSInt InitVal = ECD->getInitVal();
16847 
16848     // If it fits into an integer type, force it.  Otherwise force it to match
16849     // the enum decl type.
16850     QualType NewTy;
16851     unsigned NewWidth;
16852     bool NewSign;
16853     if (!getLangOpts().CPlusPlus &&
16854         !Enum->isFixed() &&
16855         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16856       NewTy = Context.IntTy;
16857       NewWidth = IntWidth;
16858       NewSign = true;
16859     } else if (ECD->getType() == BestType) {
16860       // Already the right type!
16861       if (getLangOpts().CPlusPlus)
16862         // C++ [dcl.enum]p4: Following the closing brace of an
16863         // enum-specifier, each enumerator has the type of its
16864         // enumeration.
16865         ECD->setType(EnumType);
16866       continue;
16867     } else {
16868       NewTy = BestType;
16869       NewWidth = BestWidth;
16870       NewSign = BestType->isSignedIntegerOrEnumerationType();
16871     }
16872 
16873     // Adjust the APSInt value.
16874     InitVal = InitVal.extOrTrunc(NewWidth);
16875     InitVal.setIsSigned(NewSign);
16876     ECD->setInitVal(InitVal);
16877 
16878     // Adjust the Expr initializer and type.
16879     if (ECD->getInitExpr() &&
16880         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16881       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16882                                                 CK_IntegralCast,
16883                                                 ECD->getInitExpr(),
16884                                                 /*base paths*/ nullptr,
16885                                                 VK_RValue));
16886     if (getLangOpts().CPlusPlus)
16887       // C++ [dcl.enum]p4: Following the closing brace of an
16888       // enum-specifier, each enumerator has the type of its
16889       // enumeration.
16890       ECD->setType(EnumType);
16891     else
16892       ECD->setType(NewTy);
16893   }
16894 
16895   Enum->completeDefinition(BestType, BestPromotionType,
16896                            NumPositiveBits, NumNegativeBits);
16897 
16898   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16899 
16900   if (Enum->isClosedFlag()) {
16901     for (Decl *D : Elements) {
16902       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16903       if (!ECD) continue;  // Already issued a diagnostic.
16904 
16905       llvm::APSInt InitVal = ECD->getInitVal();
16906       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16907           !IsValueInFlagEnum(Enum, InitVal, true))
16908         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16909           << ECD << Enum;
16910     }
16911   }
16912 
16913   // Now that the enum type is defined, ensure it's not been underaligned.
16914   if (Enum->hasAttrs())
16915     CheckAlignasUnderalignment(Enum);
16916 }
16917 
16918 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16919                                   SourceLocation StartLoc,
16920                                   SourceLocation EndLoc) {
16921   StringLiteral *AsmString = cast<StringLiteral>(expr);
16922 
16923   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16924                                                    AsmString, StartLoc,
16925                                                    EndLoc);
16926   CurContext->addDecl(New);
16927   return New;
16928 }
16929 
16930 static void checkModuleImportContext(Sema &S, Module *M,
16931                                      SourceLocation ImportLoc, DeclContext *DC,
16932                                      bool FromInclude = false) {
16933   SourceLocation ExternCLoc;
16934 
16935   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16936     switch (LSD->getLanguage()) {
16937     case LinkageSpecDecl::lang_c:
16938       if (ExternCLoc.isInvalid())
16939         ExternCLoc = LSD->getBeginLoc();
16940       break;
16941     case LinkageSpecDecl::lang_cxx:
16942       break;
16943     }
16944     DC = LSD->getParent();
16945   }
16946 
16947   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16948     DC = DC->getParent();
16949 
16950   if (!isa<TranslationUnitDecl>(DC)) {
16951     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16952                           ? diag::ext_module_import_not_at_top_level_noop
16953                           : diag::err_module_import_not_at_top_level_fatal)
16954         << M->getFullModuleName() << DC;
16955     S.Diag(cast<Decl>(DC)->getBeginLoc(),
16956            diag::note_module_import_not_at_top_level)
16957         << DC;
16958   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16959     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16960       << M->getFullModuleName();
16961     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16962   }
16963 }
16964 
16965 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16966                                            SourceLocation ModuleLoc,
16967                                            ModuleDeclKind MDK,
16968                                            ModuleIdPath Path) {
16969   assert(getLangOpts().ModulesTS &&
16970          "should only have module decl in modules TS");
16971 
16972   // A module implementation unit requires that we are not compiling a module
16973   // of any kind. A module interface unit requires that we are not compiling a
16974   // module map.
16975   switch (getLangOpts().getCompilingModule()) {
16976   case LangOptions::CMK_None:
16977     // It's OK to compile a module interface as a normal translation unit.
16978     break;
16979 
16980   case LangOptions::CMK_ModuleInterface:
16981     if (MDK != ModuleDeclKind::Implementation)
16982       break;
16983 
16984     // We were asked to compile a module interface unit but this is a module
16985     // implementation unit. That indicates the 'export' is missing.
16986     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16987       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16988     MDK = ModuleDeclKind::Interface;
16989     break;
16990 
16991   case LangOptions::CMK_ModuleMap:
16992     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16993     return nullptr;
16994 
16995   case LangOptions::CMK_HeaderModule:
16996     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
16997     return nullptr;
16998   }
16999 
17000   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
17001 
17002   // FIXME: Most of this work should be done by the preprocessor rather than
17003   // here, in order to support macro import.
17004 
17005   // Only one module-declaration is permitted per source file.
17006   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
17007     Diag(ModuleLoc, diag::err_module_redeclaration);
17008     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
17009          diag::note_prev_module_declaration);
17010     return nullptr;
17011   }
17012 
17013   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
17014   // modules, the dots here are just another character that can appear in a
17015   // module name.
17016   std::string ModuleName;
17017   for (auto &Piece : Path) {
17018     if (!ModuleName.empty())
17019       ModuleName += ".";
17020     ModuleName += Piece.first->getName();
17021   }
17022 
17023   // If a module name was explicitly specified on the command line, it must be
17024   // correct.
17025   if (!getLangOpts().CurrentModule.empty() &&
17026       getLangOpts().CurrentModule != ModuleName) {
17027     Diag(Path.front().second, diag::err_current_module_name_mismatch)
17028         << SourceRange(Path.front().second, Path.back().second)
17029         << getLangOpts().CurrentModule;
17030     return nullptr;
17031   }
17032   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
17033 
17034   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
17035   Module *Mod;
17036 
17037   switch (MDK) {
17038   case ModuleDeclKind::Interface: {
17039     // We can't have parsed or imported a definition of this module or parsed a
17040     // module map defining it already.
17041     if (auto *M = Map.findModule(ModuleName)) {
17042       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
17043       if (M->DefinitionLoc.isValid())
17044         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
17045       else if (const auto *FE = M->getASTFile())
17046         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
17047             << FE->getName();
17048       Mod = M;
17049       break;
17050     }
17051 
17052     // Create a Module for the module that we're defining.
17053     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17054                                            ModuleScopes.front().Module);
17055     assert(Mod && "module creation should not fail");
17056     break;
17057   }
17058 
17059   case ModuleDeclKind::Partition:
17060     // FIXME: Check we are in a submodule of the named module.
17061     return nullptr;
17062 
17063   case ModuleDeclKind::Implementation:
17064     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
17065         PP.getIdentifierInfo(ModuleName), Path[0].second);
17066     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
17067                                        Module::AllVisible,
17068                                        /*IsIncludeDirective=*/false);
17069     if (!Mod) {
17070       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
17071       // Create an empty module interface unit for error recovery.
17072       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17073                                              ModuleScopes.front().Module);
17074     }
17075     break;
17076   }
17077 
17078   // Switch from the global module to the named module.
17079   ModuleScopes.back().Module = Mod;
17080   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
17081   VisibleModules.setVisible(Mod, ModuleLoc);
17082 
17083   // From now on, we have an owning module for all declarations we see.
17084   // However, those declarations are module-private unless explicitly
17085   // exported.
17086   auto *TU = Context.getTranslationUnitDecl();
17087   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
17088   TU->setLocalOwningModule(Mod);
17089 
17090   // FIXME: Create a ModuleDecl.
17091   return nullptr;
17092 }
17093 
17094 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
17095                                    SourceLocation ImportLoc,
17096                                    ModuleIdPath Path) {
17097   // Flatten the module path for a Modules TS module name.
17098   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
17099   if (getLangOpts().ModulesTS) {
17100     std::string ModuleName;
17101     for (auto &Piece : Path) {
17102       if (!ModuleName.empty())
17103         ModuleName += ".";
17104       ModuleName += Piece.first->getName();
17105     }
17106     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
17107     Path = ModuleIdPath(ModuleNameLoc);
17108   }
17109 
17110   Module *Mod =
17111       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
17112                                    /*IsIncludeDirective=*/false);
17113   if (!Mod)
17114     return true;
17115 
17116   VisibleModules.setVisible(Mod, ImportLoc);
17117 
17118   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
17119 
17120   // FIXME: we should support importing a submodule within a different submodule
17121   // of the same top-level module. Until we do, make it an error rather than
17122   // silently ignoring the import.
17123   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
17124   // warn on a redundant import of the current module?
17125   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
17126       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
17127     Diag(ImportLoc, getLangOpts().isCompilingModule()
17128                         ? diag::err_module_self_import
17129                         : diag::err_module_import_in_implementation)
17130         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
17131 
17132   SmallVector<SourceLocation, 2> IdentifierLocs;
17133   Module *ModCheck = Mod;
17134   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
17135     // If we've run out of module parents, just drop the remaining identifiers.
17136     // We need the length to be consistent.
17137     if (!ModCheck)
17138       break;
17139     ModCheck = ModCheck->Parent;
17140 
17141     IdentifierLocs.push_back(Path[I].second);
17142   }
17143 
17144   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17145                                           Mod, IdentifierLocs);
17146   if (!ModuleScopes.empty())
17147     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17148   CurContext->addDecl(Import);
17149 
17150   // Re-export the module if needed.
17151   if (Import->isExported() &&
17152       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17153     getCurrentModule()->Exports.emplace_back(Mod, false);
17154 
17155   return Import;
17156 }
17157 
17158 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17159   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17160   BuildModuleInclude(DirectiveLoc, Mod);
17161 }
17162 
17163 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17164   // Determine whether we're in the #include buffer for a module. The #includes
17165   // in that buffer do not qualify as module imports; they're just an
17166   // implementation detail of us building the module.
17167   //
17168   // FIXME: Should we even get ActOnModuleInclude calls for those?
17169   bool IsInModuleIncludes =
17170       TUKind == TU_Module &&
17171       getSourceManager().isWrittenInMainFile(DirectiveLoc);
17172 
17173   bool ShouldAddImport = !IsInModuleIncludes;
17174 
17175   // If this module import was due to an inclusion directive, create an
17176   // implicit import declaration to capture it in the AST.
17177   if (ShouldAddImport) {
17178     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17179     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17180                                                      DirectiveLoc, Mod,
17181                                                      DirectiveLoc);
17182     if (!ModuleScopes.empty())
17183       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17184     TU->addDecl(ImportD);
17185     Consumer.HandleImplicitImportDecl(ImportD);
17186   }
17187 
17188   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17189   VisibleModules.setVisible(Mod, DirectiveLoc);
17190 }
17191 
17192 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17193   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17194 
17195   ModuleScopes.push_back({});
17196   ModuleScopes.back().Module = Mod;
17197   if (getLangOpts().ModulesLocalVisibility)
17198     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17199 
17200   VisibleModules.setVisible(Mod, DirectiveLoc);
17201 
17202   // The enclosing context is now part of this module.
17203   // FIXME: Consider creating a child DeclContext to hold the entities
17204   // lexically within the module.
17205   if (getLangOpts().trackLocalOwningModule()) {
17206     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17207       cast<Decl>(DC)->setModuleOwnershipKind(
17208           getLangOpts().ModulesLocalVisibility
17209               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17210               : Decl::ModuleOwnershipKind::Visible);
17211       cast<Decl>(DC)->setLocalOwningModule(Mod);
17212     }
17213   }
17214 }
17215 
17216 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17217   if (getLangOpts().ModulesLocalVisibility) {
17218     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17219     // Leaving a module hides namespace names, so our visible namespace cache
17220     // is now out of date.
17221     VisibleNamespaceCache.clear();
17222   }
17223 
17224   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17225          "left the wrong module scope");
17226   ModuleScopes.pop_back();
17227 
17228   // We got to the end of processing a local module. Create an
17229   // ImportDecl as we would for an imported module.
17230   FileID File = getSourceManager().getFileID(EomLoc);
17231   SourceLocation DirectiveLoc;
17232   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17233     // We reached the end of a #included module header. Use the #include loc.
17234     assert(File != getSourceManager().getMainFileID() &&
17235            "end of submodule in main source file");
17236     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17237   } else {
17238     // We reached an EOM pragma. Use the pragma location.
17239     DirectiveLoc = EomLoc;
17240   }
17241   BuildModuleInclude(DirectiveLoc, Mod);
17242 
17243   // Any further declarations are in whatever module we returned to.
17244   if (getLangOpts().trackLocalOwningModule()) {
17245     // The parser guarantees that this is the same context that we entered
17246     // the module within.
17247     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17248       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17249       if (!getCurrentModule())
17250         cast<Decl>(DC)->setModuleOwnershipKind(
17251             Decl::ModuleOwnershipKind::Unowned);
17252     }
17253   }
17254 }
17255 
17256 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17257                                                       Module *Mod) {
17258   // Bail if we're not allowed to implicitly import a module here.
17259   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17260       VisibleModules.isVisible(Mod))
17261     return;
17262 
17263   // Create the implicit import declaration.
17264   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17265   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17266                                                    Loc, Mod, Loc);
17267   TU->addDecl(ImportD);
17268   Consumer.HandleImplicitImportDecl(ImportD);
17269 
17270   // Make the module visible.
17271   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17272   VisibleModules.setVisible(Mod, Loc);
17273 }
17274 
17275 /// We have parsed the start of an export declaration, including the '{'
17276 /// (if present).
17277 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17278                                  SourceLocation LBraceLoc) {
17279   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17280 
17281   // C++ Modules TS draft:
17282   //   An export-declaration shall appear in the purview of a module other than
17283   //   the global module.
17284   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17285     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17286 
17287   //   An export-declaration [...] shall not contain more than one
17288   //   export keyword.
17289   //
17290   // The intent here is that an export-declaration cannot appear within another
17291   // export-declaration.
17292   if (D->isExported())
17293     Diag(ExportLoc, diag::err_export_within_export);
17294 
17295   CurContext->addDecl(D);
17296   PushDeclContext(S, D);
17297   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17298   return D;
17299 }
17300 
17301 /// Complete the definition of an export declaration.
17302 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17303   auto *ED = cast<ExportDecl>(D);
17304   if (RBraceLoc.isValid())
17305     ED->setRBraceLoc(RBraceLoc);
17306 
17307   // FIXME: Diagnose export of internal-linkage declaration (including
17308   // anonymous namespace).
17309 
17310   PopDeclContext();
17311   return D;
17312 }
17313 
17314 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17315                                       IdentifierInfo* AliasName,
17316                                       SourceLocation PragmaLoc,
17317                                       SourceLocation NameLoc,
17318                                       SourceLocation AliasNameLoc) {
17319   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17320                                          LookupOrdinaryName);
17321   AsmLabelAttr *Attr =
17322       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17323 
17324   // If a declaration that:
17325   // 1) declares a function or a variable
17326   // 2) has external linkage
17327   // already exists, add a label attribute to it.
17328   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17329     if (isDeclExternC(PrevDecl))
17330       PrevDecl->addAttr(Attr);
17331     else
17332       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17333           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17334   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17335   } else
17336     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17337 }
17338 
17339 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17340                              SourceLocation PragmaLoc,
17341                              SourceLocation NameLoc) {
17342   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17343 
17344   if (PrevDecl) {
17345     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17346   } else {
17347     (void)WeakUndeclaredIdentifiers.insert(
17348       std::pair<IdentifierInfo*,WeakInfo>
17349         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17350   }
17351 }
17352 
17353 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17354                                 IdentifierInfo* AliasName,
17355                                 SourceLocation PragmaLoc,
17356                                 SourceLocation NameLoc,
17357                                 SourceLocation AliasNameLoc) {
17358   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17359                                     LookupOrdinaryName);
17360   WeakInfo W = WeakInfo(Name, NameLoc);
17361 
17362   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17363     if (!PrevDecl->hasAttr<AliasAttr>())
17364       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17365         DeclApplyPragmaWeak(TUScope, ND, W);
17366   } else {
17367     (void)WeakUndeclaredIdentifiers.insert(
17368       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17369   }
17370 }
17371 
17372 Decl *Sema::getObjCDeclContext() const {
17373   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17374 }
17375