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, /*AllowFunctionTemplates=*/true,
1021                                       /*AllowDependent=*/false)) {
1022       // C++ [temp.local]p3:
1023       //   A lookup that finds an injected-class-name (10.2) can result in an
1024       //   ambiguity in certain cases (for example, if it is found in more than
1025       //   one base class). If all of the injected-class-names that are found
1026       //   refer to specializations of the same class template, and if the name
1027       //   is followed by a template-argument-list, the reference refers to the
1028       //   class template itself and not a specialization thereof, and is not
1029       //   ambiguous.
1030       //
1031       // This filtering can make an ambiguous result into an unambiguous one,
1032       // so try again after filtering out template names.
1033       FilterAcceptableTemplateNames(Result);
1034       if (!Result.isAmbiguous()) {
1035         IsFilteredTemplateName = true;
1036         break;
1037       }
1038     }
1039 
1040     // Diagnose the ambiguity and return an error.
1041     return NameClassification::Error();
1042   }
1043 
1044   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1045       (IsFilteredTemplateName ||
1046        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047                                      /*AllowDependent=*/false))) {
1048     // C++ [temp.names]p3:
1049     //   After name lookup (3.4) finds that a name is a template-name or that
1050     //   an operator-function-id or a literal- operator-id refers to a set of
1051     //   overloaded functions any member of which is a function template if
1052     //   this is followed by a <, the < is always taken as the delimiter of a
1053     //   template-argument-list and never as the less-than operator.
1054     if (!IsFilteredTemplateName)
1055       FilterAcceptableTemplateNames(Result);
1056 
1057     if (!Result.empty()) {
1058       bool IsFunctionTemplate;
1059       bool IsVarTemplate;
1060       TemplateName Template;
1061       if (Result.end() - Result.begin() > 1) {
1062         IsFunctionTemplate = true;
1063         Template = Context.getOverloadedTemplateName(Result.begin(),
1064                                                      Result.end());
1065       } else {
1066         auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1067             *Result.begin(), /*AllowFunctionTemplates=*/true,
1068             /*AllowDependent=*/false));
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template =
1074               Context.getQualifiedTemplateName(SS.getScopeRep(),
1075                                                /*TemplateKeyword=*/false, TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1452 /// have compatible owning modules.
1453 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1454   // FIXME: The Modules TS is not clear about how friend declarations are
1455   // to be treated. It's not meaningful to have different owning modules for
1456   // linkage in redeclarations of the same entity, so for now allow the
1457   // redeclaration and change the owning modules to match.
1458   if (New->getFriendObjectKind() &&
1459       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1460     New->setLocalOwningModule(Old->getOwningModule());
1461     makeMergedDefinitionVisible(New);
1462     return false;
1463   }
1464 
1465   Module *NewM = New->getOwningModule();
1466   Module *OldM = Old->getOwningModule();
1467   if (NewM == OldM)
1468     return false;
1469 
1470   // FIXME: Check proclaimed-ownership-declarations here too.
1471   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473   if (NewIsModuleInterface || OldIsModuleInterface) {
1474     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475     //   if a declaration of D [...] appears in the purview of a module, all
1476     //   other such declarations shall appear in the purview of the same module
1477     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478       << New
1479       << NewIsModuleInterface
1480       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481       << OldIsModuleInterface
1482       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483     Diag(Old->getLocation(), diag::note_previous_declaration);
1484     New->setInvalidDecl();
1485     return true;
1486   }
1487 
1488   return false;
1489 }
1490 
1491 static bool isUsingDecl(NamedDecl *D) {
1492   return isa<UsingShadowDecl>(D) ||
1493          isa<UnresolvedUsingTypenameDecl>(D) ||
1494          isa<UnresolvedUsingValueDecl>(D);
1495 }
1496 
1497 /// Removes using shadow declarations from the lookup results.
1498 static void RemoveUsingDecls(LookupResult &R) {
1499   LookupResult::Filter F = R.makeFilter();
1500   while (F.hasNext())
1501     if (isUsingDecl(F.next()))
1502       F.erase();
1503 
1504   F.done();
1505 }
1506 
1507 /// Check for this common pattern:
1508 /// @code
1509 /// class S {
1510 ///   S(const S&); // DO NOT IMPLEMENT
1511 ///   void operator=(const S&); // DO NOT IMPLEMENT
1512 /// };
1513 /// @endcode
1514 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1515   // FIXME: Should check for private access too but access is set after we get
1516   // the decl here.
1517   if (D->doesThisDeclarationHaveABody())
1518     return false;
1519 
1520   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521     return CD->isCopyConstructor();
1522   return D->isCopyAssignmentOperator();
1523 }
1524 
1525 // We need this to handle
1526 //
1527 // typedef struct {
1528 //   void *foo() { return 0; }
1529 // } A;
1530 //
1531 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1532 // for example. If 'A', foo will have external linkage. If we have '*A',
1533 // foo will have no linkage. Since we can't know until we get to the end
1534 // of the typedef, this function finds out if D might have non-external linkage.
1535 // Callers should verify at the end of the TU if it D has external linkage or
1536 // not.
1537 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1538   const DeclContext *DC = D->getDeclContext();
1539   while (!DC->isTranslationUnit()) {
1540     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1541       if (!RD->hasNameForLinkage())
1542         return true;
1543     }
1544     DC = DC->getParent();
1545   }
1546 
1547   return !D->isExternallyVisible();
1548 }
1549 
1550 // FIXME: This needs to be refactored; some other isInMainFile users want
1551 // these semantics.
1552 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1553   if (S.TUKind != TU_Complete)
1554     return false;
1555   return S.SourceMgr.isInMainFile(Loc);
1556 }
1557 
1558 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1559   assert(D);
1560 
1561   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1562     return false;
1563 
1564   // Ignore all entities declared within templates, and out-of-line definitions
1565   // of members of class templates.
1566   if (D->getDeclContext()->isDependentContext() ||
1567       D->getLexicalDeclContext()->isDependentContext())
1568     return false;
1569 
1570   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1571     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1572       return false;
1573     // A non-out-of-line declaration of a member specialization was implicitly
1574     // instantiated; it's the out-of-line declaration that we're interested in.
1575     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1576         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1577       return false;
1578 
1579     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1580       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1581         return false;
1582     } else {
1583       // 'static inline' functions are defined in headers; don't warn.
1584       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585         return false;
1586     }
1587 
1588     if (FD->doesThisDeclarationHaveABody() &&
1589         Context.DeclMustBeEmitted(FD))
1590       return false;
1591   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592     // Constants and utility variables are defined in headers with internal
1593     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1594     // like "inline".)
1595     if (!isMainFileLoc(*this, VD->getLocation()))
1596       return false;
1597 
1598     if (Context.DeclMustBeEmitted(VD))
1599       return false;
1600 
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1603       return false;
1604     if (VD->isStaticDataMember() &&
1605         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1606         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1607       return false;
1608 
1609     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1610       return false;
1611   } else {
1612     return false;
1613   }
1614 
1615   // Only warn for unused decls internal to the translation unit.
1616   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1617   // for inline functions defined in the main source file, for instance.
1618   return mightHaveNonExternalLinkage(D);
1619 }
1620 
1621 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1622   if (!D)
1623     return;
1624 
1625   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1626     const FunctionDecl *First = FD->getFirstDecl();
1627     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1628       return; // First should already be in the vector.
1629   }
1630 
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632     const VarDecl *First = VD->getFirstDecl();
1633     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1634       return; // First should already be in the vector.
1635   }
1636 
1637   if (ShouldWarnIfUnusedFileScopedDecl(D))
1638     UnusedFileScopedDecls.push_back(D);
1639 }
1640 
1641 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1642   if (D->isInvalidDecl())
1643     return false;
1644 
1645   bool Referenced = false;
1646   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1647     // For a decomposition declaration, warn if none of the bindings are
1648     // referenced, instead of if the variable itself is referenced (which
1649     // it is, by the bindings' expressions).
1650     for (auto *BD : DD->bindings()) {
1651       if (BD->isReferenced()) {
1652         Referenced = true;
1653         break;
1654       }
1655     }
1656   } else if (!D->getDeclName()) {
1657     return false;
1658   } else if (D->isReferenced() || D->isUsed()) {
1659     Referenced = true;
1660   }
1661 
1662   if (Referenced || D->hasAttr<UnusedAttr>() ||
1663       D->hasAttr<ObjCPreciseLifetimeAttr>())
1664     return false;
1665 
1666   if (isa<LabelDecl>(D))
1667     return true;
1668 
1669   // Except for labels, we only care about unused decls that are local to
1670   // functions.
1671   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1672   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1673     // For dependent types, the diagnostic is deferred.
1674     WithinFunction =
1675         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1676   if (!WithinFunction)
1677     return false;
1678 
1679   if (isa<TypedefNameDecl>(D))
1680     return true;
1681 
1682   // White-list anything that isn't a local variable.
1683   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1684     return false;
1685 
1686   // Types of valid local variables should be complete, so this should succeed.
1687   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1688 
1689     // White-list anything with an __attribute__((unused)) type.
1690     const auto *Ty = VD->getType().getTypePtr();
1691 
1692     // Only look at the outermost level of typedef.
1693     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1694       if (TT->getDecl()->hasAttr<UnusedAttr>())
1695         return false;
1696     }
1697 
1698     // If we failed to complete the type for some reason, or if the type is
1699     // dependent, don't diagnose the variable.
1700     if (Ty->isIncompleteType() || Ty->isDependentType())
1701       return false;
1702 
1703     // Look at the element type to ensure that the warning behaviour is
1704     // consistent for both scalars and arrays.
1705     Ty = Ty->getBaseElementTypeUnsafe();
1706 
1707     if (const TagType *TT = Ty->getAs<TagType>()) {
1708       const TagDecl *Tag = TT->getDecl();
1709       if (Tag->hasAttr<UnusedAttr>())
1710         return false;
1711 
1712       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1713         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1714           return false;
1715 
1716         if (const Expr *Init = VD->getInit()) {
1717           if (const ExprWithCleanups *Cleanups =
1718                   dyn_cast<ExprWithCleanups>(Init))
1719             Init = Cleanups->getSubExpr();
1720           const CXXConstructExpr *Construct =
1721             dyn_cast<CXXConstructExpr>(Init);
1722           if (Construct && !Construct->isElidable()) {
1723             CXXConstructorDecl *CD = Construct->getConstructor();
1724             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1725                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1726               return false;
1727           }
1728         }
1729       }
1730     }
1731 
1732     // TODO: __attribute__((unused)) templates?
1733   }
1734 
1735   return true;
1736 }
1737 
1738 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1739                                      FixItHint &Hint) {
1740   if (isa<LabelDecl>(D)) {
1741     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1742         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1743         true);
1744     if (AfterColon.isInvalid())
1745       return;
1746     Hint = FixItHint::CreateRemoval(
1747         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1748   }
1749 }
1750 
1751 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1752   if (D->getTypeForDecl()->isDependentType())
1753     return;
1754 
1755   for (auto *TmpD : D->decls()) {
1756     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1757       DiagnoseUnusedDecl(T);
1758     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1759       DiagnoseUnusedNestedTypedefs(R);
1760   }
1761 }
1762 
1763 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1764 /// unless they are marked attr(unused).
1765 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1766   if (!ShouldDiagnoseUnusedDecl(D))
1767     return;
1768 
1769   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1770     // typedefs can be referenced later on, so the diagnostics are emitted
1771     // at end-of-translation-unit.
1772     UnusedLocalTypedefNameCandidates.insert(TD);
1773     return;
1774   }
1775 
1776   FixItHint Hint;
1777   GenerateFixForUnusedDecl(D, Context, Hint);
1778 
1779   unsigned DiagID;
1780   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1781     DiagID = diag::warn_unused_exception_param;
1782   else if (isa<LabelDecl>(D))
1783     DiagID = diag::warn_unused_label;
1784   else
1785     DiagID = diag::warn_unused_variable;
1786 
1787   Diag(D->getLocation(), DiagID) << D << Hint;
1788 }
1789 
1790 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1791   // Verify that we have no forward references left.  If so, there was a goto
1792   // or address of a label taken, but no definition of it.  Label fwd
1793   // definitions are indicated with a null substmt which is also not a resolved
1794   // MS inline assembly label name.
1795   bool Diagnose = false;
1796   if (L->isMSAsmLabel())
1797     Diagnose = !L->isResolvedMSAsmLabel();
1798   else
1799     Diagnose = L->getStmt() == nullptr;
1800   if (Diagnose)
1801     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1802 }
1803 
1804 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1805   S->mergeNRVOIntoParent();
1806 
1807   if (S->decl_empty()) return;
1808   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1809          "Scope shouldn't contain decls!");
1810 
1811   for (auto *TmpD : S->decls()) {
1812     assert(TmpD && "This decl didn't get pushed??");
1813 
1814     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1815     NamedDecl *D = cast<NamedDecl>(TmpD);
1816 
1817     // Diagnose unused variables in this scope.
1818     if (!S->hasUnrecoverableErrorOccurred()) {
1819       DiagnoseUnusedDecl(D);
1820       if (const auto *RD = dyn_cast<RecordDecl>(D))
1821         DiagnoseUnusedNestedTypedefs(RD);
1822     }
1823 
1824     if (!D->getDeclName()) continue;
1825 
1826     // If this was a forward reference to a label, verify it was defined.
1827     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1828       CheckPoppedLabel(LD, *this);
1829 
1830     // Remove this name from our lexical scope, and warn on it if we haven't
1831     // already.
1832     IdResolver.RemoveDecl(D);
1833     auto ShadowI = ShadowingDecls.find(D);
1834     if (ShadowI != ShadowingDecls.end()) {
1835       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1836         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1837             << D << FD << FD->getParent();
1838         Diag(FD->getLocation(), diag::note_previous_declaration);
1839       }
1840       ShadowingDecls.erase(ShadowI);
1841     }
1842   }
1843 }
1844 
1845 /// Look for an Objective-C class in the translation unit.
1846 ///
1847 /// \param Id The name of the Objective-C class we're looking for. If
1848 /// typo-correction fixes this name, the Id will be updated
1849 /// to the fixed name.
1850 ///
1851 /// \param IdLoc The location of the name in the translation unit.
1852 ///
1853 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1854 /// if there is no class with the given name.
1855 ///
1856 /// \returns The declaration of the named Objective-C class, or NULL if the
1857 /// class could not be found.
1858 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1859                                               SourceLocation IdLoc,
1860                                               bool DoTypoCorrection) {
1861   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1862   // creation from this context.
1863   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1864 
1865   if (!IDecl && DoTypoCorrection) {
1866     // Perform typo correction at the given location, but only if we
1867     // find an Objective-C class name.
1868     if (TypoCorrection C = CorrectTypo(
1869             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1870             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1871             CTK_ErrorRecovery)) {
1872       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1873       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1874       Id = IDecl->getIdentifier();
1875     }
1876   }
1877   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1878   // This routine must always return a class definition, if any.
1879   if (Def && Def->getDefinition())
1880       Def = Def->getDefinition();
1881   return Def;
1882 }
1883 
1884 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1885 /// from S, where a non-field would be declared. This routine copes
1886 /// with the difference between C and C++ scoping rules in structs and
1887 /// unions. For example, the following code is well-formed in C but
1888 /// ill-formed in C++:
1889 /// @code
1890 /// struct S6 {
1891 ///   enum { BAR } e;
1892 /// };
1893 ///
1894 /// void test_S6() {
1895 ///   struct S6 a;
1896 ///   a.e = BAR;
1897 /// }
1898 /// @endcode
1899 /// For the declaration of BAR, this routine will return a different
1900 /// scope. The scope S will be the scope of the unnamed enumeration
1901 /// within S6. In C++, this routine will return the scope associated
1902 /// with S6, because the enumeration's scope is a transparent
1903 /// context but structures can contain non-field names. In C, this
1904 /// routine will return the translation unit scope, since the
1905 /// enumeration's scope is a transparent context and structures cannot
1906 /// contain non-field names.
1907 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1908   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1909          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1910          (S->isClassScope() && !getLangOpts().CPlusPlus))
1911     S = S->getParent();
1912   return S;
1913 }
1914 
1915 /// Looks up the declaration of "struct objc_super" and
1916 /// saves it for later use in building builtin declaration of
1917 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1918 /// pre-existing declaration exists no action takes place.
1919 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1920                                         IdentifierInfo *II) {
1921   if (!II->isStr("objc_msgSendSuper"))
1922     return;
1923   ASTContext &Context = ThisSema.Context;
1924 
1925   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1926                       SourceLocation(), Sema::LookupTagName);
1927   ThisSema.LookupName(Result, S);
1928   if (Result.getResultKind() == LookupResult::Found)
1929     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1930       Context.setObjCSuperType(Context.getTagDeclType(TD));
1931 }
1932 
1933 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1934                                ASTContext::GetBuiltinTypeError Error) {
1935   switch (Error) {
1936   case ASTContext::GE_None:
1937     return "";
1938   case ASTContext::GE_Missing_type:
1939     return BuiltinInfo.getHeaderName(ID);
1940   case ASTContext::GE_Missing_stdio:
1941     return "stdio.h";
1942   case ASTContext::GE_Missing_setjmp:
1943     return "setjmp.h";
1944   case ASTContext::GE_Missing_ucontext:
1945     return "ucontext.h";
1946   }
1947   llvm_unreachable("unhandled error kind");
1948 }
1949 
1950 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1951 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1952 /// if we're creating this built-in in anticipation of redeclaring the
1953 /// built-in.
1954 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1955                                      Scope *S, bool ForRedeclaration,
1956                                      SourceLocation Loc) {
1957   LookupPredefedObjCSuperType(*this, S, II);
1958 
1959   ASTContext::GetBuiltinTypeError Error;
1960   QualType R = Context.GetBuiltinType(ID, Error);
1961   if (Error) {
1962     if (ForRedeclaration)
1963       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1964           << getHeaderName(Context.BuiltinInfo, ID, Error)
1965           << Context.BuiltinInfo.getName(ID);
1966     return nullptr;
1967   }
1968 
1969   if (!ForRedeclaration &&
1970       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1971        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1972     Diag(Loc, diag::ext_implicit_lib_function_decl)
1973         << Context.BuiltinInfo.getName(ID) << R;
1974     if (Context.BuiltinInfo.getHeaderName(ID) &&
1975         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1976       Diag(Loc, diag::note_include_header_or_declare)
1977           << Context.BuiltinInfo.getHeaderName(ID)
1978           << Context.BuiltinInfo.getName(ID);
1979   }
1980 
1981   if (R.isNull())
1982     return nullptr;
1983 
1984   DeclContext *Parent = Context.getTranslationUnitDecl();
1985   if (getLangOpts().CPlusPlus) {
1986     LinkageSpecDecl *CLinkageDecl =
1987         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1988                                 LinkageSpecDecl::lang_c, false);
1989     CLinkageDecl->setImplicit();
1990     Parent->addDecl(CLinkageDecl);
1991     Parent = CLinkageDecl;
1992   }
1993 
1994   FunctionDecl *New = FunctionDecl::Create(Context,
1995                                            Parent,
1996                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1997                                            SC_Extern,
1998                                            false,
1999                                            R->isFunctionProtoType());
2000   New->setImplicit();
2001 
2002   // Create Decl objects for each parameter, adding them to the
2003   // FunctionDecl.
2004   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2005     SmallVector<ParmVarDecl*, 16> Params;
2006     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2007       ParmVarDecl *parm =
2008           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2009                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2010                               SC_None, nullptr);
2011       parm->setScopeInfo(0, i);
2012       Params.push_back(parm);
2013     }
2014     New->setParams(Params);
2015   }
2016 
2017   AddKnownFunctionAttributes(New);
2018   RegisterLocallyScopedExternCDecl(New, S);
2019 
2020   // TUScope is the translation-unit scope to insert this function into.
2021   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2022   // relate Scopes to DeclContexts, and probably eliminate CurContext
2023   // entirely, but we're not there yet.
2024   DeclContext *SavedContext = CurContext;
2025   CurContext = Parent;
2026   PushOnScopeChains(New, TUScope);
2027   CurContext = SavedContext;
2028   return New;
2029 }
2030 
2031 /// Typedef declarations don't have linkage, but they still denote the same
2032 /// entity if their types are the same.
2033 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2034 /// isSameEntity.
2035 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2036                                                      TypedefNameDecl *Decl,
2037                                                      LookupResult &Previous) {
2038   // This is only interesting when modules are enabled.
2039   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2040     return;
2041 
2042   // Empty sets are uninteresting.
2043   if (Previous.empty())
2044     return;
2045 
2046   LookupResult::Filter Filter = Previous.makeFilter();
2047   while (Filter.hasNext()) {
2048     NamedDecl *Old = Filter.next();
2049 
2050     // Non-hidden declarations are never ignored.
2051     if (S.isVisible(Old))
2052       continue;
2053 
2054     // Declarations of the same entity are not ignored, even if they have
2055     // different linkages.
2056     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2057       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2058                                 Decl->getUnderlyingType()))
2059         continue;
2060 
2061       // If both declarations give a tag declaration a typedef name for linkage
2062       // purposes, then they declare the same entity.
2063       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2064           Decl->getAnonDeclWithTypedefName())
2065         continue;
2066     }
2067 
2068     Filter.erase();
2069   }
2070 
2071   Filter.done();
2072 }
2073 
2074 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2075   QualType OldType;
2076   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2077     OldType = OldTypedef->getUnderlyingType();
2078   else
2079     OldType = Context.getTypeDeclType(Old);
2080   QualType NewType = New->getUnderlyingType();
2081 
2082   if (NewType->isVariablyModifiedType()) {
2083     // Must not redefine a typedef with a variably-modified type.
2084     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2085     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2086       << Kind << NewType;
2087     if (Old->getLocation().isValid())
2088       notePreviousDefinition(Old, New->getLocation());
2089     New->setInvalidDecl();
2090     return true;
2091   }
2092 
2093   if (OldType != NewType &&
2094       !OldType->isDependentType() &&
2095       !NewType->isDependentType() &&
2096       !Context.hasSameType(OldType, NewType)) {
2097     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2098     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2099       << Kind << NewType << OldType;
2100     if (Old->getLocation().isValid())
2101       notePreviousDefinition(Old, New->getLocation());
2102     New->setInvalidDecl();
2103     return true;
2104   }
2105   return false;
2106 }
2107 
2108 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2109 /// same name and scope as a previous declaration 'Old'.  Figure out
2110 /// how to resolve this situation, merging decls or emitting
2111 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2112 ///
2113 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2114                                 LookupResult &OldDecls) {
2115   // If the new decl is known invalid already, don't bother doing any
2116   // merging checks.
2117   if (New->isInvalidDecl()) return;
2118 
2119   // Allow multiple definitions for ObjC built-in typedefs.
2120   // FIXME: Verify the underlying types are equivalent!
2121   if (getLangOpts().ObjC) {
2122     const IdentifierInfo *TypeID = New->getIdentifier();
2123     switch (TypeID->getLength()) {
2124     default: break;
2125     case 2:
2126       {
2127         if (!TypeID->isStr("id"))
2128           break;
2129         QualType T = New->getUnderlyingType();
2130         if (!T->isPointerType())
2131           break;
2132         if (!T->isVoidPointerType()) {
2133           QualType PT = T->getAs<PointerType>()->getPointeeType();
2134           if (!PT->isStructureType())
2135             break;
2136         }
2137         Context.setObjCIdRedefinitionType(T);
2138         // Install the built-in type for 'id', ignoring the current definition.
2139         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2140         return;
2141       }
2142     case 5:
2143       if (!TypeID->isStr("Class"))
2144         break;
2145       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2146       // Install the built-in type for 'Class', ignoring the current definition.
2147       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2148       return;
2149     case 3:
2150       if (!TypeID->isStr("SEL"))
2151         break;
2152       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2153       // Install the built-in type for 'SEL', ignoring the current definition.
2154       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2155       return;
2156     }
2157     // Fall through - the typedef name was not a builtin type.
2158   }
2159 
2160   // Verify the old decl was also a type.
2161   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2162   if (!Old) {
2163     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2164       << New->getDeclName();
2165 
2166     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2167     if (OldD->getLocation().isValid())
2168       notePreviousDefinition(OldD, New->getLocation());
2169 
2170     return New->setInvalidDecl();
2171   }
2172 
2173   // If the old declaration is invalid, just give up here.
2174   if (Old->isInvalidDecl())
2175     return New->setInvalidDecl();
2176 
2177   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2178     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2179     auto *NewTag = New->getAnonDeclWithTypedefName();
2180     NamedDecl *Hidden = nullptr;
2181     if (OldTag && NewTag &&
2182         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2183         !hasVisibleDefinition(OldTag, &Hidden)) {
2184       // There is a definition of this tag, but it is not visible. Use it
2185       // instead of our tag.
2186       New->setTypeForDecl(OldTD->getTypeForDecl());
2187       if (OldTD->isModed())
2188         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2189                                     OldTD->getUnderlyingType());
2190       else
2191         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2192 
2193       // Make the old tag definition visible.
2194       makeMergedDefinitionVisible(Hidden);
2195 
2196       // If this was an unscoped enumeration, yank all of its enumerators
2197       // out of the scope.
2198       if (isa<EnumDecl>(NewTag)) {
2199         Scope *EnumScope = getNonFieldDeclScope(S);
2200         for (auto *D : NewTag->decls()) {
2201           auto *ED = cast<EnumConstantDecl>(D);
2202           assert(EnumScope->isDeclScope(ED));
2203           EnumScope->RemoveDecl(ED);
2204           IdResolver.RemoveDecl(ED);
2205           ED->getLexicalDeclContext()->removeDecl(ED);
2206         }
2207       }
2208     }
2209   }
2210 
2211   // If the typedef types are not identical, reject them in all languages and
2212   // with any extensions enabled.
2213   if (isIncompatibleTypedef(Old, New))
2214     return;
2215 
2216   // The types match.  Link up the redeclaration chain and merge attributes if
2217   // the old declaration was a typedef.
2218   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2219     New->setPreviousDecl(Typedef);
2220     mergeDeclAttributes(New, Old);
2221   }
2222 
2223   if (getLangOpts().MicrosoftExt)
2224     return;
2225 
2226   if (getLangOpts().CPlusPlus) {
2227     // C++ [dcl.typedef]p2:
2228     //   In a given non-class scope, a typedef specifier can be used to
2229     //   redefine the name of any type declared in that scope to refer
2230     //   to the type to which it already refers.
2231     if (!isa<CXXRecordDecl>(CurContext))
2232       return;
2233 
2234     // C++0x [dcl.typedef]p4:
2235     //   In a given class scope, a typedef specifier can be used to redefine
2236     //   any class-name declared in that scope that is not also a typedef-name
2237     //   to refer to the type to which it already refers.
2238     //
2239     // This wording came in via DR424, which was a correction to the
2240     // wording in DR56, which accidentally banned code like:
2241     //
2242     //   struct S {
2243     //     typedef struct A { } A;
2244     //   };
2245     //
2246     // in the C++03 standard. We implement the C++0x semantics, which
2247     // allow the above but disallow
2248     //
2249     //   struct S {
2250     //     typedef int I;
2251     //     typedef int I;
2252     //   };
2253     //
2254     // since that was the intent of DR56.
2255     if (!isa<TypedefNameDecl>(Old))
2256       return;
2257 
2258     Diag(New->getLocation(), diag::err_redefinition)
2259       << New->getDeclName();
2260     notePreviousDefinition(Old, New->getLocation());
2261     return New->setInvalidDecl();
2262   }
2263 
2264   // Modules always permit redefinition of typedefs, as does C11.
2265   if (getLangOpts().Modules || getLangOpts().C11)
2266     return;
2267 
2268   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2269   // is normally mapped to an error, but can be controlled with
2270   // -Wtypedef-redefinition.  If either the original or the redefinition is
2271   // in a system header, don't emit this for compatibility with GCC.
2272   if (getDiagnostics().getSuppressSystemWarnings() &&
2273       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2274       (Old->isImplicit() ||
2275        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2276        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2277     return;
2278 
2279   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2280     << New->getDeclName();
2281   notePreviousDefinition(Old, New->getLocation());
2282 }
2283 
2284 /// DeclhasAttr - returns true if decl Declaration already has the target
2285 /// attribute.
2286 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2287   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2288   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2289   for (const auto *i : D->attrs())
2290     if (i->getKind() == A->getKind()) {
2291       if (Ann) {
2292         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2293           return true;
2294         continue;
2295       }
2296       // FIXME: Don't hardcode this check
2297       if (OA && isa<OwnershipAttr>(i))
2298         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2299       return true;
2300     }
2301 
2302   return false;
2303 }
2304 
2305 static bool isAttributeTargetADefinition(Decl *D) {
2306   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2307     return VD->isThisDeclarationADefinition();
2308   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2309     return TD->isCompleteDefinition() || TD->isBeingDefined();
2310   return true;
2311 }
2312 
2313 /// Merge alignment attributes from \p Old to \p New, taking into account the
2314 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2315 ///
2316 /// \return \c true if any attributes were added to \p New.
2317 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2318   // Look for alignas attributes on Old, and pick out whichever attribute
2319   // specifies the strictest alignment requirement.
2320   AlignedAttr *OldAlignasAttr = nullptr;
2321   AlignedAttr *OldStrictestAlignAttr = nullptr;
2322   unsigned OldAlign = 0;
2323   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2324     // FIXME: We have no way of representing inherited dependent alignments
2325     // in a case like:
2326     //   template<int A, int B> struct alignas(A) X;
2327     //   template<int A, int B> struct alignas(B) X {};
2328     // For now, we just ignore any alignas attributes which are not on the
2329     // definition in such a case.
2330     if (I->isAlignmentDependent())
2331       return false;
2332 
2333     if (I->isAlignas())
2334       OldAlignasAttr = I;
2335 
2336     unsigned Align = I->getAlignment(S.Context);
2337     if (Align > OldAlign) {
2338       OldAlign = Align;
2339       OldStrictestAlignAttr = I;
2340     }
2341   }
2342 
2343   // Look for alignas attributes on New.
2344   AlignedAttr *NewAlignasAttr = nullptr;
2345   unsigned NewAlign = 0;
2346   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2347     if (I->isAlignmentDependent())
2348       return false;
2349 
2350     if (I->isAlignas())
2351       NewAlignasAttr = I;
2352 
2353     unsigned Align = I->getAlignment(S.Context);
2354     if (Align > NewAlign)
2355       NewAlign = Align;
2356   }
2357 
2358   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2359     // Both declarations have 'alignas' attributes. We require them to match.
2360     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2361     // fall short. (If two declarations both have alignas, they must both match
2362     // every definition, and so must match each other if there is a definition.)
2363 
2364     // If either declaration only contains 'alignas(0)' specifiers, then it
2365     // specifies the natural alignment for the type.
2366     if (OldAlign == 0 || NewAlign == 0) {
2367       QualType Ty;
2368       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2369         Ty = VD->getType();
2370       else
2371         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2372 
2373       if (OldAlign == 0)
2374         OldAlign = S.Context.getTypeAlign(Ty);
2375       if (NewAlign == 0)
2376         NewAlign = S.Context.getTypeAlign(Ty);
2377     }
2378 
2379     if (OldAlign != NewAlign) {
2380       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2381         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2382         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2383       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2384     }
2385   }
2386 
2387   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2388     // C++11 [dcl.align]p6:
2389     //   if any declaration of an entity has an alignment-specifier,
2390     //   every defining declaration of that entity shall specify an
2391     //   equivalent alignment.
2392     // C11 6.7.5/7:
2393     //   If the definition of an object does not have an alignment
2394     //   specifier, any other declaration of that object shall also
2395     //   have no alignment specifier.
2396     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2397       << OldAlignasAttr;
2398     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2399       << OldAlignasAttr;
2400   }
2401 
2402   bool AnyAdded = false;
2403 
2404   // Ensure we have an attribute representing the strictest alignment.
2405   if (OldAlign > NewAlign) {
2406     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2407     Clone->setInherited(true);
2408     New->addAttr(Clone);
2409     AnyAdded = true;
2410   }
2411 
2412   // Ensure we have an alignas attribute if the old declaration had one.
2413   if (OldAlignasAttr && !NewAlignasAttr &&
2414       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2415     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2416     Clone->setInherited(true);
2417     New->addAttr(Clone);
2418     AnyAdded = true;
2419   }
2420 
2421   return AnyAdded;
2422 }
2423 
2424 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2425                                const InheritableAttr *Attr,
2426                                Sema::AvailabilityMergeKind AMK) {
2427   // This function copies an attribute Attr from a previous declaration to the
2428   // new declaration D if the new declaration doesn't itself have that attribute
2429   // yet or if that attribute allows duplicates.
2430   // If you're adding a new attribute that requires logic different from
2431   // "use explicit attribute on decl if present, else use attribute from
2432   // previous decl", for example if the attribute needs to be consistent
2433   // between redeclarations, you need to call a custom merge function here.
2434   InheritableAttr *NewAttr = nullptr;
2435   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2436   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2437     NewAttr = S.mergeAvailabilityAttr(
2438         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2439         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2440         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2441         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2442   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2443     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2444                                     AttrSpellingListIndex);
2445   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2446     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2447                                         AttrSpellingListIndex);
2448   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2449     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2450                                    AttrSpellingListIndex);
2451   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2452     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2453                                    AttrSpellingListIndex);
2454   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2455     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2456                                 FA->getFormatIdx(), FA->getFirstArg(),
2457                                 AttrSpellingListIndex);
2458   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2459     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2460                                  AttrSpellingListIndex);
2461   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2462     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2463                                  AttrSpellingListIndex);
2464   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2465     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2466                                        AttrSpellingListIndex,
2467                                        IA->getSemanticSpelling());
2468   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2469     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2470                                       &S.Context.Idents.get(AA->getSpelling()),
2471                                       AttrSpellingListIndex);
2472   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2473            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2474             isa<CUDAGlobalAttr>(Attr))) {
2475     // CUDA target attributes are part of function signature for
2476     // overloading purposes and must not be merged.
2477     return false;
2478   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2479     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2480   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2481     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2482   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2483     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2484   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2485     NewAttr = S.mergeCommonAttr(D, *CommonA);
2486   else if (isa<AlignedAttr>(Attr))
2487     // AlignedAttrs are handled separately, because we need to handle all
2488     // such attributes on a declaration at the same time.
2489     NewAttr = nullptr;
2490   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2491            (AMK == Sema::AMK_Override ||
2492             AMK == Sema::AMK_ProtocolImplementation))
2493     NewAttr = nullptr;
2494   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2495     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2496                               UA->getGuid());
2497   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2498     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2499   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2500     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2501   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2502     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2503 
2504   if (NewAttr) {
2505     NewAttr->setInherited(true);
2506     D->addAttr(NewAttr);
2507     if (isa<MSInheritanceAttr>(NewAttr))
2508       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2509     return true;
2510   }
2511 
2512   return false;
2513 }
2514 
2515 static const NamedDecl *getDefinition(const Decl *D) {
2516   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2517     return TD->getDefinition();
2518   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2519     const VarDecl *Def = VD->getDefinition();
2520     if (Def)
2521       return Def;
2522     return VD->getActingDefinition();
2523   }
2524   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2525     return FD->getDefinition();
2526   return nullptr;
2527 }
2528 
2529 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2530   for (const auto *Attribute : D->attrs())
2531     if (Attribute->getKind() == Kind)
2532       return true;
2533   return false;
2534 }
2535 
2536 /// checkNewAttributesAfterDef - If we already have a definition, check that
2537 /// there are no new attributes in this declaration.
2538 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2539   if (!New->hasAttrs())
2540     return;
2541 
2542   const NamedDecl *Def = getDefinition(Old);
2543   if (!Def || Def == New)
2544     return;
2545 
2546   AttrVec &NewAttributes = New->getAttrs();
2547   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2548     const Attr *NewAttribute = NewAttributes[I];
2549 
2550     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2551       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2552         Sema::SkipBodyInfo SkipBody;
2553         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2554 
2555         // If we're skipping this definition, drop the "alias" attribute.
2556         if (SkipBody.ShouldSkip) {
2557           NewAttributes.erase(NewAttributes.begin() + I);
2558           --E;
2559           continue;
2560         }
2561       } else {
2562         VarDecl *VD = cast<VarDecl>(New);
2563         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2564                                 VarDecl::TentativeDefinition
2565                             ? diag::err_alias_after_tentative
2566                             : diag::err_redefinition;
2567         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2568         if (Diag == diag::err_redefinition)
2569           S.notePreviousDefinition(Def, VD->getLocation());
2570         else
2571           S.Diag(Def->getLocation(), diag::note_previous_definition);
2572         VD->setInvalidDecl();
2573       }
2574       ++I;
2575       continue;
2576     }
2577 
2578     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2579       // Tentative definitions are only interesting for the alias check above.
2580       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2581         ++I;
2582         continue;
2583       }
2584     }
2585 
2586     if (hasAttribute(Def, NewAttribute->getKind())) {
2587       ++I;
2588       continue; // regular attr merging will take care of validating this.
2589     }
2590 
2591     if (isa<C11NoReturnAttr>(NewAttribute)) {
2592       // C's _Noreturn is allowed to be added to a function after it is defined.
2593       ++I;
2594       continue;
2595     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2596       if (AA->isAlignas()) {
2597         // C++11 [dcl.align]p6:
2598         //   if any declaration of an entity has an alignment-specifier,
2599         //   every defining declaration of that entity shall specify an
2600         //   equivalent alignment.
2601         // C11 6.7.5/7:
2602         //   If the definition of an object does not have an alignment
2603         //   specifier, any other declaration of that object shall also
2604         //   have no alignment specifier.
2605         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2606           << AA;
2607         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2608           << AA;
2609         NewAttributes.erase(NewAttributes.begin() + I);
2610         --E;
2611         continue;
2612       }
2613     }
2614 
2615     S.Diag(NewAttribute->getLocation(),
2616            diag::warn_attribute_precede_definition);
2617     S.Diag(Def->getLocation(), diag::note_previous_definition);
2618     NewAttributes.erase(NewAttributes.begin() + I);
2619     --E;
2620   }
2621 }
2622 
2623 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2624 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2625                                AvailabilityMergeKind AMK) {
2626   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2627     UsedAttr *NewAttr = OldAttr->clone(Context);
2628     NewAttr->setInherited(true);
2629     New->addAttr(NewAttr);
2630   }
2631 
2632   if (!Old->hasAttrs() && !New->hasAttrs())
2633     return;
2634 
2635   // Attributes declared post-definition are currently ignored.
2636   checkNewAttributesAfterDef(*this, New, Old);
2637 
2638   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2639     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2640       if (OldA->getLabel() != NewA->getLabel()) {
2641         // This redeclaration changes __asm__ label.
2642         Diag(New->getLocation(), diag::err_different_asm_label);
2643         Diag(OldA->getLocation(), diag::note_previous_declaration);
2644       }
2645     } else if (Old->isUsed()) {
2646       // This redeclaration adds an __asm__ label to a declaration that has
2647       // already been ODR-used.
2648       Diag(New->getLocation(), diag::err_late_asm_label_name)
2649         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2650     }
2651   }
2652 
2653   // Re-declaration cannot add abi_tag's.
2654   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2655     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2656       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2657         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2658                       NewTag) == OldAbiTagAttr->tags_end()) {
2659           Diag(NewAbiTagAttr->getLocation(),
2660                diag::err_new_abi_tag_on_redeclaration)
2661               << NewTag;
2662           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2663         }
2664       }
2665     } else {
2666       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2667       Diag(Old->getLocation(), diag::note_previous_declaration);
2668     }
2669   }
2670 
2671   // This redeclaration adds a section attribute.
2672   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2673     if (auto *VD = dyn_cast<VarDecl>(New)) {
2674       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2675         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2676         Diag(Old->getLocation(), diag::note_previous_declaration);
2677       }
2678     }
2679   }
2680 
2681   // Redeclaration adds code-seg attribute.
2682   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2683   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2684       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2685     Diag(New->getLocation(), diag::warn_mismatched_section)
2686          << 0 /*codeseg*/;
2687     Diag(Old->getLocation(), diag::note_previous_declaration);
2688   }
2689 
2690   if (!Old->hasAttrs())
2691     return;
2692 
2693   bool foundAny = New->hasAttrs();
2694 
2695   // Ensure that any moving of objects within the allocated map is done before
2696   // we process them.
2697   if (!foundAny) New->setAttrs(AttrVec());
2698 
2699   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2700     // Ignore deprecated/unavailable/availability attributes if requested.
2701     AvailabilityMergeKind LocalAMK = AMK_None;
2702     if (isa<DeprecatedAttr>(I) ||
2703         isa<UnavailableAttr>(I) ||
2704         isa<AvailabilityAttr>(I)) {
2705       switch (AMK) {
2706       case AMK_None:
2707         continue;
2708 
2709       case AMK_Redeclaration:
2710       case AMK_Override:
2711       case AMK_ProtocolImplementation:
2712         LocalAMK = AMK;
2713         break;
2714       }
2715     }
2716 
2717     // Already handled.
2718     if (isa<UsedAttr>(I))
2719       continue;
2720 
2721     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2722       foundAny = true;
2723   }
2724 
2725   if (mergeAlignedAttrs(*this, New, Old))
2726     foundAny = true;
2727 
2728   if (!foundAny) New->dropAttrs();
2729 }
2730 
2731 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2732 /// to the new one.
2733 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2734                                      const ParmVarDecl *oldDecl,
2735                                      Sema &S) {
2736   // C++11 [dcl.attr.depend]p2:
2737   //   The first declaration of a function shall specify the
2738   //   carries_dependency attribute for its declarator-id if any declaration
2739   //   of the function specifies the carries_dependency attribute.
2740   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2741   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2742     S.Diag(CDA->getLocation(),
2743            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2744     // Find the first declaration of the parameter.
2745     // FIXME: Should we build redeclaration chains for function parameters?
2746     const FunctionDecl *FirstFD =
2747       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2748     const ParmVarDecl *FirstVD =
2749       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2750     S.Diag(FirstVD->getLocation(),
2751            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2752   }
2753 
2754   if (!oldDecl->hasAttrs())
2755     return;
2756 
2757   bool foundAny = newDecl->hasAttrs();
2758 
2759   // Ensure that any moving of objects within the allocated map is
2760   // done before we process them.
2761   if (!foundAny) newDecl->setAttrs(AttrVec());
2762 
2763   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2764     if (!DeclHasAttr(newDecl, I)) {
2765       InheritableAttr *newAttr =
2766         cast<InheritableParamAttr>(I->clone(S.Context));
2767       newAttr->setInherited(true);
2768       newDecl->addAttr(newAttr);
2769       foundAny = true;
2770     }
2771   }
2772 
2773   if (!foundAny) newDecl->dropAttrs();
2774 }
2775 
2776 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2777                                 const ParmVarDecl *OldParam,
2778                                 Sema &S) {
2779   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2780     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2781       if (*Oldnullability != *Newnullability) {
2782         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2783           << DiagNullabilityKind(
2784                *Newnullability,
2785                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2786                 != 0))
2787           << DiagNullabilityKind(
2788                *Oldnullability,
2789                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2790                 != 0));
2791         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2792       }
2793     } else {
2794       QualType NewT = NewParam->getType();
2795       NewT = S.Context.getAttributedType(
2796                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2797                          NewT, NewT);
2798       NewParam->setType(NewT);
2799     }
2800   }
2801 }
2802 
2803 namespace {
2804 
2805 /// Used in MergeFunctionDecl to keep track of function parameters in
2806 /// C.
2807 struct GNUCompatibleParamWarning {
2808   ParmVarDecl *OldParm;
2809   ParmVarDecl *NewParm;
2810   QualType PromotedType;
2811 };
2812 
2813 } // end anonymous namespace
2814 
2815 /// getSpecialMember - get the special member enum for a method.
2816 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2817   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2818     if (Ctor->isDefaultConstructor())
2819       return Sema::CXXDefaultConstructor;
2820 
2821     if (Ctor->isCopyConstructor())
2822       return Sema::CXXCopyConstructor;
2823 
2824     if (Ctor->isMoveConstructor())
2825       return Sema::CXXMoveConstructor;
2826   } else if (isa<CXXDestructorDecl>(MD)) {
2827     return Sema::CXXDestructor;
2828   } else if (MD->isCopyAssignmentOperator()) {
2829     return Sema::CXXCopyAssignment;
2830   } else if (MD->isMoveAssignmentOperator()) {
2831     return Sema::CXXMoveAssignment;
2832   }
2833 
2834   return Sema::CXXInvalid;
2835 }
2836 
2837 // Determine whether the previous declaration was a definition, implicit
2838 // declaration, or a declaration.
2839 template <typename T>
2840 static std::pair<diag::kind, SourceLocation>
2841 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2842   diag::kind PrevDiag;
2843   SourceLocation OldLocation = Old->getLocation();
2844   if (Old->isThisDeclarationADefinition())
2845     PrevDiag = diag::note_previous_definition;
2846   else if (Old->isImplicit()) {
2847     PrevDiag = diag::note_previous_implicit_declaration;
2848     if (OldLocation.isInvalid())
2849       OldLocation = New->getLocation();
2850   } else
2851     PrevDiag = diag::note_previous_declaration;
2852   return std::make_pair(PrevDiag, OldLocation);
2853 }
2854 
2855 /// canRedefineFunction - checks if a function can be redefined. Currently,
2856 /// only extern inline functions can be redefined, and even then only in
2857 /// GNU89 mode.
2858 static bool canRedefineFunction(const FunctionDecl *FD,
2859                                 const LangOptions& LangOpts) {
2860   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2861           !LangOpts.CPlusPlus &&
2862           FD->isInlineSpecified() &&
2863           FD->getStorageClass() == SC_Extern);
2864 }
2865 
2866 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2867   const AttributedType *AT = T->getAs<AttributedType>();
2868   while (AT && !AT->isCallingConv())
2869     AT = AT->getModifiedType()->getAs<AttributedType>();
2870   return AT;
2871 }
2872 
2873 template <typename T>
2874 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2875   const DeclContext *DC = Old->getDeclContext();
2876   if (DC->isRecord())
2877     return false;
2878 
2879   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2880   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2881     return true;
2882   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2883     return true;
2884   return false;
2885 }
2886 
2887 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2888 static bool isExternC(VarTemplateDecl *) { return false; }
2889 
2890 /// Check whether a redeclaration of an entity introduced by a
2891 /// using-declaration is valid, given that we know it's not an overload
2892 /// (nor a hidden tag declaration).
2893 template<typename ExpectedDecl>
2894 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2895                                    ExpectedDecl *New) {
2896   // C++11 [basic.scope.declarative]p4:
2897   //   Given a set of declarations in a single declarative region, each of
2898   //   which specifies the same unqualified name,
2899   //   -- they shall all refer to the same entity, or all refer to functions
2900   //      and function templates; or
2901   //   -- exactly one declaration shall declare a class name or enumeration
2902   //      name that is not a typedef name and the other declarations shall all
2903   //      refer to the same variable or enumerator, or all refer to functions
2904   //      and function templates; in this case the class name or enumeration
2905   //      name is hidden (3.3.10).
2906 
2907   // C++11 [namespace.udecl]p14:
2908   //   If a function declaration in namespace scope or block scope has the
2909   //   same name and the same parameter-type-list as a function introduced
2910   //   by a using-declaration, and the declarations do not declare the same
2911   //   function, the program is ill-formed.
2912 
2913   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2914   if (Old &&
2915       !Old->getDeclContext()->getRedeclContext()->Equals(
2916           New->getDeclContext()->getRedeclContext()) &&
2917       !(isExternC(Old) && isExternC(New)))
2918     Old = nullptr;
2919 
2920   if (!Old) {
2921     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2922     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2923     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2924     return true;
2925   }
2926   return false;
2927 }
2928 
2929 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2930                                             const FunctionDecl *B) {
2931   assert(A->getNumParams() == B->getNumParams());
2932 
2933   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2934     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2935     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2936     if (AttrA == AttrB)
2937       return true;
2938     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2939   };
2940 
2941   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2942 }
2943 
2944 /// If necessary, adjust the semantic declaration context for a qualified
2945 /// declaration to name the correct inline namespace within the qualifier.
2946 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2947                                                DeclaratorDecl *OldD) {
2948   // The only case where we need to update the DeclContext is when
2949   // redeclaration lookup for a qualified name finds a declaration
2950   // in an inline namespace within the context named by the qualifier:
2951   //
2952   //   inline namespace N { int f(); }
2953   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2954   //
2955   // For unqualified declarations, the semantic context *can* change
2956   // along the redeclaration chain (for local extern declarations,
2957   // extern "C" declarations, and friend declarations in particular).
2958   if (!NewD->getQualifier())
2959     return;
2960 
2961   // NewD is probably already in the right context.
2962   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2963   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2964   if (NamedDC->Equals(SemaDC))
2965     return;
2966 
2967   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2968           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2969          "unexpected context for redeclaration");
2970 
2971   auto *LexDC = NewD->getLexicalDeclContext();
2972   auto FixSemaDC = [=](NamedDecl *D) {
2973     if (!D)
2974       return;
2975     D->setDeclContext(SemaDC);
2976     D->setLexicalDeclContext(LexDC);
2977   };
2978 
2979   FixSemaDC(NewD);
2980   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2981     FixSemaDC(FD->getDescribedFunctionTemplate());
2982   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2983     FixSemaDC(VD->getDescribedVarTemplate());
2984 }
2985 
2986 /// MergeFunctionDecl - We just parsed a function 'New' from
2987 /// declarator D which has the same name and scope as a previous
2988 /// declaration 'Old'.  Figure out how to resolve this situation,
2989 /// merging decls or emitting diagnostics as appropriate.
2990 ///
2991 /// In C++, New and Old must be declarations that are not
2992 /// overloaded. Use IsOverload to determine whether New and Old are
2993 /// overloaded, and to select the Old declaration that New should be
2994 /// merged with.
2995 ///
2996 /// Returns true if there was an error, false otherwise.
2997 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2998                              Scope *S, bool MergeTypeWithOld) {
2999   // Verify the old decl was also a function.
3000   FunctionDecl *Old = OldD->getAsFunction();
3001   if (!Old) {
3002     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3003       if (New->getFriendObjectKind()) {
3004         Diag(New->getLocation(), diag::err_using_decl_friend);
3005         Diag(Shadow->getTargetDecl()->getLocation(),
3006              diag::note_using_decl_target);
3007         Diag(Shadow->getUsingDecl()->getLocation(),
3008              diag::note_using_decl) << 0;
3009         return true;
3010       }
3011 
3012       // Check whether the two declarations might declare the same function.
3013       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3014         return true;
3015       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3016     } else {
3017       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3018         << New->getDeclName();
3019       notePreviousDefinition(OldD, New->getLocation());
3020       return true;
3021     }
3022   }
3023 
3024   // If the old declaration is invalid, just give up here.
3025   if (Old->isInvalidDecl())
3026     return true;
3027 
3028   // Disallow redeclaration of some builtins.
3029   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3030     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3031     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3032         << Old << Old->getType();
3033     return true;
3034   }
3035 
3036   diag::kind PrevDiag;
3037   SourceLocation OldLocation;
3038   std::tie(PrevDiag, OldLocation) =
3039       getNoteDiagForInvalidRedeclaration(Old, New);
3040 
3041   // Don't complain about this if we're in GNU89 mode and the old function
3042   // is an extern inline function.
3043   // Don't complain about specializations. They are not supposed to have
3044   // storage classes.
3045   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3046       New->getStorageClass() == SC_Static &&
3047       Old->hasExternalFormalLinkage() &&
3048       !New->getTemplateSpecializationInfo() &&
3049       !canRedefineFunction(Old, getLangOpts())) {
3050     if (getLangOpts().MicrosoftExt) {
3051       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3052       Diag(OldLocation, PrevDiag);
3053     } else {
3054       Diag(New->getLocation(), diag::err_static_non_static) << New;
3055       Diag(OldLocation, PrevDiag);
3056       return true;
3057     }
3058   }
3059 
3060   if (New->hasAttr<InternalLinkageAttr>() &&
3061       !Old->hasAttr<InternalLinkageAttr>()) {
3062     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3063         << New->getDeclName();
3064     notePreviousDefinition(Old, New->getLocation());
3065     New->dropAttr<InternalLinkageAttr>();
3066   }
3067 
3068   if (CheckRedeclarationModuleOwnership(New, Old))
3069     return true;
3070 
3071   if (!getLangOpts().CPlusPlus) {
3072     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3073     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3074       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3075         << New << OldOvl;
3076 
3077       // Try our best to find a decl that actually has the overloadable
3078       // attribute for the note. In most cases (e.g. programs with only one
3079       // broken declaration/definition), this won't matter.
3080       //
3081       // FIXME: We could do this if we juggled some extra state in
3082       // OverloadableAttr, rather than just removing it.
3083       const Decl *DiagOld = Old;
3084       if (OldOvl) {
3085         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3086           const auto *A = D->getAttr<OverloadableAttr>();
3087           return A && !A->isImplicit();
3088         });
3089         // If we've implicitly added *all* of the overloadable attrs to this
3090         // chain, emitting a "previous redecl" note is pointless.
3091         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3092       }
3093 
3094       if (DiagOld)
3095         Diag(DiagOld->getLocation(),
3096              diag::note_attribute_overloadable_prev_overload)
3097           << OldOvl;
3098 
3099       if (OldOvl)
3100         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3101       else
3102         New->dropAttr<OverloadableAttr>();
3103     }
3104   }
3105 
3106   // If a function is first declared with a calling convention, but is later
3107   // declared or defined without one, all following decls assume the calling
3108   // convention of the first.
3109   //
3110   // It's OK if a function is first declared without a calling convention,
3111   // but is later declared or defined with the default calling convention.
3112   //
3113   // To test if either decl has an explicit calling convention, we look for
3114   // AttributedType sugar nodes on the type as written.  If they are missing or
3115   // were canonicalized away, we assume the calling convention was implicit.
3116   //
3117   // Note also that we DO NOT return at this point, because we still have
3118   // other tests to run.
3119   QualType OldQType = Context.getCanonicalType(Old->getType());
3120   QualType NewQType = Context.getCanonicalType(New->getType());
3121   const FunctionType *OldType = cast<FunctionType>(OldQType);
3122   const FunctionType *NewType = cast<FunctionType>(NewQType);
3123   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3124   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3125   bool RequiresAdjustment = false;
3126 
3127   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3128     FunctionDecl *First = Old->getFirstDecl();
3129     const FunctionType *FT =
3130         First->getType().getCanonicalType()->castAs<FunctionType>();
3131     FunctionType::ExtInfo FI = FT->getExtInfo();
3132     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3133     if (!NewCCExplicit) {
3134       // Inherit the CC from the previous declaration if it was specified
3135       // there but not here.
3136       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3137       RequiresAdjustment = true;
3138     } else {
3139       // Calling conventions aren't compatible, so complain.
3140       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3141       Diag(New->getLocation(), diag::err_cconv_change)
3142         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3143         << !FirstCCExplicit
3144         << (!FirstCCExplicit ? "" :
3145             FunctionType::getNameForCallConv(FI.getCC()));
3146 
3147       // Put the note on the first decl, since it is the one that matters.
3148       Diag(First->getLocation(), diag::note_previous_declaration);
3149       return true;
3150     }
3151   }
3152 
3153   // FIXME: diagnose the other way around?
3154   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3155     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3156     RequiresAdjustment = true;
3157   }
3158 
3159   // Merge regparm attribute.
3160   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3161       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3162     if (NewTypeInfo.getHasRegParm()) {
3163       Diag(New->getLocation(), diag::err_regparm_mismatch)
3164         << NewType->getRegParmType()
3165         << OldType->getRegParmType();
3166       Diag(OldLocation, diag::note_previous_declaration);
3167       return true;
3168     }
3169 
3170     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3171     RequiresAdjustment = true;
3172   }
3173 
3174   // Merge ns_returns_retained attribute.
3175   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3176     if (NewTypeInfo.getProducesResult()) {
3177       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3178           << "'ns_returns_retained'";
3179       Diag(OldLocation, diag::note_previous_declaration);
3180       return true;
3181     }
3182 
3183     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3184     RequiresAdjustment = true;
3185   }
3186 
3187   if (OldTypeInfo.getNoCallerSavedRegs() !=
3188       NewTypeInfo.getNoCallerSavedRegs()) {
3189     if (NewTypeInfo.getNoCallerSavedRegs()) {
3190       AnyX86NoCallerSavedRegistersAttr *Attr =
3191         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3192       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3193       Diag(OldLocation, diag::note_previous_declaration);
3194       return true;
3195     }
3196 
3197     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3198     RequiresAdjustment = true;
3199   }
3200 
3201   if (RequiresAdjustment) {
3202     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3203     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3204     New->setType(QualType(AdjustedType, 0));
3205     NewQType = Context.getCanonicalType(New->getType());
3206     NewType = cast<FunctionType>(NewQType);
3207   }
3208 
3209   // If this redeclaration makes the function inline, we may need to add it to
3210   // UndefinedButUsed.
3211   if (!Old->isInlined() && New->isInlined() &&
3212       !New->hasAttr<GNUInlineAttr>() &&
3213       !getLangOpts().GNUInline &&
3214       Old->isUsed(false) &&
3215       !Old->isDefined() && !New->isThisDeclarationADefinition())
3216     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3217                                            SourceLocation()));
3218 
3219   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3220   // about it.
3221   if (New->hasAttr<GNUInlineAttr>() &&
3222       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3223     UndefinedButUsed.erase(Old->getCanonicalDecl());
3224   }
3225 
3226   // If pass_object_size params don't match up perfectly, this isn't a valid
3227   // redeclaration.
3228   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3229       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3230     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3231         << New->getDeclName();
3232     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3233     return true;
3234   }
3235 
3236   if (getLangOpts().CPlusPlus) {
3237     // C++1z [over.load]p2
3238     //   Certain function declarations cannot be overloaded:
3239     //     -- Function declarations that differ only in the return type,
3240     //        the exception specification, or both cannot be overloaded.
3241 
3242     // Check the exception specifications match. This may recompute the type of
3243     // both Old and New if it resolved exception specifications, so grab the
3244     // types again after this. Because this updates the type, we do this before
3245     // any of the other checks below, which may update the "de facto" NewQType
3246     // but do not necessarily update the type of New.
3247     if (CheckEquivalentExceptionSpec(Old, New))
3248       return true;
3249     OldQType = Context.getCanonicalType(Old->getType());
3250     NewQType = Context.getCanonicalType(New->getType());
3251 
3252     // Go back to the type source info to compare the declared return types,
3253     // per C++1y [dcl.type.auto]p13:
3254     //   Redeclarations or specializations of a function or function template
3255     //   with a declared return type that uses a placeholder type shall also
3256     //   use that placeholder, not a deduced type.
3257     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3258     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3259     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3260         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3261                                        OldDeclaredReturnType)) {
3262       QualType ResQT;
3263       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3264           OldDeclaredReturnType->isObjCObjectPointerType())
3265         // FIXME: This does the wrong thing for a deduced return type.
3266         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3267       if (ResQT.isNull()) {
3268         if (New->isCXXClassMember() && New->isOutOfLine())
3269           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3270               << New << New->getReturnTypeSourceRange();
3271         else
3272           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3273               << New->getReturnTypeSourceRange();
3274         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3275                                     << Old->getReturnTypeSourceRange();
3276         return true;
3277       }
3278       else
3279         NewQType = ResQT;
3280     }
3281 
3282     QualType OldReturnType = OldType->getReturnType();
3283     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3284     if (OldReturnType != NewReturnType) {
3285       // If this function has a deduced return type and has already been
3286       // defined, copy the deduced value from the old declaration.
3287       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3288       if (OldAT && OldAT->isDeduced()) {
3289         New->setType(
3290             SubstAutoType(New->getType(),
3291                           OldAT->isDependentType() ? Context.DependentTy
3292                                                    : OldAT->getDeducedType()));
3293         NewQType = Context.getCanonicalType(
3294             SubstAutoType(NewQType,
3295                           OldAT->isDependentType() ? Context.DependentTy
3296                                                    : OldAT->getDeducedType()));
3297       }
3298     }
3299 
3300     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3301     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3302     if (OldMethod && NewMethod) {
3303       // Preserve triviality.
3304       NewMethod->setTrivial(OldMethod->isTrivial());
3305 
3306       // MSVC allows explicit template specialization at class scope:
3307       // 2 CXXMethodDecls referring to the same function will be injected.
3308       // We don't want a redeclaration error.
3309       bool IsClassScopeExplicitSpecialization =
3310                               OldMethod->isFunctionTemplateSpecialization() &&
3311                               NewMethod->isFunctionTemplateSpecialization();
3312       bool isFriend = NewMethod->getFriendObjectKind();
3313 
3314       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3315           !IsClassScopeExplicitSpecialization) {
3316         //    -- Member function declarations with the same name and the
3317         //       same parameter types cannot be overloaded if any of them
3318         //       is a static member function declaration.
3319         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3320           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3321           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3322           return true;
3323         }
3324 
3325         // C++ [class.mem]p1:
3326         //   [...] A member shall not be declared twice in the
3327         //   member-specification, except that a nested class or member
3328         //   class template can be declared and then later defined.
3329         if (!inTemplateInstantiation()) {
3330           unsigned NewDiag;
3331           if (isa<CXXConstructorDecl>(OldMethod))
3332             NewDiag = diag::err_constructor_redeclared;
3333           else if (isa<CXXDestructorDecl>(NewMethod))
3334             NewDiag = diag::err_destructor_redeclared;
3335           else if (isa<CXXConversionDecl>(NewMethod))
3336             NewDiag = diag::err_conv_function_redeclared;
3337           else
3338             NewDiag = diag::err_member_redeclared;
3339 
3340           Diag(New->getLocation(), NewDiag);
3341         } else {
3342           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3343             << New << New->getType();
3344         }
3345         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3346         return true;
3347 
3348       // Complain if this is an explicit declaration of a special
3349       // member that was initially declared implicitly.
3350       //
3351       // As an exception, it's okay to befriend such methods in order
3352       // to permit the implicit constructor/destructor/operator calls.
3353       } else if (OldMethod->isImplicit()) {
3354         if (isFriend) {
3355           NewMethod->setImplicit();
3356         } else {
3357           Diag(NewMethod->getLocation(),
3358                diag::err_definition_of_implicitly_declared_member)
3359             << New << getSpecialMember(OldMethod);
3360           return true;
3361         }
3362       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3363         Diag(NewMethod->getLocation(),
3364              diag::err_definition_of_explicitly_defaulted_member)
3365           << getSpecialMember(OldMethod);
3366         return true;
3367       }
3368     }
3369 
3370     // C++11 [dcl.attr.noreturn]p1:
3371     //   The first declaration of a function shall specify the noreturn
3372     //   attribute if any declaration of that function specifies the noreturn
3373     //   attribute.
3374     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3375     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3376       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3377       Diag(Old->getFirstDecl()->getLocation(),
3378            diag::note_noreturn_missing_first_decl);
3379     }
3380 
3381     // C++11 [dcl.attr.depend]p2:
3382     //   The first declaration of a function shall specify the
3383     //   carries_dependency attribute for its declarator-id if any declaration
3384     //   of the function specifies the carries_dependency attribute.
3385     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3386     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3387       Diag(CDA->getLocation(),
3388            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3389       Diag(Old->getFirstDecl()->getLocation(),
3390            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3391     }
3392 
3393     // (C++98 8.3.5p3):
3394     //   All declarations for a function shall agree exactly in both the
3395     //   return type and the parameter-type-list.
3396     // We also want to respect all the extended bits except noreturn.
3397 
3398     // noreturn should now match unless the old type info didn't have it.
3399     QualType OldQTypeForComparison = OldQType;
3400     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3401       auto *OldType = OldQType->castAs<FunctionProtoType>();
3402       const FunctionType *OldTypeForComparison
3403         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3404       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3405       assert(OldQTypeForComparison.isCanonical());
3406     }
3407 
3408     if (haveIncompatibleLanguageLinkages(Old, New)) {
3409       // As a special case, retain the language linkage from previous
3410       // declarations of a friend function as an extension.
3411       //
3412       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3413       // and is useful because there's otherwise no way to specify language
3414       // linkage within class scope.
3415       //
3416       // Check cautiously as the friend object kind isn't yet complete.
3417       if (New->getFriendObjectKind() != Decl::FOK_None) {
3418         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3419         Diag(OldLocation, PrevDiag);
3420       } else {
3421         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3422         Diag(OldLocation, PrevDiag);
3423         return true;
3424       }
3425     }
3426 
3427     if (OldQTypeForComparison == NewQType)
3428       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3429 
3430     // If the types are imprecise (due to dependent constructs in friends or
3431     // local extern declarations), it's OK if they differ. We'll check again
3432     // during instantiation.
3433     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3434       return false;
3435 
3436     // Fall through for conflicting redeclarations and redefinitions.
3437   }
3438 
3439   // C: Function types need to be compatible, not identical. This handles
3440   // duplicate function decls like "void f(int); void f(enum X);" properly.
3441   if (!getLangOpts().CPlusPlus &&
3442       Context.typesAreCompatible(OldQType, NewQType)) {
3443     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3444     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3445     const FunctionProtoType *OldProto = nullptr;
3446     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3447         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3448       // The old declaration provided a function prototype, but the
3449       // new declaration does not. Merge in the prototype.
3450       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3451       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3452       NewQType =
3453           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3454                                   OldProto->getExtProtoInfo());
3455       New->setType(NewQType);
3456       New->setHasInheritedPrototype();
3457 
3458       // Synthesize parameters with the same types.
3459       SmallVector<ParmVarDecl*, 16> Params;
3460       for (const auto &ParamType : OldProto->param_types()) {
3461         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3462                                                  SourceLocation(), nullptr,
3463                                                  ParamType, /*TInfo=*/nullptr,
3464                                                  SC_None, nullptr);
3465         Param->setScopeInfo(0, Params.size());
3466         Param->setImplicit();
3467         Params.push_back(Param);
3468       }
3469 
3470       New->setParams(Params);
3471     }
3472 
3473     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3474   }
3475 
3476   // GNU C permits a K&R definition to follow a prototype declaration
3477   // if the declared types of the parameters in the K&R definition
3478   // match the types in the prototype declaration, even when the
3479   // promoted types of the parameters from the K&R definition differ
3480   // from the types in the prototype. GCC then keeps the types from
3481   // the prototype.
3482   //
3483   // If a variadic prototype is followed by a non-variadic K&R definition,
3484   // the K&R definition becomes variadic.  This is sort of an edge case, but
3485   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3486   // C99 6.9.1p8.
3487   if (!getLangOpts().CPlusPlus &&
3488       Old->hasPrototype() && !New->hasPrototype() &&
3489       New->getType()->getAs<FunctionProtoType>() &&
3490       Old->getNumParams() == New->getNumParams()) {
3491     SmallVector<QualType, 16> ArgTypes;
3492     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3493     const FunctionProtoType *OldProto
3494       = Old->getType()->getAs<FunctionProtoType>();
3495     const FunctionProtoType *NewProto
3496       = New->getType()->getAs<FunctionProtoType>();
3497 
3498     // Determine whether this is the GNU C extension.
3499     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3500                                                NewProto->getReturnType());
3501     bool LooseCompatible = !MergedReturn.isNull();
3502     for (unsigned Idx = 0, End = Old->getNumParams();
3503          LooseCompatible && Idx != End; ++Idx) {
3504       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3505       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3506       if (Context.typesAreCompatible(OldParm->getType(),
3507                                      NewProto->getParamType(Idx))) {
3508         ArgTypes.push_back(NewParm->getType());
3509       } else if (Context.typesAreCompatible(OldParm->getType(),
3510                                             NewParm->getType(),
3511                                             /*CompareUnqualified=*/true)) {
3512         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3513                                            NewProto->getParamType(Idx) };
3514         Warnings.push_back(Warn);
3515         ArgTypes.push_back(NewParm->getType());
3516       } else
3517         LooseCompatible = false;
3518     }
3519 
3520     if (LooseCompatible) {
3521       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3522         Diag(Warnings[Warn].NewParm->getLocation(),
3523              diag::ext_param_promoted_not_compatible_with_prototype)
3524           << Warnings[Warn].PromotedType
3525           << Warnings[Warn].OldParm->getType();
3526         if (Warnings[Warn].OldParm->getLocation().isValid())
3527           Diag(Warnings[Warn].OldParm->getLocation(),
3528                diag::note_previous_declaration);
3529       }
3530 
3531       if (MergeTypeWithOld)
3532         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3533                                              OldProto->getExtProtoInfo()));
3534       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3535     }
3536 
3537     // Fall through to diagnose conflicting types.
3538   }
3539 
3540   // A function that has already been declared has been redeclared or
3541   // defined with a different type; show an appropriate diagnostic.
3542 
3543   // If the previous declaration was an implicitly-generated builtin
3544   // declaration, then at the very least we should use a specialized note.
3545   unsigned BuiltinID;
3546   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3547     // If it's actually a library-defined builtin function like 'malloc'
3548     // or 'printf', just warn about the incompatible redeclaration.
3549     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3550       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3551       Diag(OldLocation, diag::note_previous_builtin_declaration)
3552         << Old << Old->getType();
3553 
3554       // If this is a global redeclaration, just forget hereafter
3555       // about the "builtin-ness" of the function.
3556       //
3557       // Doing this for local extern declarations is problematic.  If
3558       // the builtin declaration remains visible, a second invalid
3559       // local declaration will produce a hard error; if it doesn't
3560       // remain visible, a single bogus local redeclaration (which is
3561       // actually only a warning) could break all the downstream code.
3562       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3563         New->getIdentifier()->revertBuiltin();
3564 
3565       return false;
3566     }
3567 
3568     PrevDiag = diag::note_previous_builtin_declaration;
3569   }
3570 
3571   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3572   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3573   return true;
3574 }
3575 
3576 /// Completes the merge of two function declarations that are
3577 /// known to be compatible.
3578 ///
3579 /// This routine handles the merging of attributes and other
3580 /// properties of function declarations from the old declaration to
3581 /// the new declaration, once we know that New is in fact a
3582 /// redeclaration of Old.
3583 ///
3584 /// \returns false
3585 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3586                                         Scope *S, bool MergeTypeWithOld) {
3587   // Merge the attributes
3588   mergeDeclAttributes(New, Old);
3589 
3590   // Merge "pure" flag.
3591   if (Old->isPure())
3592     New->setPure();
3593 
3594   // Merge "used" flag.
3595   if (Old->getMostRecentDecl()->isUsed(false))
3596     New->setIsUsed();
3597 
3598   // Merge attributes from the parameters.  These can mismatch with K&R
3599   // declarations.
3600   if (New->getNumParams() == Old->getNumParams())
3601       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3602         ParmVarDecl *NewParam = New->getParamDecl(i);
3603         ParmVarDecl *OldParam = Old->getParamDecl(i);
3604         mergeParamDeclAttributes(NewParam, OldParam, *this);
3605         mergeParamDeclTypes(NewParam, OldParam, *this);
3606       }
3607 
3608   if (getLangOpts().CPlusPlus)
3609     return MergeCXXFunctionDecl(New, Old, S);
3610 
3611   // Merge the function types so the we get the composite types for the return
3612   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3613   // was visible.
3614   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3615   if (!Merged.isNull() && MergeTypeWithOld)
3616     New->setType(Merged);
3617 
3618   return false;
3619 }
3620 
3621 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3622                                 ObjCMethodDecl *oldMethod) {
3623   // Merge the attributes, including deprecated/unavailable
3624   AvailabilityMergeKind MergeKind =
3625     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3626       ? AMK_ProtocolImplementation
3627       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3628                                                        : AMK_Override;
3629 
3630   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3631 
3632   // Merge attributes from the parameters.
3633   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3634                                        oe = oldMethod->param_end();
3635   for (ObjCMethodDecl::param_iterator
3636          ni = newMethod->param_begin(), ne = newMethod->param_end();
3637        ni != ne && oi != oe; ++ni, ++oi)
3638     mergeParamDeclAttributes(*ni, *oi, *this);
3639 
3640   CheckObjCMethodOverride(newMethod, oldMethod);
3641 }
3642 
3643 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3644   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3645 
3646   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3647          ? diag::err_redefinition_different_type
3648          : diag::err_redeclaration_different_type)
3649     << New->getDeclName() << New->getType() << Old->getType();
3650 
3651   diag::kind PrevDiag;
3652   SourceLocation OldLocation;
3653   std::tie(PrevDiag, OldLocation)
3654     = getNoteDiagForInvalidRedeclaration(Old, New);
3655   S.Diag(OldLocation, PrevDiag);
3656   New->setInvalidDecl();
3657 }
3658 
3659 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3660 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3661 /// emitting diagnostics as appropriate.
3662 ///
3663 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3664 /// to here in AddInitializerToDecl. We can't check them before the initializer
3665 /// is attached.
3666 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3667                              bool MergeTypeWithOld) {
3668   if (New->isInvalidDecl() || Old->isInvalidDecl())
3669     return;
3670 
3671   QualType MergedT;
3672   if (getLangOpts().CPlusPlus) {
3673     if (New->getType()->isUndeducedType()) {
3674       // We don't know what the new type is until the initializer is attached.
3675       return;
3676     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3677       // These could still be something that needs exception specs checked.
3678       return MergeVarDeclExceptionSpecs(New, Old);
3679     }
3680     // C++ [basic.link]p10:
3681     //   [...] the types specified by all declarations referring to a given
3682     //   object or function shall be identical, except that declarations for an
3683     //   array object can specify array types that differ by the presence or
3684     //   absence of a major array bound (8.3.4).
3685     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3686       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3687       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3688 
3689       // We are merging a variable declaration New into Old. If it has an array
3690       // bound, and that bound differs from Old's bound, we should diagnose the
3691       // mismatch.
3692       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3693         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3694              PrevVD = PrevVD->getPreviousDecl()) {
3695           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3696           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3697             continue;
3698 
3699           if (!Context.hasSameType(NewArray, PrevVDTy))
3700             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3701         }
3702       }
3703 
3704       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3705         if (Context.hasSameType(OldArray->getElementType(),
3706                                 NewArray->getElementType()))
3707           MergedT = New->getType();
3708       }
3709       // FIXME: Check visibility. New is hidden but has a complete type. If New
3710       // has no array bound, it should not inherit one from Old, if Old is not
3711       // visible.
3712       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3713         if (Context.hasSameType(OldArray->getElementType(),
3714                                 NewArray->getElementType()))
3715           MergedT = Old->getType();
3716       }
3717     }
3718     else if (New->getType()->isObjCObjectPointerType() &&
3719                Old->getType()->isObjCObjectPointerType()) {
3720       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3721                                               Old->getType());
3722     }
3723   } else {
3724     // C 6.2.7p2:
3725     //   All declarations that refer to the same object or function shall have
3726     //   compatible type.
3727     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3728   }
3729   if (MergedT.isNull()) {
3730     // It's OK if we couldn't merge types if either type is dependent, for a
3731     // block-scope variable. In other cases (static data members of class
3732     // templates, variable templates, ...), we require the types to be
3733     // equivalent.
3734     // FIXME: The C++ standard doesn't say anything about this.
3735     if ((New->getType()->isDependentType() ||
3736          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3737       // If the old type was dependent, we can't merge with it, so the new type
3738       // becomes dependent for now. We'll reproduce the original type when we
3739       // instantiate the TypeSourceInfo for the variable.
3740       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3741         New->setType(Context.DependentTy);
3742       return;
3743     }
3744     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3745   }
3746 
3747   // Don't actually update the type on the new declaration if the old
3748   // declaration was an extern declaration in a different scope.
3749   if (MergeTypeWithOld)
3750     New->setType(MergedT);
3751 }
3752 
3753 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3754                                   LookupResult &Previous) {
3755   // C11 6.2.7p4:
3756   //   For an identifier with internal or external linkage declared
3757   //   in a scope in which a prior declaration of that identifier is
3758   //   visible, if the prior declaration specifies internal or
3759   //   external linkage, the type of the identifier at the later
3760   //   declaration becomes the composite type.
3761   //
3762   // If the variable isn't visible, we do not merge with its type.
3763   if (Previous.isShadowed())
3764     return false;
3765 
3766   if (S.getLangOpts().CPlusPlus) {
3767     // C++11 [dcl.array]p3:
3768     //   If there is a preceding declaration of the entity in the same
3769     //   scope in which the bound was specified, an omitted array bound
3770     //   is taken to be the same as in that earlier declaration.
3771     return NewVD->isPreviousDeclInSameBlockScope() ||
3772            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3773             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3774   } else {
3775     // If the old declaration was function-local, don't merge with its
3776     // type unless we're in the same function.
3777     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3778            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3779   }
3780 }
3781 
3782 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3783 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3784 /// situation, merging decls or emitting diagnostics as appropriate.
3785 ///
3786 /// Tentative definition rules (C99 6.9.2p2) are checked by
3787 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3788 /// definitions here, since the initializer hasn't been attached.
3789 ///
3790 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3791   // If the new decl is already invalid, don't do any other checking.
3792   if (New->isInvalidDecl())
3793     return;
3794 
3795   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3796     return;
3797 
3798   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3799 
3800   // Verify the old decl was also a variable or variable template.
3801   VarDecl *Old = nullptr;
3802   VarTemplateDecl *OldTemplate = nullptr;
3803   if (Previous.isSingleResult()) {
3804     if (NewTemplate) {
3805       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3806       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3807 
3808       if (auto *Shadow =
3809               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3810         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3811           return New->setInvalidDecl();
3812     } else {
3813       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3814 
3815       if (auto *Shadow =
3816               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3817         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3818           return New->setInvalidDecl();
3819     }
3820   }
3821   if (!Old) {
3822     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3823         << New->getDeclName();
3824     notePreviousDefinition(Previous.getRepresentativeDecl(),
3825                            New->getLocation());
3826     return New->setInvalidDecl();
3827   }
3828 
3829   // Ensure the template parameters are compatible.
3830   if (NewTemplate &&
3831       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3832                                       OldTemplate->getTemplateParameters(),
3833                                       /*Complain=*/true, TPL_TemplateMatch))
3834     return New->setInvalidDecl();
3835 
3836   // C++ [class.mem]p1:
3837   //   A member shall not be declared twice in the member-specification [...]
3838   //
3839   // Here, we need only consider static data members.
3840   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3841     Diag(New->getLocation(), diag::err_duplicate_member)
3842       << New->getIdentifier();
3843     Diag(Old->getLocation(), diag::note_previous_declaration);
3844     New->setInvalidDecl();
3845   }
3846 
3847   mergeDeclAttributes(New, Old);
3848   // Warn if an already-declared variable is made a weak_import in a subsequent
3849   // declaration
3850   if (New->hasAttr<WeakImportAttr>() &&
3851       Old->getStorageClass() == SC_None &&
3852       !Old->hasAttr<WeakImportAttr>()) {
3853     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3854     notePreviousDefinition(Old, New->getLocation());
3855     // Remove weak_import attribute on new declaration.
3856     New->dropAttr<WeakImportAttr>();
3857   }
3858 
3859   if (New->hasAttr<InternalLinkageAttr>() &&
3860       !Old->hasAttr<InternalLinkageAttr>()) {
3861     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3862         << New->getDeclName();
3863     notePreviousDefinition(Old, New->getLocation());
3864     New->dropAttr<InternalLinkageAttr>();
3865   }
3866 
3867   // Merge the types.
3868   VarDecl *MostRecent = Old->getMostRecentDecl();
3869   if (MostRecent != Old) {
3870     MergeVarDeclTypes(New, MostRecent,
3871                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3872     if (New->isInvalidDecl())
3873       return;
3874   }
3875 
3876   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3877   if (New->isInvalidDecl())
3878     return;
3879 
3880   diag::kind PrevDiag;
3881   SourceLocation OldLocation;
3882   std::tie(PrevDiag, OldLocation) =
3883       getNoteDiagForInvalidRedeclaration(Old, New);
3884 
3885   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3886   if (New->getStorageClass() == SC_Static &&
3887       !New->isStaticDataMember() &&
3888       Old->hasExternalFormalLinkage()) {
3889     if (getLangOpts().MicrosoftExt) {
3890       Diag(New->getLocation(), diag::ext_static_non_static)
3891           << New->getDeclName();
3892       Diag(OldLocation, PrevDiag);
3893     } else {
3894       Diag(New->getLocation(), diag::err_static_non_static)
3895           << New->getDeclName();
3896       Diag(OldLocation, PrevDiag);
3897       return New->setInvalidDecl();
3898     }
3899   }
3900   // C99 6.2.2p4:
3901   //   For an identifier declared with the storage-class specifier
3902   //   extern in a scope in which a prior declaration of that
3903   //   identifier is visible,23) if the prior declaration specifies
3904   //   internal or external linkage, the linkage of the identifier at
3905   //   the later declaration is the same as the linkage specified at
3906   //   the prior declaration. If no prior declaration is visible, or
3907   //   if the prior declaration specifies no linkage, then the
3908   //   identifier has external linkage.
3909   if (New->hasExternalStorage() && Old->hasLinkage())
3910     /* Okay */;
3911   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3912            !New->isStaticDataMember() &&
3913            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3914     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3915     Diag(OldLocation, PrevDiag);
3916     return New->setInvalidDecl();
3917   }
3918 
3919   // Check if extern is followed by non-extern and vice-versa.
3920   if (New->hasExternalStorage() &&
3921       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3922     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3923     Diag(OldLocation, PrevDiag);
3924     return New->setInvalidDecl();
3925   }
3926   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3927       !New->hasExternalStorage()) {
3928     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3929     Diag(OldLocation, PrevDiag);
3930     return New->setInvalidDecl();
3931   }
3932 
3933   if (CheckRedeclarationModuleOwnership(New, Old))
3934     return;
3935 
3936   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3937 
3938   // FIXME: The test for external storage here seems wrong? We still
3939   // need to check for mismatches.
3940   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3941       // Don't complain about out-of-line definitions of static members.
3942       !(Old->getLexicalDeclContext()->isRecord() &&
3943         !New->getLexicalDeclContext()->isRecord())) {
3944     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3945     Diag(OldLocation, PrevDiag);
3946     return New->setInvalidDecl();
3947   }
3948 
3949   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3950     if (VarDecl *Def = Old->getDefinition()) {
3951       // C++1z [dcl.fcn.spec]p4:
3952       //   If the definition of a variable appears in a translation unit before
3953       //   its first declaration as inline, the program is ill-formed.
3954       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3955       Diag(Def->getLocation(), diag::note_previous_definition);
3956     }
3957   }
3958 
3959   // If this redeclaration makes the variable inline, we may need to add it to
3960   // UndefinedButUsed.
3961   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3962       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3963     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3964                                            SourceLocation()));
3965 
3966   if (New->getTLSKind() != Old->getTLSKind()) {
3967     if (!Old->getTLSKind()) {
3968       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3969       Diag(OldLocation, PrevDiag);
3970     } else if (!New->getTLSKind()) {
3971       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3972       Diag(OldLocation, PrevDiag);
3973     } else {
3974       // Do not allow redeclaration to change the variable between requiring
3975       // static and dynamic initialization.
3976       // FIXME: GCC allows this, but uses the TLS keyword on the first
3977       // declaration to determine the kind. Do we need to be compatible here?
3978       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3979         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3980       Diag(OldLocation, PrevDiag);
3981     }
3982   }
3983 
3984   // C++ doesn't have tentative definitions, so go right ahead and check here.
3985   if (getLangOpts().CPlusPlus &&
3986       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3987     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3988         Old->getCanonicalDecl()->isConstexpr()) {
3989       // This definition won't be a definition any more once it's been merged.
3990       Diag(New->getLocation(),
3991            diag::warn_deprecated_redundant_constexpr_static_def);
3992     } else if (VarDecl *Def = Old->getDefinition()) {
3993       if (checkVarDeclRedefinition(Def, New))
3994         return;
3995     }
3996   }
3997 
3998   if (haveIncompatibleLanguageLinkages(Old, New)) {
3999     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4000     Diag(OldLocation, PrevDiag);
4001     New->setInvalidDecl();
4002     return;
4003   }
4004 
4005   // Merge "used" flag.
4006   if (Old->getMostRecentDecl()->isUsed(false))
4007     New->setIsUsed();
4008 
4009   // Keep a chain of previous declarations.
4010   New->setPreviousDecl(Old);
4011   if (NewTemplate)
4012     NewTemplate->setPreviousDecl(OldTemplate);
4013   adjustDeclContextForDeclaratorDecl(New, Old);
4014 
4015   // Inherit access appropriately.
4016   New->setAccess(Old->getAccess());
4017   if (NewTemplate)
4018     NewTemplate->setAccess(New->getAccess());
4019 
4020   if (Old->isInline())
4021     New->setImplicitlyInline();
4022 }
4023 
4024 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4025   SourceManager &SrcMgr = getSourceManager();
4026   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4027   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4028   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4029   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4030   auto &HSI = PP.getHeaderSearchInfo();
4031   StringRef HdrFilename =
4032       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4033 
4034   auto noteFromModuleOrInclude = [&](Module *Mod,
4035                                      SourceLocation IncLoc) -> bool {
4036     // Redefinition errors with modules are common with non modular mapped
4037     // headers, example: a non-modular header H in module A that also gets
4038     // included directly in a TU. Pointing twice to the same header/definition
4039     // is confusing, try to get better diagnostics when modules is on.
4040     if (IncLoc.isValid()) {
4041       if (Mod) {
4042         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4043             << HdrFilename.str() << Mod->getFullModuleName();
4044         if (!Mod->DefinitionLoc.isInvalid())
4045           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4046               << Mod->getFullModuleName();
4047       } else {
4048         Diag(IncLoc, diag::note_redefinition_include_same_file)
4049             << HdrFilename.str();
4050       }
4051       return true;
4052     }
4053 
4054     return false;
4055   };
4056 
4057   // Is it the same file and same offset? Provide more information on why
4058   // this leads to a redefinition error.
4059   bool EmittedDiag = false;
4060   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4061     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4062     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4063     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4064     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4065 
4066     // If the header has no guards, emit a note suggesting one.
4067     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4068       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4069 
4070     if (EmittedDiag)
4071       return;
4072   }
4073 
4074   // Redefinition coming from different files or couldn't do better above.
4075   if (Old->getLocation().isValid())
4076     Diag(Old->getLocation(), diag::note_previous_definition);
4077 }
4078 
4079 /// We've just determined that \p Old and \p New both appear to be definitions
4080 /// of the same variable. Either diagnose or fix the problem.
4081 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4082   if (!hasVisibleDefinition(Old) &&
4083       (New->getFormalLinkage() == InternalLinkage ||
4084        New->isInline() ||
4085        New->getDescribedVarTemplate() ||
4086        New->getNumTemplateParameterLists() ||
4087        New->getDeclContext()->isDependentContext())) {
4088     // The previous definition is hidden, and multiple definitions are
4089     // permitted (in separate TUs). Demote this to a declaration.
4090     New->demoteThisDefinitionToDeclaration();
4091 
4092     // Make the canonical definition visible.
4093     if (auto *OldTD = Old->getDescribedVarTemplate())
4094       makeMergedDefinitionVisible(OldTD);
4095     makeMergedDefinitionVisible(Old);
4096     return false;
4097   } else {
4098     Diag(New->getLocation(), diag::err_redefinition) << New;
4099     notePreviousDefinition(Old, New->getLocation());
4100     New->setInvalidDecl();
4101     return true;
4102   }
4103 }
4104 
4105 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4106 /// no declarator (e.g. "struct foo;") is parsed.
4107 Decl *
4108 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4109                                  RecordDecl *&AnonRecord) {
4110   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4111                                     AnonRecord);
4112 }
4113 
4114 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4115 // disambiguate entities defined in different scopes.
4116 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4117 // compatibility.
4118 // We will pick our mangling number depending on which version of MSVC is being
4119 // targeted.
4120 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4121   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4122              ? S->getMSCurManglingNumber()
4123              : S->getMSLastManglingNumber();
4124 }
4125 
4126 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4127   if (!Context.getLangOpts().CPlusPlus)
4128     return;
4129 
4130   if (isa<CXXRecordDecl>(Tag->getParent())) {
4131     // If this tag is the direct child of a class, number it if
4132     // it is anonymous.
4133     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4134       return;
4135     MangleNumberingContext &MCtx =
4136         Context.getManglingNumberContext(Tag->getParent());
4137     Context.setManglingNumber(
4138         Tag, MCtx.getManglingNumber(
4139                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4140     return;
4141   }
4142 
4143   // If this tag isn't a direct child of a class, number it if it is local.
4144   Decl *ManglingContextDecl;
4145   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4146           Tag->getDeclContext(), ManglingContextDecl)) {
4147     Context.setManglingNumber(
4148         Tag, MCtx->getManglingNumber(
4149                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4150   }
4151 }
4152 
4153 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4154                                         TypedefNameDecl *NewTD) {
4155   if (TagFromDeclSpec->isInvalidDecl())
4156     return;
4157 
4158   // Do nothing if the tag already has a name for linkage purposes.
4159   if (TagFromDeclSpec->hasNameForLinkage())
4160     return;
4161 
4162   // A well-formed anonymous tag must always be a TUK_Definition.
4163   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4164 
4165   // The type must match the tag exactly;  no qualifiers allowed.
4166   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4167                            Context.getTagDeclType(TagFromDeclSpec))) {
4168     if (getLangOpts().CPlusPlus)
4169       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4170     return;
4171   }
4172 
4173   // If we've already computed linkage for the anonymous tag, then
4174   // adding a typedef name for the anonymous decl can change that
4175   // linkage, which might be a serious problem.  Diagnose this as
4176   // unsupported and ignore the typedef name.  TODO: we should
4177   // pursue this as a language defect and establish a formal rule
4178   // for how to handle it.
4179   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4180     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4181 
4182     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4183     tagLoc = getLocForEndOfToken(tagLoc);
4184 
4185     llvm::SmallString<40> textToInsert;
4186     textToInsert += ' ';
4187     textToInsert += NewTD->getIdentifier()->getName();
4188     Diag(tagLoc, diag::note_typedef_changes_linkage)
4189         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4190     return;
4191   }
4192 
4193   // Otherwise, set this is the anon-decl typedef for the tag.
4194   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4195 }
4196 
4197 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4198   switch (T) {
4199   case DeclSpec::TST_class:
4200     return 0;
4201   case DeclSpec::TST_struct:
4202     return 1;
4203   case DeclSpec::TST_interface:
4204     return 2;
4205   case DeclSpec::TST_union:
4206     return 3;
4207   case DeclSpec::TST_enum:
4208     return 4;
4209   default:
4210     llvm_unreachable("unexpected type specifier");
4211   }
4212 }
4213 
4214 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4215 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4216 /// parameters to cope with template friend declarations.
4217 Decl *
4218 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4219                                  MultiTemplateParamsArg TemplateParams,
4220                                  bool IsExplicitInstantiation,
4221                                  RecordDecl *&AnonRecord) {
4222   Decl *TagD = nullptr;
4223   TagDecl *Tag = nullptr;
4224   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4225       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4226       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4227       DS.getTypeSpecType() == DeclSpec::TST_union ||
4228       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4229     TagD = DS.getRepAsDecl();
4230 
4231     if (!TagD) // We probably had an error
4232       return nullptr;
4233 
4234     // Note that the above type specs guarantee that the
4235     // type rep is a Decl, whereas in many of the others
4236     // it's a Type.
4237     if (isa<TagDecl>(TagD))
4238       Tag = cast<TagDecl>(TagD);
4239     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4240       Tag = CTD->getTemplatedDecl();
4241   }
4242 
4243   if (Tag) {
4244     handleTagNumbering(Tag, S);
4245     Tag->setFreeStanding();
4246     if (Tag->isInvalidDecl())
4247       return Tag;
4248   }
4249 
4250   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4251     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4252     // or incomplete types shall not be restrict-qualified."
4253     if (TypeQuals & DeclSpec::TQ_restrict)
4254       Diag(DS.getRestrictSpecLoc(),
4255            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4256            << DS.getSourceRange();
4257   }
4258 
4259   if (DS.isInlineSpecified())
4260     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4261         << getLangOpts().CPlusPlus17;
4262 
4263   if (DS.isConstexprSpecified()) {
4264     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4265     // and definitions of functions and variables.
4266     if (Tag)
4267       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4268           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4269     else
4270       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4271     // Don't emit warnings after this error.
4272     return TagD;
4273   }
4274 
4275   DiagnoseFunctionSpecifiers(DS);
4276 
4277   if (DS.isFriendSpecified()) {
4278     // If we're dealing with a decl but not a TagDecl, assume that
4279     // whatever routines created it handled the friendship aspect.
4280     if (TagD && !Tag)
4281       return nullptr;
4282     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4283   }
4284 
4285   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4286   bool IsExplicitSpecialization =
4287     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4288   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4289       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4290       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4291     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4292     // nested-name-specifier unless it is an explicit instantiation
4293     // or an explicit specialization.
4294     //
4295     // FIXME: We allow class template partial specializations here too, per the
4296     // obvious intent of DR1819.
4297     //
4298     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4299     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4300         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4301     return nullptr;
4302   }
4303 
4304   // Track whether this decl-specifier declares anything.
4305   bool DeclaresAnything = true;
4306 
4307   // Handle anonymous struct definitions.
4308   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4309     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4310         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4311       if (getLangOpts().CPlusPlus ||
4312           Record->getDeclContext()->isRecord()) {
4313         // If CurContext is a DeclContext that can contain statements,
4314         // RecursiveASTVisitor won't visit the decls that
4315         // BuildAnonymousStructOrUnion() will put into CurContext.
4316         // Also store them here so that they can be part of the
4317         // DeclStmt that gets created in this case.
4318         // FIXME: Also return the IndirectFieldDecls created by
4319         // BuildAnonymousStructOr union, for the same reason?
4320         if (CurContext->isFunctionOrMethod())
4321           AnonRecord = Record;
4322         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4323                                            Context.getPrintingPolicy());
4324       }
4325 
4326       DeclaresAnything = false;
4327     }
4328   }
4329 
4330   // C11 6.7.2.1p2:
4331   //   A struct-declaration that does not declare an anonymous structure or
4332   //   anonymous union shall contain a struct-declarator-list.
4333   //
4334   // This rule also existed in C89 and C99; the grammar for struct-declaration
4335   // did not permit a struct-declaration without a struct-declarator-list.
4336   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4337       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4338     // Check for Microsoft C extension: anonymous struct/union member.
4339     // Handle 2 kinds of anonymous struct/union:
4340     //   struct STRUCT;
4341     //   union UNION;
4342     // and
4343     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4344     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4345     if ((Tag && Tag->getDeclName()) ||
4346         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4347       RecordDecl *Record = nullptr;
4348       if (Tag)
4349         Record = dyn_cast<RecordDecl>(Tag);
4350       else if (const RecordType *RT =
4351                    DS.getRepAsType().get()->getAsStructureType())
4352         Record = RT->getDecl();
4353       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4354         Record = UT->getDecl();
4355 
4356       if (Record && getLangOpts().MicrosoftExt) {
4357         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4358             << Record->isUnion() << DS.getSourceRange();
4359         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4360       }
4361 
4362       DeclaresAnything = false;
4363     }
4364   }
4365 
4366   // Skip all the checks below if we have a type error.
4367   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4368       (TagD && TagD->isInvalidDecl()))
4369     return TagD;
4370 
4371   if (getLangOpts().CPlusPlus &&
4372       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4373     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4374       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4375           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4376         DeclaresAnything = false;
4377 
4378   if (!DS.isMissingDeclaratorOk()) {
4379     // Customize diagnostic for a typedef missing a name.
4380     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4381       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4382           << DS.getSourceRange();
4383     else
4384       DeclaresAnything = false;
4385   }
4386 
4387   if (DS.isModulePrivateSpecified() &&
4388       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4389     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4390       << Tag->getTagKind()
4391       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4392 
4393   ActOnDocumentableDecl(TagD);
4394 
4395   // C 6.7/2:
4396   //   A declaration [...] shall declare at least a declarator [...], a tag,
4397   //   or the members of an enumeration.
4398   // C++ [dcl.dcl]p3:
4399   //   [If there are no declarators], and except for the declaration of an
4400   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4401   //   names into the program, or shall redeclare a name introduced by a
4402   //   previous declaration.
4403   if (!DeclaresAnything) {
4404     // In C, we allow this as a (popular) extension / bug. Don't bother
4405     // producing further diagnostics for redundant qualifiers after this.
4406     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4407     return TagD;
4408   }
4409 
4410   // C++ [dcl.stc]p1:
4411   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4412   //   init-declarator-list of the declaration shall not be empty.
4413   // C++ [dcl.fct.spec]p1:
4414   //   If a cv-qualifier appears in a decl-specifier-seq, the
4415   //   init-declarator-list of the declaration shall not be empty.
4416   //
4417   // Spurious qualifiers here appear to be valid in C.
4418   unsigned DiagID = diag::warn_standalone_specifier;
4419   if (getLangOpts().CPlusPlus)
4420     DiagID = diag::ext_standalone_specifier;
4421 
4422   // Note that a linkage-specification sets a storage class, but
4423   // 'extern "C" struct foo;' is actually valid and not theoretically
4424   // useless.
4425   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4426     if (SCS == DeclSpec::SCS_mutable)
4427       // Since mutable is not a viable storage class specifier in C, there is
4428       // no reason to treat it as an extension. Instead, diagnose as an error.
4429       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4430     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4431       Diag(DS.getStorageClassSpecLoc(), DiagID)
4432         << DeclSpec::getSpecifierName(SCS);
4433   }
4434 
4435   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4436     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4437       << DeclSpec::getSpecifierName(TSCS);
4438   if (DS.getTypeQualifiers()) {
4439     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4440       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4441     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4442       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4443     // Restrict is covered above.
4444     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4445       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4446     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4447       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4448   }
4449 
4450   // Warn about ignored type attributes, for example:
4451   // __attribute__((aligned)) struct A;
4452   // Attributes should be placed after tag to apply to type declaration.
4453   if (!DS.getAttributes().empty()) {
4454     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4455     if (TypeSpecType == DeclSpec::TST_class ||
4456         TypeSpecType == DeclSpec::TST_struct ||
4457         TypeSpecType == DeclSpec::TST_interface ||
4458         TypeSpecType == DeclSpec::TST_union ||
4459         TypeSpecType == DeclSpec::TST_enum) {
4460       for (const ParsedAttr &AL : DS.getAttributes())
4461         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4462             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4463     }
4464   }
4465 
4466   return TagD;
4467 }
4468 
4469 /// We are trying to inject an anonymous member into the given scope;
4470 /// check if there's an existing declaration that can't be overloaded.
4471 ///
4472 /// \return true if this is a forbidden redeclaration
4473 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4474                                          Scope *S,
4475                                          DeclContext *Owner,
4476                                          DeclarationName Name,
4477                                          SourceLocation NameLoc,
4478                                          bool IsUnion) {
4479   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4480                  Sema::ForVisibleRedeclaration);
4481   if (!SemaRef.LookupName(R, S)) return false;
4482 
4483   // Pick a representative declaration.
4484   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4485   assert(PrevDecl && "Expected a non-null Decl");
4486 
4487   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4488     return false;
4489 
4490   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4491     << IsUnion << Name;
4492   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4493 
4494   return true;
4495 }
4496 
4497 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4498 /// anonymous struct or union AnonRecord into the owning context Owner
4499 /// and scope S. This routine will be invoked just after we realize
4500 /// that an unnamed union or struct is actually an anonymous union or
4501 /// struct, e.g.,
4502 ///
4503 /// @code
4504 /// union {
4505 ///   int i;
4506 ///   float f;
4507 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4508 ///    // f into the surrounding scope.x
4509 /// @endcode
4510 ///
4511 /// This routine is recursive, injecting the names of nested anonymous
4512 /// structs/unions into the owning context and scope as well.
4513 static bool
4514 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4515                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4516                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4517   bool Invalid = false;
4518 
4519   // Look every FieldDecl and IndirectFieldDecl with a name.
4520   for (auto *D : AnonRecord->decls()) {
4521     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4522         cast<NamedDecl>(D)->getDeclName()) {
4523       ValueDecl *VD = cast<ValueDecl>(D);
4524       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4525                                        VD->getLocation(),
4526                                        AnonRecord->isUnion())) {
4527         // C++ [class.union]p2:
4528         //   The names of the members of an anonymous union shall be
4529         //   distinct from the names of any other entity in the
4530         //   scope in which the anonymous union is declared.
4531         Invalid = true;
4532       } else {
4533         // C++ [class.union]p2:
4534         //   For the purpose of name lookup, after the anonymous union
4535         //   definition, the members of the anonymous union are
4536         //   considered to have been defined in the scope in which the
4537         //   anonymous union is declared.
4538         unsigned OldChainingSize = Chaining.size();
4539         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4540           Chaining.append(IF->chain_begin(), IF->chain_end());
4541         else
4542           Chaining.push_back(VD);
4543 
4544         assert(Chaining.size() >= 2);
4545         NamedDecl **NamedChain =
4546           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4547         for (unsigned i = 0; i < Chaining.size(); i++)
4548           NamedChain[i] = Chaining[i];
4549 
4550         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4551             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4552             VD->getType(), {NamedChain, Chaining.size()});
4553 
4554         for (const auto *Attr : VD->attrs())
4555           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4556 
4557         IndirectField->setAccess(AS);
4558         IndirectField->setImplicit();
4559         SemaRef.PushOnScopeChains(IndirectField, S);
4560 
4561         // That includes picking up the appropriate access specifier.
4562         if (AS != AS_none) IndirectField->setAccess(AS);
4563 
4564         Chaining.resize(OldChainingSize);
4565       }
4566     }
4567   }
4568 
4569   return Invalid;
4570 }
4571 
4572 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4573 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4574 /// illegal input values are mapped to SC_None.
4575 static StorageClass
4576 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4577   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4578   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4579          "Parser allowed 'typedef' as storage class VarDecl.");
4580   switch (StorageClassSpec) {
4581   case DeclSpec::SCS_unspecified:    return SC_None;
4582   case DeclSpec::SCS_extern:
4583     if (DS.isExternInLinkageSpec())
4584       return SC_None;
4585     return SC_Extern;
4586   case DeclSpec::SCS_static:         return SC_Static;
4587   case DeclSpec::SCS_auto:           return SC_Auto;
4588   case DeclSpec::SCS_register:       return SC_Register;
4589   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4590     // Illegal SCSs map to None: error reporting is up to the caller.
4591   case DeclSpec::SCS_mutable:        // Fall through.
4592   case DeclSpec::SCS_typedef:        return SC_None;
4593   }
4594   llvm_unreachable("unknown storage class specifier");
4595 }
4596 
4597 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4598   assert(Record->hasInClassInitializer());
4599 
4600   for (const auto *I : Record->decls()) {
4601     const auto *FD = dyn_cast<FieldDecl>(I);
4602     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4603       FD = IFD->getAnonField();
4604     if (FD && FD->hasInClassInitializer())
4605       return FD->getLocation();
4606   }
4607 
4608   llvm_unreachable("couldn't find in-class initializer");
4609 }
4610 
4611 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4612                                       SourceLocation DefaultInitLoc) {
4613   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4614     return;
4615 
4616   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4617   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4618 }
4619 
4620 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4621                                       CXXRecordDecl *AnonUnion) {
4622   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4623     return;
4624 
4625   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4626 }
4627 
4628 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4629 /// anonymous structure or union. Anonymous unions are a C++ feature
4630 /// (C++ [class.union]) and a C11 feature; anonymous structures
4631 /// are a C11 feature and GNU C++ extension.
4632 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4633                                         AccessSpecifier AS,
4634                                         RecordDecl *Record,
4635                                         const PrintingPolicy &Policy) {
4636   DeclContext *Owner = Record->getDeclContext();
4637 
4638   // Diagnose whether this anonymous struct/union is an extension.
4639   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4640     Diag(Record->getLocation(), diag::ext_anonymous_union);
4641   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4642     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4643   else if (!Record->isUnion() && !getLangOpts().C11)
4644     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4645 
4646   // C and C++ require different kinds of checks for anonymous
4647   // structs/unions.
4648   bool Invalid = false;
4649   if (getLangOpts().CPlusPlus) {
4650     const char *PrevSpec = nullptr;
4651     unsigned DiagID;
4652     if (Record->isUnion()) {
4653       // C++ [class.union]p6:
4654       // C++17 [class.union.anon]p2:
4655       //   Anonymous unions declared in a named namespace or in the
4656       //   global namespace shall be declared static.
4657       DeclContext *OwnerScope = Owner->getRedeclContext();
4658       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4659           (OwnerScope->isTranslationUnit() ||
4660            (OwnerScope->isNamespace() &&
4661             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4662         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4663           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4664 
4665         // Recover by adding 'static'.
4666         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4667                                PrevSpec, DiagID, Policy);
4668       }
4669       // C++ [class.union]p6:
4670       //   A storage class is not allowed in a declaration of an
4671       //   anonymous union in a class scope.
4672       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4673                isa<RecordDecl>(Owner)) {
4674         Diag(DS.getStorageClassSpecLoc(),
4675              diag::err_anonymous_union_with_storage_spec)
4676           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4677 
4678         // Recover by removing the storage specifier.
4679         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4680                                SourceLocation(),
4681                                PrevSpec, DiagID, Context.getPrintingPolicy());
4682       }
4683     }
4684 
4685     // Ignore const/volatile/restrict qualifiers.
4686     if (DS.getTypeQualifiers()) {
4687       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4688         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4689           << Record->isUnion() << "const"
4690           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4691       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4692         Diag(DS.getVolatileSpecLoc(),
4693              diag::ext_anonymous_struct_union_qualified)
4694           << Record->isUnion() << "volatile"
4695           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4696       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4697         Diag(DS.getRestrictSpecLoc(),
4698              diag::ext_anonymous_struct_union_qualified)
4699           << Record->isUnion() << "restrict"
4700           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4701       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4702         Diag(DS.getAtomicSpecLoc(),
4703              diag::ext_anonymous_struct_union_qualified)
4704           << Record->isUnion() << "_Atomic"
4705           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4706       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4707         Diag(DS.getUnalignedSpecLoc(),
4708              diag::ext_anonymous_struct_union_qualified)
4709           << Record->isUnion() << "__unaligned"
4710           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4711 
4712       DS.ClearTypeQualifiers();
4713     }
4714 
4715     // C++ [class.union]p2:
4716     //   The member-specification of an anonymous union shall only
4717     //   define non-static data members. [Note: nested types and
4718     //   functions cannot be declared within an anonymous union. ]
4719     for (auto *Mem : Record->decls()) {
4720       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4721         // C++ [class.union]p3:
4722         //   An anonymous union shall not have private or protected
4723         //   members (clause 11).
4724         assert(FD->getAccess() != AS_none);
4725         if (FD->getAccess() != AS_public) {
4726           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4727             << Record->isUnion() << (FD->getAccess() == AS_protected);
4728           Invalid = true;
4729         }
4730 
4731         // C++ [class.union]p1
4732         //   An object of a class with a non-trivial constructor, a non-trivial
4733         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4734         //   assignment operator cannot be a member of a union, nor can an
4735         //   array of such objects.
4736         if (CheckNontrivialField(FD))
4737           Invalid = true;
4738       } else if (Mem->isImplicit()) {
4739         // Any implicit members are fine.
4740       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4741         // This is a type that showed up in an
4742         // elaborated-type-specifier inside the anonymous struct or
4743         // union, but which actually declares a type outside of the
4744         // anonymous struct or union. It's okay.
4745       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4746         if (!MemRecord->isAnonymousStructOrUnion() &&
4747             MemRecord->getDeclName()) {
4748           // Visual C++ allows type definition in anonymous struct or union.
4749           if (getLangOpts().MicrosoftExt)
4750             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4751               << Record->isUnion();
4752           else {
4753             // This is a nested type declaration.
4754             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4755               << Record->isUnion();
4756             Invalid = true;
4757           }
4758         } else {
4759           // This is an anonymous type definition within another anonymous type.
4760           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4761           // not part of standard C++.
4762           Diag(MemRecord->getLocation(),
4763                diag::ext_anonymous_record_with_anonymous_type)
4764             << Record->isUnion();
4765         }
4766       } else if (isa<AccessSpecDecl>(Mem)) {
4767         // Any access specifier is fine.
4768       } else if (isa<StaticAssertDecl>(Mem)) {
4769         // In C++1z, static_assert declarations are also fine.
4770       } else {
4771         // We have something that isn't a non-static data
4772         // member. Complain about it.
4773         unsigned DK = diag::err_anonymous_record_bad_member;
4774         if (isa<TypeDecl>(Mem))
4775           DK = diag::err_anonymous_record_with_type;
4776         else if (isa<FunctionDecl>(Mem))
4777           DK = diag::err_anonymous_record_with_function;
4778         else if (isa<VarDecl>(Mem))
4779           DK = diag::err_anonymous_record_with_static;
4780 
4781         // Visual C++ allows type definition in anonymous struct or union.
4782         if (getLangOpts().MicrosoftExt &&
4783             DK == diag::err_anonymous_record_with_type)
4784           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4785             << Record->isUnion();
4786         else {
4787           Diag(Mem->getLocation(), DK) << Record->isUnion();
4788           Invalid = true;
4789         }
4790       }
4791     }
4792 
4793     // C++11 [class.union]p8 (DR1460):
4794     //   At most one variant member of a union may have a
4795     //   brace-or-equal-initializer.
4796     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4797         Owner->isRecord())
4798       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4799                                 cast<CXXRecordDecl>(Record));
4800   }
4801 
4802   if (!Record->isUnion() && !Owner->isRecord()) {
4803     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4804       << getLangOpts().CPlusPlus;
4805     Invalid = true;
4806   }
4807 
4808   // Mock up a declarator.
4809   Declarator Dc(DS, DeclaratorContext::MemberContext);
4810   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4811   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4812 
4813   // Create a declaration for this anonymous struct/union.
4814   NamedDecl *Anon = nullptr;
4815   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4816     Anon = FieldDecl::Create(
4817         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4818         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4819         /*BitWidth=*/nullptr, /*Mutable=*/false,
4820         /*InitStyle=*/ICIS_NoInit);
4821     Anon->setAccess(AS);
4822     if (getLangOpts().CPlusPlus)
4823       FieldCollector->Add(cast<FieldDecl>(Anon));
4824   } else {
4825     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4826     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4827     if (SCSpec == DeclSpec::SCS_mutable) {
4828       // mutable can only appear on non-static class members, so it's always
4829       // an error here
4830       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4831       Invalid = true;
4832       SC = SC_None;
4833     }
4834 
4835     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4836                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4837                            Context.getTypeDeclType(Record), TInfo, SC);
4838 
4839     // Default-initialize the implicit variable. This initialization will be
4840     // trivial in almost all cases, except if a union member has an in-class
4841     // initializer:
4842     //   union { int n = 0; };
4843     ActOnUninitializedDecl(Anon);
4844   }
4845   Anon->setImplicit();
4846 
4847   // Mark this as an anonymous struct/union type.
4848   Record->setAnonymousStructOrUnion(true);
4849 
4850   // Add the anonymous struct/union object to the current
4851   // context. We'll be referencing this object when we refer to one of
4852   // its members.
4853   Owner->addDecl(Anon);
4854 
4855   // Inject the members of the anonymous struct/union into the owning
4856   // context and into the identifier resolver chain for name lookup
4857   // purposes.
4858   SmallVector<NamedDecl*, 2> Chain;
4859   Chain.push_back(Anon);
4860 
4861   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4862     Invalid = true;
4863 
4864   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4865     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4866       Decl *ManglingContextDecl;
4867       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4868               NewVD->getDeclContext(), ManglingContextDecl)) {
4869         Context.setManglingNumber(
4870             NewVD, MCtx->getManglingNumber(
4871                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4872         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4873       }
4874     }
4875   }
4876 
4877   if (Invalid)
4878     Anon->setInvalidDecl();
4879 
4880   return Anon;
4881 }
4882 
4883 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4884 /// Microsoft C anonymous structure.
4885 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4886 /// Example:
4887 ///
4888 /// struct A { int a; };
4889 /// struct B { struct A; int b; };
4890 ///
4891 /// void foo() {
4892 ///   B var;
4893 ///   var.a = 3;
4894 /// }
4895 ///
4896 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4897                                            RecordDecl *Record) {
4898   assert(Record && "expected a record!");
4899 
4900   // Mock up a declarator.
4901   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4902   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4903   assert(TInfo && "couldn't build declarator info for anonymous struct");
4904 
4905   auto *ParentDecl = cast<RecordDecl>(CurContext);
4906   QualType RecTy = Context.getTypeDeclType(Record);
4907 
4908   // Create a declaration for this anonymous struct.
4909   NamedDecl *Anon =
4910       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4911                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4912                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4913                         /*InitStyle=*/ICIS_NoInit);
4914   Anon->setImplicit();
4915 
4916   // Add the anonymous struct object to the current context.
4917   CurContext->addDecl(Anon);
4918 
4919   // Inject the members of the anonymous struct into the current
4920   // context and into the identifier resolver chain for name lookup
4921   // purposes.
4922   SmallVector<NamedDecl*, 2> Chain;
4923   Chain.push_back(Anon);
4924 
4925   RecordDecl *RecordDef = Record->getDefinition();
4926   if (RequireCompleteType(Anon->getLocation(), RecTy,
4927                           diag::err_field_incomplete) ||
4928       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4929                                           AS_none, Chain)) {
4930     Anon->setInvalidDecl();
4931     ParentDecl->setInvalidDecl();
4932   }
4933 
4934   return Anon;
4935 }
4936 
4937 /// GetNameForDeclarator - Determine the full declaration name for the
4938 /// given Declarator.
4939 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4940   return GetNameFromUnqualifiedId(D.getName());
4941 }
4942 
4943 /// Retrieves the declaration name from a parsed unqualified-id.
4944 DeclarationNameInfo
4945 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4946   DeclarationNameInfo NameInfo;
4947   NameInfo.setLoc(Name.StartLocation);
4948 
4949   switch (Name.getKind()) {
4950 
4951   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4952   case UnqualifiedIdKind::IK_Identifier:
4953     NameInfo.setName(Name.Identifier);
4954     return NameInfo;
4955 
4956   case UnqualifiedIdKind::IK_DeductionGuideName: {
4957     // C++ [temp.deduct.guide]p3:
4958     //   The simple-template-id shall name a class template specialization.
4959     //   The template-name shall be the same identifier as the template-name
4960     //   of the simple-template-id.
4961     // These together intend to imply that the template-name shall name a
4962     // class template.
4963     // FIXME: template<typename T> struct X {};
4964     //        template<typename T> using Y = X<T>;
4965     //        Y(int) -> Y<int>;
4966     //   satisfies these rules but does not name a class template.
4967     TemplateName TN = Name.TemplateName.get().get();
4968     auto *Template = TN.getAsTemplateDecl();
4969     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4970       Diag(Name.StartLocation,
4971            diag::err_deduction_guide_name_not_class_template)
4972         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4973       if (Template)
4974         Diag(Template->getLocation(), diag::note_template_decl_here);
4975       return DeclarationNameInfo();
4976     }
4977 
4978     NameInfo.setName(
4979         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4980     return NameInfo;
4981   }
4982 
4983   case UnqualifiedIdKind::IK_OperatorFunctionId:
4984     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4985                                            Name.OperatorFunctionId.Operator));
4986     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4987       = Name.OperatorFunctionId.SymbolLocations[0];
4988     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4989       = Name.EndLocation.getRawEncoding();
4990     return NameInfo;
4991 
4992   case UnqualifiedIdKind::IK_LiteralOperatorId:
4993     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4994                                                            Name.Identifier));
4995     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4996     return NameInfo;
4997 
4998   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4999     TypeSourceInfo *TInfo;
5000     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5001     if (Ty.isNull())
5002       return DeclarationNameInfo();
5003     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5004                                                Context.getCanonicalType(Ty)));
5005     NameInfo.setNamedTypeInfo(TInfo);
5006     return NameInfo;
5007   }
5008 
5009   case UnqualifiedIdKind::IK_ConstructorName: {
5010     TypeSourceInfo *TInfo;
5011     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5012     if (Ty.isNull())
5013       return DeclarationNameInfo();
5014     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5015                                               Context.getCanonicalType(Ty)));
5016     NameInfo.setNamedTypeInfo(TInfo);
5017     return NameInfo;
5018   }
5019 
5020   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5021     // In well-formed code, we can only have a constructor
5022     // template-id that refers to the current context, so go there
5023     // to find the actual type being constructed.
5024     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5025     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5026       return DeclarationNameInfo();
5027 
5028     // Determine the type of the class being constructed.
5029     QualType CurClassType = Context.getTypeDeclType(CurClass);
5030 
5031     // FIXME: Check two things: that the template-id names the same type as
5032     // CurClassType, and that the template-id does not occur when the name
5033     // was qualified.
5034 
5035     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5036                                     Context.getCanonicalType(CurClassType)));
5037     // FIXME: should we retrieve TypeSourceInfo?
5038     NameInfo.setNamedTypeInfo(nullptr);
5039     return NameInfo;
5040   }
5041 
5042   case UnqualifiedIdKind::IK_DestructorName: {
5043     TypeSourceInfo *TInfo;
5044     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5045     if (Ty.isNull())
5046       return DeclarationNameInfo();
5047     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5048                                               Context.getCanonicalType(Ty)));
5049     NameInfo.setNamedTypeInfo(TInfo);
5050     return NameInfo;
5051   }
5052 
5053   case UnqualifiedIdKind::IK_TemplateId: {
5054     TemplateName TName = Name.TemplateId->Template.get();
5055     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5056     return Context.getNameForTemplate(TName, TNameLoc);
5057   }
5058 
5059   } // switch (Name.getKind())
5060 
5061   llvm_unreachable("Unknown name kind");
5062 }
5063 
5064 static QualType getCoreType(QualType Ty) {
5065   do {
5066     if (Ty->isPointerType() || Ty->isReferenceType())
5067       Ty = Ty->getPointeeType();
5068     else if (Ty->isArrayType())
5069       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5070     else
5071       return Ty.withoutLocalFastQualifiers();
5072   } while (true);
5073 }
5074 
5075 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5076 /// and Definition have "nearly" matching parameters. This heuristic is
5077 /// used to improve diagnostics in the case where an out-of-line function
5078 /// definition doesn't match any declaration within the class or namespace.
5079 /// Also sets Params to the list of indices to the parameters that differ
5080 /// between the declaration and the definition. If hasSimilarParameters
5081 /// returns true and Params is empty, then all of the parameters match.
5082 static bool hasSimilarParameters(ASTContext &Context,
5083                                      FunctionDecl *Declaration,
5084                                      FunctionDecl *Definition,
5085                                      SmallVectorImpl<unsigned> &Params) {
5086   Params.clear();
5087   if (Declaration->param_size() != Definition->param_size())
5088     return false;
5089   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5090     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5091     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5092 
5093     // The parameter types are identical
5094     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5095       continue;
5096 
5097     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5098     QualType DefParamBaseTy = getCoreType(DefParamTy);
5099     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5100     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5101 
5102     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5103         (DeclTyName && DeclTyName == DefTyName))
5104       Params.push_back(Idx);
5105     else  // The two parameters aren't even close
5106       return false;
5107   }
5108 
5109   return true;
5110 }
5111 
5112 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5113 /// declarator needs to be rebuilt in the current instantiation.
5114 /// Any bits of declarator which appear before the name are valid for
5115 /// consideration here.  That's specifically the type in the decl spec
5116 /// and the base type in any member-pointer chunks.
5117 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5118                                                     DeclarationName Name) {
5119   // The types we specifically need to rebuild are:
5120   //   - typenames, typeofs, and decltypes
5121   //   - types which will become injected class names
5122   // Of course, we also need to rebuild any type referencing such a
5123   // type.  It's safest to just say "dependent", but we call out a
5124   // few cases here.
5125 
5126   DeclSpec &DS = D.getMutableDeclSpec();
5127   switch (DS.getTypeSpecType()) {
5128   case DeclSpec::TST_typename:
5129   case DeclSpec::TST_typeofType:
5130   case DeclSpec::TST_underlyingType:
5131   case DeclSpec::TST_atomic: {
5132     // Grab the type from the parser.
5133     TypeSourceInfo *TSI = nullptr;
5134     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5135     if (T.isNull() || !T->isDependentType()) break;
5136 
5137     // Make sure there's a type source info.  This isn't really much
5138     // of a waste; most dependent types should have type source info
5139     // attached already.
5140     if (!TSI)
5141       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5142 
5143     // Rebuild the type in the current instantiation.
5144     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5145     if (!TSI) return true;
5146 
5147     // Store the new type back in the decl spec.
5148     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5149     DS.UpdateTypeRep(LocType);
5150     break;
5151   }
5152 
5153   case DeclSpec::TST_decltype:
5154   case DeclSpec::TST_typeofExpr: {
5155     Expr *E = DS.getRepAsExpr();
5156     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5157     if (Result.isInvalid()) return true;
5158     DS.UpdateExprRep(Result.get());
5159     break;
5160   }
5161 
5162   default:
5163     // Nothing to do for these decl specs.
5164     break;
5165   }
5166 
5167   // It doesn't matter what order we do this in.
5168   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5169     DeclaratorChunk &Chunk = D.getTypeObject(I);
5170 
5171     // The only type information in the declarator which can come
5172     // before the declaration name is the base type of a member
5173     // pointer.
5174     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5175       continue;
5176 
5177     // Rebuild the scope specifier in-place.
5178     CXXScopeSpec &SS = Chunk.Mem.Scope();
5179     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5180       return true;
5181   }
5182 
5183   return false;
5184 }
5185 
5186 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5187   D.setFunctionDefinitionKind(FDK_Declaration);
5188   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5189 
5190   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5191       Dcl && Dcl->getDeclContext()->isFileContext())
5192     Dcl->setTopLevelDeclInObjCContainer();
5193 
5194   if (getLangOpts().OpenCL)
5195     setCurrentOpenCLExtensionForDecl(Dcl);
5196 
5197   return Dcl;
5198 }
5199 
5200 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5201 ///   If T is the name of a class, then each of the following shall have a
5202 ///   name different from T:
5203 ///     - every static data member of class T;
5204 ///     - every member function of class T
5205 ///     - every member of class T that is itself a type;
5206 /// \returns true if the declaration name violates these rules.
5207 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5208                                    DeclarationNameInfo NameInfo) {
5209   DeclarationName Name = NameInfo.getName();
5210 
5211   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5212   while (Record && Record->isAnonymousStructOrUnion())
5213     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5214   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5215     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5216     return true;
5217   }
5218 
5219   return false;
5220 }
5221 
5222 /// Diagnose a declaration whose declarator-id has the given
5223 /// nested-name-specifier.
5224 ///
5225 /// \param SS The nested-name-specifier of the declarator-id.
5226 ///
5227 /// \param DC The declaration context to which the nested-name-specifier
5228 /// resolves.
5229 ///
5230 /// \param Name The name of the entity being declared.
5231 ///
5232 /// \param Loc The location of the name of the entity being declared.
5233 ///
5234 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5235 /// we're declaring an explicit / partial specialization / instantiation.
5236 ///
5237 /// \returns true if we cannot safely recover from this error, false otherwise.
5238 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5239                                         DeclarationName Name,
5240                                         SourceLocation Loc, bool IsTemplateId) {
5241   DeclContext *Cur = CurContext;
5242   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5243     Cur = Cur->getParent();
5244 
5245   // If the user provided a superfluous scope specifier that refers back to the
5246   // class in which the entity is already declared, diagnose and ignore it.
5247   //
5248   // class X {
5249   //   void X::f();
5250   // };
5251   //
5252   // Note, it was once ill-formed to give redundant qualification in all
5253   // contexts, but that rule was removed by DR482.
5254   if (Cur->Equals(DC)) {
5255     if (Cur->isRecord()) {
5256       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5257                                       : diag::err_member_extra_qualification)
5258         << Name << FixItHint::CreateRemoval(SS.getRange());
5259       SS.clear();
5260     } else {
5261       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5262     }
5263     return false;
5264   }
5265 
5266   // Check whether the qualifying scope encloses the scope of the original
5267   // declaration. For a template-id, we perform the checks in
5268   // CheckTemplateSpecializationScope.
5269   if (!Cur->Encloses(DC) && !IsTemplateId) {
5270     if (Cur->isRecord())
5271       Diag(Loc, diag::err_member_qualification)
5272         << Name << SS.getRange();
5273     else if (isa<TranslationUnitDecl>(DC))
5274       Diag(Loc, diag::err_invalid_declarator_global_scope)
5275         << Name << SS.getRange();
5276     else if (isa<FunctionDecl>(Cur))
5277       Diag(Loc, diag::err_invalid_declarator_in_function)
5278         << Name << SS.getRange();
5279     else if (isa<BlockDecl>(Cur))
5280       Diag(Loc, diag::err_invalid_declarator_in_block)
5281         << Name << SS.getRange();
5282     else
5283       Diag(Loc, diag::err_invalid_declarator_scope)
5284       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5285 
5286     return true;
5287   }
5288 
5289   if (Cur->isRecord()) {
5290     // Cannot qualify members within a class.
5291     Diag(Loc, diag::err_member_qualification)
5292       << Name << SS.getRange();
5293     SS.clear();
5294 
5295     // C++ constructors and destructors with incorrect scopes can break
5296     // our AST invariants by having the wrong underlying types. If
5297     // that's the case, then drop this declaration entirely.
5298     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5299          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5300         !Context.hasSameType(Name.getCXXNameType(),
5301                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5302       return true;
5303 
5304     return false;
5305   }
5306 
5307   // C++11 [dcl.meaning]p1:
5308   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5309   //   not begin with a decltype-specifer"
5310   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5311   while (SpecLoc.getPrefix())
5312     SpecLoc = SpecLoc.getPrefix();
5313   if (dyn_cast_or_null<DecltypeType>(
5314         SpecLoc.getNestedNameSpecifier()->getAsType()))
5315     Diag(Loc, diag::err_decltype_in_declarator)
5316       << SpecLoc.getTypeLoc().getSourceRange();
5317 
5318   return false;
5319 }
5320 
5321 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5322                                   MultiTemplateParamsArg TemplateParamLists) {
5323   // TODO: consider using NameInfo for diagnostic.
5324   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5325   DeclarationName Name = NameInfo.getName();
5326 
5327   // All of these full declarators require an identifier.  If it doesn't have
5328   // one, the ParsedFreeStandingDeclSpec action should be used.
5329   if (D.isDecompositionDeclarator()) {
5330     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5331   } else if (!Name) {
5332     if (!D.isInvalidType())  // Reject this if we think it is valid.
5333       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5334           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5335     return nullptr;
5336   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5337     return nullptr;
5338 
5339   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5340   // we find one that is.
5341   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5342          (S->getFlags() & Scope::TemplateParamScope) != 0)
5343     S = S->getParent();
5344 
5345   DeclContext *DC = CurContext;
5346   if (D.getCXXScopeSpec().isInvalid())
5347     D.setInvalidType();
5348   else if (D.getCXXScopeSpec().isSet()) {
5349     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5350                                         UPPC_DeclarationQualifier))
5351       return nullptr;
5352 
5353     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5354     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5355     if (!DC || isa<EnumDecl>(DC)) {
5356       // If we could not compute the declaration context, it's because the
5357       // declaration context is dependent but does not refer to a class,
5358       // class template, or class template partial specialization. Complain
5359       // and return early, to avoid the coming semantic disaster.
5360       Diag(D.getIdentifierLoc(),
5361            diag::err_template_qualified_declarator_no_match)
5362         << D.getCXXScopeSpec().getScopeRep()
5363         << D.getCXXScopeSpec().getRange();
5364       return nullptr;
5365     }
5366     bool IsDependentContext = DC->isDependentContext();
5367 
5368     if (!IsDependentContext &&
5369         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5370       return nullptr;
5371 
5372     // If a class is incomplete, do not parse entities inside it.
5373     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5374       Diag(D.getIdentifierLoc(),
5375            diag::err_member_def_undefined_record)
5376         << Name << DC << D.getCXXScopeSpec().getRange();
5377       return nullptr;
5378     }
5379     if (!D.getDeclSpec().isFriendSpecified()) {
5380       if (diagnoseQualifiedDeclaration(
5381               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5382               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5383         if (DC->isRecord())
5384           return nullptr;
5385 
5386         D.setInvalidType();
5387       }
5388     }
5389 
5390     // Check whether we need to rebuild the type of the given
5391     // declaration in the current instantiation.
5392     if (EnteringContext && IsDependentContext &&
5393         TemplateParamLists.size() != 0) {
5394       ContextRAII SavedContext(*this, DC);
5395       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5396         D.setInvalidType();
5397     }
5398   }
5399 
5400   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5401   QualType R = TInfo->getType();
5402 
5403   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5404                                       UPPC_DeclarationType))
5405     D.setInvalidType();
5406 
5407   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5408                         forRedeclarationInCurContext());
5409 
5410   // See if this is a redefinition of a variable in the same scope.
5411   if (!D.getCXXScopeSpec().isSet()) {
5412     bool IsLinkageLookup = false;
5413     bool CreateBuiltins = false;
5414 
5415     // If the declaration we're planning to build will be a function
5416     // or object with linkage, then look for another declaration with
5417     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5418     //
5419     // If the declaration we're planning to build will be declared with
5420     // external linkage in the translation unit, create any builtin with
5421     // the same name.
5422     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5423       /* Do nothing*/;
5424     else if (CurContext->isFunctionOrMethod() &&
5425              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5426               R->isFunctionType())) {
5427       IsLinkageLookup = true;
5428       CreateBuiltins =
5429           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5430     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5431                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5432       CreateBuiltins = true;
5433 
5434     if (IsLinkageLookup) {
5435       Previous.clear(LookupRedeclarationWithLinkage);
5436       Previous.setRedeclarationKind(ForExternalRedeclaration);
5437     }
5438 
5439     LookupName(Previous, S, CreateBuiltins);
5440   } else { // Something like "int foo::x;"
5441     LookupQualifiedName(Previous, DC);
5442 
5443     // C++ [dcl.meaning]p1:
5444     //   When the declarator-id is qualified, the declaration shall refer to a
5445     //  previously declared member of the class or namespace to which the
5446     //  qualifier refers (or, in the case of a namespace, of an element of the
5447     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5448     //  thereof; [...]
5449     //
5450     // Note that we already checked the context above, and that we do not have
5451     // enough information to make sure that Previous contains the declaration
5452     // we want to match. For example, given:
5453     //
5454     //   class X {
5455     //     void f();
5456     //     void f(float);
5457     //   };
5458     //
5459     //   void X::f(int) { } // ill-formed
5460     //
5461     // In this case, Previous will point to the overload set
5462     // containing the two f's declared in X, but neither of them
5463     // matches.
5464 
5465     // C++ [dcl.meaning]p1:
5466     //   [...] the member shall not merely have been introduced by a
5467     //   using-declaration in the scope of the class or namespace nominated by
5468     //   the nested-name-specifier of the declarator-id.
5469     RemoveUsingDecls(Previous);
5470   }
5471 
5472   if (Previous.isSingleResult() &&
5473       Previous.getFoundDecl()->isTemplateParameter()) {
5474     // Maybe we will complain about the shadowed template parameter.
5475     if (!D.isInvalidType())
5476       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5477                                       Previous.getFoundDecl());
5478 
5479     // Just pretend that we didn't see the previous declaration.
5480     Previous.clear();
5481   }
5482 
5483   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5484     // Forget that the previous declaration is the injected-class-name.
5485     Previous.clear();
5486 
5487   // In C++, the previous declaration we find might be a tag type
5488   // (class or enum). In this case, the new declaration will hide the
5489   // tag type. Note that this applies to functions, function templates, and
5490   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5491   if (Previous.isSingleTagDecl() &&
5492       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5493       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5494     Previous.clear();
5495 
5496   // Check that there are no default arguments other than in the parameters
5497   // of a function declaration (C++ only).
5498   if (getLangOpts().CPlusPlus)
5499     CheckExtraCXXDefaultArguments(D);
5500 
5501   NamedDecl *New;
5502 
5503   bool AddToScope = true;
5504   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5505     if (TemplateParamLists.size()) {
5506       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5507       return nullptr;
5508     }
5509 
5510     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5511   } else if (R->isFunctionType()) {
5512     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5513                                   TemplateParamLists,
5514                                   AddToScope);
5515   } else {
5516     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5517                                   AddToScope);
5518   }
5519 
5520   if (!New)
5521     return nullptr;
5522 
5523   // If this has an identifier and is not a function template specialization,
5524   // add it to the scope stack.
5525   if (New->getDeclName() && AddToScope)
5526     PushOnScopeChains(New, S);
5527 
5528   if (isInOpenMPDeclareTargetContext())
5529     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5530 
5531   return New;
5532 }
5533 
5534 /// Helper method to turn variable array types into constant array
5535 /// types in certain situations which would otherwise be errors (for
5536 /// GCC compatibility).
5537 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5538                                                     ASTContext &Context,
5539                                                     bool &SizeIsNegative,
5540                                                     llvm::APSInt &Oversized) {
5541   // This method tries to turn a variable array into a constant
5542   // array even when the size isn't an ICE.  This is necessary
5543   // for compatibility with code that depends on gcc's buggy
5544   // constant expression folding, like struct {char x[(int)(char*)2];}
5545   SizeIsNegative = false;
5546   Oversized = 0;
5547 
5548   if (T->isDependentType())
5549     return QualType();
5550 
5551   QualifierCollector Qs;
5552   const Type *Ty = Qs.strip(T);
5553 
5554   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5555     QualType Pointee = PTy->getPointeeType();
5556     QualType FixedType =
5557         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5558                                             Oversized);
5559     if (FixedType.isNull()) return FixedType;
5560     FixedType = Context.getPointerType(FixedType);
5561     return Qs.apply(Context, FixedType);
5562   }
5563   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5564     QualType Inner = PTy->getInnerType();
5565     QualType FixedType =
5566         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5567                                             Oversized);
5568     if (FixedType.isNull()) return FixedType;
5569     FixedType = Context.getParenType(FixedType);
5570     return Qs.apply(Context, FixedType);
5571   }
5572 
5573   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5574   if (!VLATy)
5575     return QualType();
5576   // FIXME: We should probably handle this case
5577   if (VLATy->getElementType()->isVariablyModifiedType())
5578     return QualType();
5579 
5580   Expr::EvalResult Result;
5581   if (!VLATy->getSizeExpr() ||
5582       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5583     return QualType();
5584 
5585   llvm::APSInt Res = Result.Val.getInt();
5586 
5587   // Check whether the array size is negative.
5588   if (Res.isSigned() && Res.isNegative()) {
5589     SizeIsNegative = true;
5590     return QualType();
5591   }
5592 
5593   // Check whether the array is too large to be addressed.
5594   unsigned ActiveSizeBits
5595     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5596                                               Res);
5597   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5598     Oversized = Res;
5599     return QualType();
5600   }
5601 
5602   return Context.getConstantArrayType(VLATy->getElementType(),
5603                                       Res, ArrayType::Normal, 0);
5604 }
5605 
5606 static void
5607 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5608   SrcTL = SrcTL.getUnqualifiedLoc();
5609   DstTL = DstTL.getUnqualifiedLoc();
5610   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5611     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5612     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5613                                       DstPTL.getPointeeLoc());
5614     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5615     return;
5616   }
5617   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5618     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5619     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5620                                       DstPTL.getInnerLoc());
5621     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5622     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5623     return;
5624   }
5625   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5626   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5627   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5628   TypeLoc DstElemTL = DstATL.getElementLoc();
5629   DstElemTL.initializeFullCopy(SrcElemTL);
5630   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5631   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5632   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5633 }
5634 
5635 /// Helper method to turn variable array types into constant array
5636 /// types in certain situations which would otherwise be errors (for
5637 /// GCC compatibility).
5638 static TypeSourceInfo*
5639 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5640                                               ASTContext &Context,
5641                                               bool &SizeIsNegative,
5642                                               llvm::APSInt &Oversized) {
5643   QualType FixedTy
5644     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5645                                           SizeIsNegative, Oversized);
5646   if (FixedTy.isNull())
5647     return nullptr;
5648   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5649   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5650                                     FixedTInfo->getTypeLoc());
5651   return FixedTInfo;
5652 }
5653 
5654 /// Register the given locally-scoped extern "C" declaration so
5655 /// that it can be found later for redeclarations. We include any extern "C"
5656 /// declaration that is not visible in the translation unit here, not just
5657 /// function-scope declarations.
5658 void
5659 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5660   if (!getLangOpts().CPlusPlus &&
5661       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5662     // Don't need to track declarations in the TU in C.
5663     return;
5664 
5665   // Note that we have a locally-scoped external with this name.
5666   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5667 }
5668 
5669 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5670   // FIXME: We can have multiple results via __attribute__((overloadable)).
5671   auto Result = Context.getExternCContextDecl()->lookup(Name);
5672   return Result.empty() ? nullptr : *Result.begin();
5673 }
5674 
5675 /// Diagnose function specifiers on a declaration of an identifier that
5676 /// does not identify a function.
5677 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5678   // FIXME: We should probably indicate the identifier in question to avoid
5679   // confusion for constructs like "virtual int a(), b;"
5680   if (DS.isVirtualSpecified())
5681     Diag(DS.getVirtualSpecLoc(),
5682          diag::err_virtual_non_function);
5683 
5684   if (DS.isExplicitSpecified())
5685     Diag(DS.getExplicitSpecLoc(),
5686          diag::err_explicit_non_function);
5687 
5688   if (DS.isNoreturnSpecified())
5689     Diag(DS.getNoreturnSpecLoc(),
5690          diag::err_noreturn_non_function);
5691 }
5692 
5693 NamedDecl*
5694 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5695                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5696   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5697   if (D.getCXXScopeSpec().isSet()) {
5698     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5699       << D.getCXXScopeSpec().getRange();
5700     D.setInvalidType();
5701     // Pretend we didn't see the scope specifier.
5702     DC = CurContext;
5703     Previous.clear();
5704   }
5705 
5706   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5707 
5708   if (D.getDeclSpec().isInlineSpecified())
5709     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5710         << getLangOpts().CPlusPlus17;
5711   if (D.getDeclSpec().isConstexprSpecified())
5712     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5713       << 1;
5714 
5715   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5716     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5717       Diag(D.getName().StartLocation,
5718            diag::err_deduction_guide_invalid_specifier)
5719           << "typedef";
5720     else
5721       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5722           << D.getName().getSourceRange();
5723     return nullptr;
5724   }
5725 
5726   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5727   if (!NewTD) return nullptr;
5728 
5729   // Handle attributes prior to checking for duplicates in MergeVarDecl
5730   ProcessDeclAttributes(S, NewTD, D);
5731 
5732   CheckTypedefForVariablyModifiedType(S, NewTD);
5733 
5734   bool Redeclaration = D.isRedeclaration();
5735   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5736   D.setRedeclaration(Redeclaration);
5737   return ND;
5738 }
5739 
5740 void
5741 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5742   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5743   // then it shall have block scope.
5744   // Note that variably modified types must be fixed before merging the decl so
5745   // that redeclarations will match.
5746   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5747   QualType T = TInfo->getType();
5748   if (T->isVariablyModifiedType()) {
5749     setFunctionHasBranchProtectedScope();
5750 
5751     if (S->getFnParent() == nullptr) {
5752       bool SizeIsNegative;
5753       llvm::APSInt Oversized;
5754       TypeSourceInfo *FixedTInfo =
5755         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5756                                                       SizeIsNegative,
5757                                                       Oversized);
5758       if (FixedTInfo) {
5759         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5760         NewTD->setTypeSourceInfo(FixedTInfo);
5761       } else {
5762         if (SizeIsNegative)
5763           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5764         else if (T->isVariableArrayType())
5765           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5766         else if (Oversized.getBoolValue())
5767           Diag(NewTD->getLocation(), diag::err_array_too_large)
5768             << Oversized.toString(10);
5769         else
5770           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5771         NewTD->setInvalidDecl();
5772       }
5773     }
5774   }
5775 }
5776 
5777 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5778 /// declares a typedef-name, either using the 'typedef' type specifier or via
5779 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5780 NamedDecl*
5781 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5782                            LookupResult &Previous, bool &Redeclaration) {
5783 
5784   // Find the shadowed declaration before filtering for scope.
5785   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5786 
5787   // Merge the decl with the existing one if appropriate. If the decl is
5788   // in an outer scope, it isn't the same thing.
5789   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5790                        /*AllowInlineNamespace*/false);
5791   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5792   if (!Previous.empty()) {
5793     Redeclaration = true;
5794     MergeTypedefNameDecl(S, NewTD, Previous);
5795   }
5796 
5797   if (ShadowedDecl && !Redeclaration)
5798     CheckShadow(NewTD, ShadowedDecl, Previous);
5799 
5800   // If this is the C FILE type, notify the AST context.
5801   if (IdentifierInfo *II = NewTD->getIdentifier())
5802     if (!NewTD->isInvalidDecl() &&
5803         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5804       if (II->isStr("FILE"))
5805         Context.setFILEDecl(NewTD);
5806       else if (II->isStr("jmp_buf"))
5807         Context.setjmp_bufDecl(NewTD);
5808       else if (II->isStr("sigjmp_buf"))
5809         Context.setsigjmp_bufDecl(NewTD);
5810       else if (II->isStr("ucontext_t"))
5811         Context.setucontext_tDecl(NewTD);
5812     }
5813 
5814   return NewTD;
5815 }
5816 
5817 /// Determines whether the given declaration is an out-of-scope
5818 /// previous declaration.
5819 ///
5820 /// This routine should be invoked when name lookup has found a
5821 /// previous declaration (PrevDecl) that is not in the scope where a
5822 /// new declaration by the same name is being introduced. If the new
5823 /// declaration occurs in a local scope, previous declarations with
5824 /// linkage may still be considered previous declarations (C99
5825 /// 6.2.2p4-5, C++ [basic.link]p6).
5826 ///
5827 /// \param PrevDecl the previous declaration found by name
5828 /// lookup
5829 ///
5830 /// \param DC the context in which the new declaration is being
5831 /// declared.
5832 ///
5833 /// \returns true if PrevDecl is an out-of-scope previous declaration
5834 /// for a new delcaration with the same name.
5835 static bool
5836 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5837                                 ASTContext &Context) {
5838   if (!PrevDecl)
5839     return false;
5840 
5841   if (!PrevDecl->hasLinkage())
5842     return false;
5843 
5844   if (Context.getLangOpts().CPlusPlus) {
5845     // C++ [basic.link]p6:
5846     //   If there is a visible declaration of an entity with linkage
5847     //   having the same name and type, ignoring entities declared
5848     //   outside the innermost enclosing namespace scope, the block
5849     //   scope declaration declares that same entity and receives the
5850     //   linkage of the previous declaration.
5851     DeclContext *OuterContext = DC->getRedeclContext();
5852     if (!OuterContext->isFunctionOrMethod())
5853       // This rule only applies to block-scope declarations.
5854       return false;
5855 
5856     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5857     if (PrevOuterContext->isRecord())
5858       // We found a member function: ignore it.
5859       return false;
5860 
5861     // Find the innermost enclosing namespace for the new and
5862     // previous declarations.
5863     OuterContext = OuterContext->getEnclosingNamespaceContext();
5864     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5865 
5866     // The previous declaration is in a different namespace, so it
5867     // isn't the same function.
5868     if (!OuterContext->Equals(PrevOuterContext))
5869       return false;
5870   }
5871 
5872   return true;
5873 }
5874 
5875 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5876   CXXScopeSpec &SS = D.getCXXScopeSpec();
5877   if (!SS.isSet()) return;
5878   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5879 }
5880 
5881 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5882   QualType type = decl->getType();
5883   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5884   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5885     // Various kinds of declaration aren't allowed to be __autoreleasing.
5886     unsigned kind = -1U;
5887     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5888       if (var->hasAttr<BlocksAttr>())
5889         kind = 0; // __block
5890       else if (!var->hasLocalStorage())
5891         kind = 1; // global
5892     } else if (isa<ObjCIvarDecl>(decl)) {
5893       kind = 3; // ivar
5894     } else if (isa<FieldDecl>(decl)) {
5895       kind = 2; // field
5896     }
5897 
5898     if (kind != -1U) {
5899       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5900         << kind;
5901     }
5902   } else if (lifetime == Qualifiers::OCL_None) {
5903     // Try to infer lifetime.
5904     if (!type->isObjCLifetimeType())
5905       return false;
5906 
5907     lifetime = type->getObjCARCImplicitLifetime();
5908     type = Context.getLifetimeQualifiedType(type, lifetime);
5909     decl->setType(type);
5910   }
5911 
5912   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5913     // Thread-local variables cannot have lifetime.
5914     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5915         var->getTLSKind()) {
5916       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5917         << var->getType();
5918       return true;
5919     }
5920   }
5921 
5922   return false;
5923 }
5924 
5925 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5926   // Ensure that an auto decl is deduced otherwise the checks below might cache
5927   // the wrong linkage.
5928   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5929 
5930   // 'weak' only applies to declarations with external linkage.
5931   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5932     if (!ND.isExternallyVisible()) {
5933       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5934       ND.dropAttr<WeakAttr>();
5935     }
5936   }
5937   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5938     if (ND.isExternallyVisible()) {
5939       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5940       ND.dropAttr<WeakRefAttr>();
5941       ND.dropAttr<AliasAttr>();
5942     }
5943   }
5944 
5945   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5946     if (VD->hasInit()) {
5947       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5948         assert(VD->isThisDeclarationADefinition() &&
5949                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5950         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5951         VD->dropAttr<AliasAttr>();
5952       }
5953     }
5954   }
5955 
5956   // 'selectany' only applies to externally visible variable declarations.
5957   // It does not apply to functions.
5958   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5959     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5960       S.Diag(Attr->getLocation(),
5961              diag::err_attribute_selectany_non_extern_data);
5962       ND.dropAttr<SelectAnyAttr>();
5963     }
5964   }
5965 
5966   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5967     // dll attributes require external linkage. Static locals may have external
5968     // linkage but still cannot be explicitly imported or exported.
5969     auto *VD = dyn_cast<VarDecl>(&ND);
5970     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5971       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5972         << &ND << Attr;
5973       ND.setInvalidDecl();
5974     }
5975   }
5976 
5977   // Virtual functions cannot be marked as 'notail'.
5978   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5979     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5980       if (MD->isVirtual()) {
5981         S.Diag(ND.getLocation(),
5982                diag::err_invalid_attribute_on_virtual_function)
5983             << Attr;
5984         ND.dropAttr<NotTailCalledAttr>();
5985       }
5986 
5987   // Check the attributes on the function type, if any.
5988   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
5989     // Don't declare this variable in the second operand of the for-statement;
5990     // GCC miscompiles that by ending its lifetime before evaluating the
5991     // third operand. See gcc.gnu.org/PR86769.
5992     AttributedTypeLoc ATL;
5993     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
5994          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
5995          TL = ATL.getModifiedLoc()) {
5996       // The [[lifetimebound]] attribute can be applied to the implicit object
5997       // parameter of a non-static member function (other than a ctor or dtor)
5998       // by applying it to the function type.
5999       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6000         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6001         if (!MD || MD->isStatic()) {
6002           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6003               << !MD << A->getRange();
6004         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6005           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6006               << isa<CXXDestructorDecl>(MD) << A->getRange();
6007         }
6008       }
6009     }
6010   }
6011 }
6012 
6013 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6014                                            NamedDecl *NewDecl,
6015                                            bool IsSpecialization,
6016                                            bool IsDefinition) {
6017   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6018     return;
6019 
6020   bool IsTemplate = false;
6021   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6022     OldDecl = OldTD->getTemplatedDecl();
6023     IsTemplate = true;
6024     if (!IsSpecialization)
6025       IsDefinition = false;
6026   }
6027   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6028     NewDecl = NewTD->getTemplatedDecl();
6029     IsTemplate = true;
6030   }
6031 
6032   if (!OldDecl || !NewDecl)
6033     return;
6034 
6035   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6036   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6037   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6038   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6039 
6040   // dllimport and dllexport are inheritable attributes so we have to exclude
6041   // inherited attribute instances.
6042   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6043                     (NewExportAttr && !NewExportAttr->isInherited());
6044 
6045   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6046   // the only exception being explicit specializations.
6047   // Implicitly generated declarations are also excluded for now because there
6048   // is no other way to switch these to use dllimport or dllexport.
6049   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6050 
6051   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6052     // Allow with a warning for free functions and global variables.
6053     bool JustWarn = false;
6054     if (!OldDecl->isCXXClassMember()) {
6055       auto *VD = dyn_cast<VarDecl>(OldDecl);
6056       if (VD && !VD->getDescribedVarTemplate())
6057         JustWarn = true;
6058       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6059       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6060         JustWarn = true;
6061     }
6062 
6063     // We cannot change a declaration that's been used because IR has already
6064     // been emitted. Dllimported functions will still work though (modulo
6065     // address equality) as they can use the thunk.
6066     if (OldDecl->isUsed())
6067       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6068         JustWarn = false;
6069 
6070     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6071                                : diag::err_attribute_dll_redeclaration;
6072     S.Diag(NewDecl->getLocation(), DiagID)
6073         << NewDecl
6074         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6075     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6076     if (!JustWarn) {
6077       NewDecl->setInvalidDecl();
6078       return;
6079     }
6080   }
6081 
6082   // A redeclaration is not allowed to drop a dllimport attribute, the only
6083   // exceptions being inline function definitions (except for function
6084   // templates), local extern declarations, qualified friend declarations or
6085   // special MSVC extension: in the last case, the declaration is treated as if
6086   // it were marked dllexport.
6087   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6088   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6089   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6090     // Ignore static data because out-of-line definitions are diagnosed
6091     // separately.
6092     IsStaticDataMember = VD->isStaticDataMember();
6093     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6094                    VarDecl::DeclarationOnly;
6095   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6096     IsInline = FD->isInlined();
6097     IsQualifiedFriend = FD->getQualifier() &&
6098                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6099   }
6100 
6101   if (OldImportAttr && !HasNewAttr &&
6102       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6103       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6104     if (IsMicrosoft && IsDefinition) {
6105       S.Diag(NewDecl->getLocation(),
6106              diag::warn_redeclaration_without_import_attribute)
6107           << NewDecl;
6108       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6109       NewDecl->dropAttr<DLLImportAttr>();
6110       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6111           NewImportAttr->getRange(), S.Context,
6112           NewImportAttr->getSpellingListIndex()));
6113     } else {
6114       S.Diag(NewDecl->getLocation(),
6115              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6116           << NewDecl << OldImportAttr;
6117       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6118       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6119       OldDecl->dropAttr<DLLImportAttr>();
6120       NewDecl->dropAttr<DLLImportAttr>();
6121     }
6122   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6123     // In MinGW, seeing a function declared inline drops the dllimport
6124     // attribute.
6125     OldDecl->dropAttr<DLLImportAttr>();
6126     NewDecl->dropAttr<DLLImportAttr>();
6127     S.Diag(NewDecl->getLocation(),
6128            diag::warn_dllimport_dropped_from_inline_function)
6129         << NewDecl << OldImportAttr;
6130   }
6131 
6132   // A specialization of a class template member function is processed here
6133   // since it's a redeclaration. If the parent class is dllexport, the
6134   // specialization inherits that attribute. This doesn't happen automatically
6135   // since the parent class isn't instantiated until later.
6136   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6137     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6138         !NewImportAttr && !NewExportAttr) {
6139       if (const DLLExportAttr *ParentExportAttr =
6140               MD->getParent()->getAttr<DLLExportAttr>()) {
6141         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6142         NewAttr->setInherited(true);
6143         NewDecl->addAttr(NewAttr);
6144       }
6145     }
6146   }
6147 }
6148 
6149 /// Given that we are within the definition of the given function,
6150 /// will that definition behave like C99's 'inline', where the
6151 /// definition is discarded except for optimization purposes?
6152 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6153   // Try to avoid calling GetGVALinkageForFunction.
6154 
6155   // All cases of this require the 'inline' keyword.
6156   if (!FD->isInlined()) return false;
6157 
6158   // This is only possible in C++ with the gnu_inline attribute.
6159   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6160     return false;
6161 
6162   // Okay, go ahead and call the relatively-more-expensive function.
6163   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6164 }
6165 
6166 /// Determine whether a variable is extern "C" prior to attaching
6167 /// an initializer. We can't just call isExternC() here, because that
6168 /// will also compute and cache whether the declaration is externally
6169 /// visible, which might change when we attach the initializer.
6170 ///
6171 /// This can only be used if the declaration is known to not be a
6172 /// redeclaration of an internal linkage declaration.
6173 ///
6174 /// For instance:
6175 ///
6176 ///   auto x = []{};
6177 ///
6178 /// Attaching the initializer here makes this declaration not externally
6179 /// visible, because its type has internal linkage.
6180 ///
6181 /// FIXME: This is a hack.
6182 template<typename T>
6183 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6184   if (S.getLangOpts().CPlusPlus) {
6185     // In C++, the overloadable attribute negates the effects of extern "C".
6186     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6187       return false;
6188 
6189     // So do CUDA's host/device attributes.
6190     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6191                                  D->template hasAttr<CUDAHostAttr>()))
6192       return false;
6193   }
6194   return D->isExternC();
6195 }
6196 
6197 static bool shouldConsiderLinkage(const VarDecl *VD) {
6198   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6199   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6200       isa<OMPDeclareMapperDecl>(DC))
6201     return VD->hasExternalStorage();
6202   if (DC->isFileContext())
6203     return true;
6204   if (DC->isRecord())
6205     return false;
6206   llvm_unreachable("Unexpected context");
6207 }
6208 
6209 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6210   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6211   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6212       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6213     return true;
6214   if (DC->isRecord())
6215     return false;
6216   llvm_unreachable("Unexpected context");
6217 }
6218 
6219 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6220                           ParsedAttr::Kind Kind) {
6221   // Check decl attributes on the DeclSpec.
6222   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6223     return true;
6224 
6225   // Walk the declarator structure, checking decl attributes that were in a type
6226   // position to the decl itself.
6227   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6228     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6229       return true;
6230   }
6231 
6232   // Finally, check attributes on the decl itself.
6233   return PD.getAttributes().hasAttribute(Kind);
6234 }
6235 
6236 /// Adjust the \c DeclContext for a function or variable that might be a
6237 /// function-local external declaration.
6238 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6239   if (!DC->isFunctionOrMethod())
6240     return false;
6241 
6242   // If this is a local extern function or variable declared within a function
6243   // template, don't add it into the enclosing namespace scope until it is
6244   // instantiated; it might have a dependent type right now.
6245   if (DC->isDependentContext())
6246     return true;
6247 
6248   // C++11 [basic.link]p7:
6249   //   When a block scope declaration of an entity with linkage is not found to
6250   //   refer to some other declaration, then that entity is a member of the
6251   //   innermost enclosing namespace.
6252   //
6253   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6254   // semantically-enclosing namespace, not a lexically-enclosing one.
6255   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6256     DC = DC->getParent();
6257   return true;
6258 }
6259 
6260 /// Returns true if given declaration has external C language linkage.
6261 static bool isDeclExternC(const Decl *D) {
6262   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6263     return FD->isExternC();
6264   if (const auto *VD = dyn_cast<VarDecl>(D))
6265     return VD->isExternC();
6266 
6267   llvm_unreachable("Unknown type of decl!");
6268 }
6269 
6270 NamedDecl *Sema::ActOnVariableDeclarator(
6271     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6272     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6273     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6274   QualType R = TInfo->getType();
6275   DeclarationName Name = GetNameForDeclarator(D).getName();
6276 
6277   IdentifierInfo *II = Name.getAsIdentifierInfo();
6278 
6279   if (D.isDecompositionDeclarator()) {
6280     // Take the name of the first declarator as our name for diagnostic
6281     // purposes.
6282     auto &Decomp = D.getDecompositionDeclarator();
6283     if (!Decomp.bindings().empty()) {
6284       II = Decomp.bindings()[0].Name;
6285       Name = II;
6286     }
6287   } else if (!II) {
6288     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6289     return nullptr;
6290   }
6291 
6292   if (getLangOpts().OpenCL) {
6293     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6294     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6295     // argument.
6296     if (R->isImageType() || R->isPipeType()) {
6297       Diag(D.getIdentifierLoc(),
6298            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6299           << R;
6300       D.setInvalidType();
6301       return nullptr;
6302     }
6303 
6304     // OpenCL v1.2 s6.9.r:
6305     // The event type cannot be used to declare a program scope variable.
6306     // OpenCL v2.0 s6.9.q:
6307     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6308     if (NULL == S->getParent()) {
6309       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6310         Diag(D.getIdentifierLoc(),
6311              diag::err_invalid_type_for_program_scope_var) << R;
6312         D.setInvalidType();
6313         return nullptr;
6314       }
6315     }
6316 
6317     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6318     QualType NR = R;
6319     while (NR->isPointerType()) {
6320       if (NR->isFunctionPointerType()) {
6321         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6322         D.setInvalidType();
6323         break;
6324       }
6325       NR = NR->getPointeeType();
6326     }
6327 
6328     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6329       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6330       // half array type (unless the cl_khr_fp16 extension is enabled).
6331       if (Context.getBaseElementType(R)->isHalfType()) {
6332         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6333         D.setInvalidType();
6334       }
6335     }
6336 
6337     if (R->isSamplerT()) {
6338       // OpenCL v1.2 s6.9.b p4:
6339       // The sampler type cannot be used with the __local and __global address
6340       // space qualifiers.
6341       if (R.getAddressSpace() == LangAS::opencl_local ||
6342           R.getAddressSpace() == LangAS::opencl_global) {
6343         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6344       }
6345 
6346       // OpenCL v1.2 s6.12.14.1:
6347       // A global sampler must be declared with either the constant address
6348       // space qualifier or with the const qualifier.
6349       if (DC->isTranslationUnit() &&
6350           !(R.getAddressSpace() == LangAS::opencl_constant ||
6351           R.isConstQualified())) {
6352         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6353         D.setInvalidType();
6354       }
6355     }
6356 
6357     // OpenCL v1.2 s6.9.r:
6358     // The event type cannot be used with the __local, __constant and __global
6359     // address space qualifiers.
6360     if (R->isEventT()) {
6361       if (R.getAddressSpace() != LangAS::opencl_private) {
6362         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6363         D.setInvalidType();
6364       }
6365     }
6366 
6367     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6368     // supported.  OpenCL C does not support thread_local either, and
6369     // also reject all other thread storage class specifiers.
6370     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6371     if (TSC != TSCS_unspecified) {
6372       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6373       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6374            diag::err_opencl_unknown_type_specifier)
6375           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6376           << DeclSpec::getSpecifierName(TSC) << 1;
6377       D.setInvalidType();
6378       return nullptr;
6379     }
6380   }
6381 
6382   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6383   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6384 
6385   // dllimport globals without explicit storage class are treated as extern. We
6386   // have to change the storage class this early to get the right DeclContext.
6387   if (SC == SC_None && !DC->isRecord() &&
6388       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6389       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6390     SC = SC_Extern;
6391 
6392   DeclContext *OriginalDC = DC;
6393   bool IsLocalExternDecl = SC == SC_Extern &&
6394                            adjustContextForLocalExternDecl(DC);
6395 
6396   if (SCSpec == DeclSpec::SCS_mutable) {
6397     // mutable can only appear on non-static class members, so it's always
6398     // an error here
6399     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6400     D.setInvalidType();
6401     SC = SC_None;
6402   }
6403 
6404   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6405       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6406                               D.getDeclSpec().getStorageClassSpecLoc())) {
6407     // In C++11, the 'register' storage class specifier is deprecated.
6408     // Suppress the warning in system macros, it's used in macros in some
6409     // popular C system headers, such as in glibc's htonl() macro.
6410     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6411          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6412                                    : diag::warn_deprecated_register)
6413       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6414   }
6415 
6416   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6417 
6418   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6419     // C99 6.9p2: The storage-class specifiers auto and register shall not
6420     // appear in the declaration specifiers in an external declaration.
6421     // Global Register+Asm is a GNU extension we support.
6422     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6423       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6424       D.setInvalidType();
6425     }
6426   }
6427 
6428   bool IsMemberSpecialization = false;
6429   bool IsVariableTemplateSpecialization = false;
6430   bool IsPartialSpecialization = false;
6431   bool IsVariableTemplate = false;
6432   VarDecl *NewVD = nullptr;
6433   VarTemplateDecl *NewTemplate = nullptr;
6434   TemplateParameterList *TemplateParams = nullptr;
6435   if (!getLangOpts().CPlusPlus) {
6436     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6437                             II, R, TInfo, SC);
6438 
6439     if (R->getContainedDeducedType())
6440       ParsingInitForAutoVars.insert(NewVD);
6441 
6442     if (D.isInvalidType())
6443       NewVD->setInvalidDecl();
6444   } else {
6445     bool Invalid = false;
6446 
6447     if (DC->isRecord() && !CurContext->isRecord()) {
6448       // This is an out-of-line definition of a static data member.
6449       switch (SC) {
6450       case SC_None:
6451         break;
6452       case SC_Static:
6453         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6454              diag::err_static_out_of_line)
6455           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6456         break;
6457       case SC_Auto:
6458       case SC_Register:
6459       case SC_Extern:
6460         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6461         // to names of variables declared in a block or to function parameters.
6462         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6463         // of class members
6464 
6465         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6466              diag::err_storage_class_for_static_member)
6467           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6468         break;
6469       case SC_PrivateExtern:
6470         llvm_unreachable("C storage class in c++!");
6471       }
6472     }
6473 
6474     if (SC == SC_Static && CurContext->isRecord()) {
6475       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6476         if (RD->isLocalClass())
6477           Diag(D.getIdentifierLoc(),
6478                diag::err_static_data_member_not_allowed_in_local_class)
6479             << Name << RD->getDeclName();
6480 
6481         // C++98 [class.union]p1: If a union contains a static data member,
6482         // the program is ill-formed. C++11 drops this restriction.
6483         if (RD->isUnion())
6484           Diag(D.getIdentifierLoc(),
6485                getLangOpts().CPlusPlus11
6486                  ? diag::warn_cxx98_compat_static_data_member_in_union
6487                  : diag::ext_static_data_member_in_union) << Name;
6488         // We conservatively disallow static data members in anonymous structs.
6489         else if (!RD->getDeclName())
6490           Diag(D.getIdentifierLoc(),
6491                diag::err_static_data_member_not_allowed_in_anon_struct)
6492             << Name << RD->isUnion();
6493       }
6494     }
6495 
6496     // Match up the template parameter lists with the scope specifier, then
6497     // determine whether we have a template or a template specialization.
6498     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6499         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6500         D.getCXXScopeSpec(),
6501         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6502             ? D.getName().TemplateId
6503             : nullptr,
6504         TemplateParamLists,
6505         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6506 
6507     if (TemplateParams) {
6508       if (!TemplateParams->size() &&
6509           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6510         // There is an extraneous 'template<>' for this variable. Complain
6511         // about it, but allow the declaration of the variable.
6512         Diag(TemplateParams->getTemplateLoc(),
6513              diag::err_template_variable_noparams)
6514           << II
6515           << SourceRange(TemplateParams->getTemplateLoc(),
6516                          TemplateParams->getRAngleLoc());
6517         TemplateParams = nullptr;
6518       } else {
6519         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6520           // This is an explicit specialization or a partial specialization.
6521           // FIXME: Check that we can declare a specialization here.
6522           IsVariableTemplateSpecialization = true;
6523           IsPartialSpecialization = TemplateParams->size() > 0;
6524         } else { // if (TemplateParams->size() > 0)
6525           // This is a template declaration.
6526           IsVariableTemplate = true;
6527 
6528           // Check that we can declare a template here.
6529           if (CheckTemplateDeclScope(S, TemplateParams))
6530             return nullptr;
6531 
6532           // Only C++1y supports variable templates (N3651).
6533           Diag(D.getIdentifierLoc(),
6534                getLangOpts().CPlusPlus14
6535                    ? diag::warn_cxx11_compat_variable_template
6536                    : diag::ext_variable_template);
6537         }
6538       }
6539     } else {
6540       assert((Invalid ||
6541               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6542              "should have a 'template<>' for this decl");
6543     }
6544 
6545     if (IsVariableTemplateSpecialization) {
6546       SourceLocation TemplateKWLoc =
6547           TemplateParamLists.size() > 0
6548               ? TemplateParamLists[0]->getTemplateLoc()
6549               : SourceLocation();
6550       DeclResult Res = ActOnVarTemplateSpecialization(
6551           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6552           IsPartialSpecialization);
6553       if (Res.isInvalid())
6554         return nullptr;
6555       NewVD = cast<VarDecl>(Res.get());
6556       AddToScope = false;
6557     } else if (D.isDecompositionDeclarator()) {
6558       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6559                                         D.getIdentifierLoc(), R, TInfo, SC,
6560                                         Bindings);
6561     } else
6562       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6563                               D.getIdentifierLoc(), II, R, TInfo, SC);
6564 
6565     // If this is supposed to be a variable template, create it as such.
6566     if (IsVariableTemplate) {
6567       NewTemplate =
6568           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6569                                   TemplateParams, NewVD);
6570       NewVD->setDescribedVarTemplate(NewTemplate);
6571     }
6572 
6573     // If this decl has an auto type in need of deduction, make a note of the
6574     // Decl so we can diagnose uses of it in its own initializer.
6575     if (R->getContainedDeducedType())
6576       ParsingInitForAutoVars.insert(NewVD);
6577 
6578     if (D.isInvalidType() || Invalid) {
6579       NewVD->setInvalidDecl();
6580       if (NewTemplate)
6581         NewTemplate->setInvalidDecl();
6582     }
6583 
6584     SetNestedNameSpecifier(*this, NewVD, D);
6585 
6586     // If we have any template parameter lists that don't directly belong to
6587     // the variable (matching the scope specifier), store them.
6588     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6589     if (TemplateParamLists.size() > VDTemplateParamLists)
6590       NewVD->setTemplateParameterListsInfo(
6591           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6592 
6593     if (D.getDeclSpec().isConstexprSpecified()) {
6594       NewVD->setConstexpr(true);
6595       // C++1z [dcl.spec.constexpr]p1:
6596       //   A static data member declared with the constexpr specifier is
6597       //   implicitly an inline variable.
6598       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6599         NewVD->setImplicitlyInline();
6600     }
6601   }
6602 
6603   if (D.getDeclSpec().isInlineSpecified()) {
6604     if (!getLangOpts().CPlusPlus) {
6605       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6606           << 0;
6607     } else if (CurContext->isFunctionOrMethod()) {
6608       // 'inline' is not allowed on block scope variable declaration.
6609       Diag(D.getDeclSpec().getInlineSpecLoc(),
6610            diag::err_inline_declaration_block_scope) << Name
6611         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6612     } else {
6613       Diag(D.getDeclSpec().getInlineSpecLoc(),
6614            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6615                                      : diag::ext_inline_variable);
6616       NewVD->setInlineSpecified();
6617     }
6618   }
6619 
6620   // Set the lexical context. If the declarator has a C++ scope specifier, the
6621   // lexical context will be different from the semantic context.
6622   NewVD->setLexicalDeclContext(CurContext);
6623   if (NewTemplate)
6624     NewTemplate->setLexicalDeclContext(CurContext);
6625 
6626   if (IsLocalExternDecl) {
6627     if (D.isDecompositionDeclarator())
6628       for (auto *B : Bindings)
6629         B->setLocalExternDecl();
6630     else
6631       NewVD->setLocalExternDecl();
6632   }
6633 
6634   bool EmitTLSUnsupportedError = false;
6635   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6636     // C++11 [dcl.stc]p4:
6637     //   When thread_local is applied to a variable of block scope the
6638     //   storage-class-specifier static is implied if it does not appear
6639     //   explicitly.
6640     // Core issue: 'static' is not implied if the variable is declared
6641     //   'extern'.
6642     if (NewVD->hasLocalStorage() &&
6643         (SCSpec != DeclSpec::SCS_unspecified ||
6644          TSCS != DeclSpec::TSCS_thread_local ||
6645          !DC->isFunctionOrMethod()))
6646       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6647            diag::err_thread_non_global)
6648         << DeclSpec::getSpecifierName(TSCS);
6649     else if (!Context.getTargetInfo().isTLSSupported()) {
6650       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6651         // Postpone error emission until we've collected attributes required to
6652         // figure out whether it's a host or device variable and whether the
6653         // error should be ignored.
6654         EmitTLSUnsupportedError = true;
6655         // We still need to mark the variable as TLS so it shows up in AST with
6656         // proper storage class for other tools to use even if we're not going
6657         // to emit any code for it.
6658         NewVD->setTSCSpec(TSCS);
6659       } else
6660         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6661              diag::err_thread_unsupported);
6662     } else
6663       NewVD->setTSCSpec(TSCS);
6664   }
6665 
6666   // C99 6.7.4p3
6667   //   An inline definition of a function with external linkage shall
6668   //   not contain a definition of a modifiable object with static or
6669   //   thread storage duration...
6670   // We only apply this when the function is required to be defined
6671   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6672   // that a local variable with thread storage duration still has to
6673   // be marked 'static'.  Also note that it's possible to get these
6674   // semantics in C++ using __attribute__((gnu_inline)).
6675   if (SC == SC_Static && S->getFnParent() != nullptr &&
6676       !NewVD->getType().isConstQualified()) {
6677     FunctionDecl *CurFD = getCurFunctionDecl();
6678     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6679       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6680            diag::warn_static_local_in_extern_inline);
6681       MaybeSuggestAddingStaticToDecl(CurFD);
6682     }
6683   }
6684 
6685   if (D.getDeclSpec().isModulePrivateSpecified()) {
6686     if (IsVariableTemplateSpecialization)
6687       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6688           << (IsPartialSpecialization ? 1 : 0)
6689           << FixItHint::CreateRemoval(
6690                  D.getDeclSpec().getModulePrivateSpecLoc());
6691     else if (IsMemberSpecialization)
6692       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6693         << 2
6694         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6695     else if (NewVD->hasLocalStorage())
6696       Diag(NewVD->getLocation(), diag::err_module_private_local)
6697         << 0 << NewVD->getDeclName()
6698         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6699         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6700     else {
6701       NewVD->setModulePrivate();
6702       if (NewTemplate)
6703         NewTemplate->setModulePrivate();
6704       for (auto *B : Bindings)
6705         B->setModulePrivate();
6706     }
6707   }
6708 
6709   // Handle attributes prior to checking for duplicates in MergeVarDecl
6710   ProcessDeclAttributes(S, NewVD, D);
6711 
6712   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6713     if (EmitTLSUnsupportedError &&
6714         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6715          (getLangOpts().OpenMPIsDevice &&
6716           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6717       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6718            diag::err_thread_unsupported);
6719     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6720     // storage [duration]."
6721     if (SC == SC_None && S->getFnParent() != nullptr &&
6722         (NewVD->hasAttr<CUDASharedAttr>() ||
6723          NewVD->hasAttr<CUDAConstantAttr>())) {
6724       NewVD->setStorageClass(SC_Static);
6725     }
6726   }
6727 
6728   // Ensure that dllimport globals without explicit storage class are treated as
6729   // extern. The storage class is set above using parsed attributes. Now we can
6730   // check the VarDecl itself.
6731   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6732          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6733          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6734 
6735   // In auto-retain/release, infer strong retension for variables of
6736   // retainable type.
6737   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6738     NewVD->setInvalidDecl();
6739 
6740   // Handle GNU asm-label extension (encoded as an attribute).
6741   if (Expr *E = (Expr*)D.getAsmLabel()) {
6742     // The parser guarantees this is a string.
6743     StringLiteral *SE = cast<StringLiteral>(E);
6744     StringRef Label = SE->getString();
6745     if (S->getFnParent() != nullptr) {
6746       switch (SC) {
6747       case SC_None:
6748       case SC_Auto:
6749         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6750         break;
6751       case SC_Register:
6752         // Local Named register
6753         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6754             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6755           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6756         break;
6757       case SC_Static:
6758       case SC_Extern:
6759       case SC_PrivateExtern:
6760         break;
6761       }
6762     } else if (SC == SC_Register) {
6763       // Global Named register
6764       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6765         const auto &TI = Context.getTargetInfo();
6766         bool HasSizeMismatch;
6767 
6768         if (!TI.isValidGCCRegisterName(Label))
6769           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6770         else if (!TI.validateGlobalRegisterVariable(Label,
6771                                                     Context.getTypeSize(R),
6772                                                     HasSizeMismatch))
6773           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6774         else if (HasSizeMismatch)
6775           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6776       }
6777 
6778       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6779         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6780         NewVD->setInvalidDecl(true);
6781       }
6782     }
6783 
6784     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6785                                                 Context, Label, 0));
6786   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6787     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6788       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6789     if (I != ExtnameUndeclaredIdentifiers.end()) {
6790       if (isDeclExternC(NewVD)) {
6791         NewVD->addAttr(I->second);
6792         ExtnameUndeclaredIdentifiers.erase(I);
6793       } else
6794         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6795             << /*Variable*/1 << NewVD;
6796     }
6797   }
6798 
6799   // Find the shadowed declaration before filtering for scope.
6800   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6801                                 ? getShadowedDeclaration(NewVD, Previous)
6802                                 : nullptr;
6803 
6804   // Don't consider existing declarations that are in a different
6805   // scope and are out-of-semantic-context declarations (if the new
6806   // declaration has linkage).
6807   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6808                        D.getCXXScopeSpec().isNotEmpty() ||
6809                        IsMemberSpecialization ||
6810                        IsVariableTemplateSpecialization);
6811 
6812   // Check whether the previous declaration is in the same block scope. This
6813   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6814   if (getLangOpts().CPlusPlus &&
6815       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6816     NewVD->setPreviousDeclInSameBlockScope(
6817         Previous.isSingleResult() && !Previous.isShadowed() &&
6818         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6819 
6820   if (!getLangOpts().CPlusPlus) {
6821     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6822   } else {
6823     // If this is an explicit specialization of a static data member, check it.
6824     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6825         CheckMemberSpecialization(NewVD, Previous))
6826       NewVD->setInvalidDecl();
6827 
6828     // Merge the decl with the existing one if appropriate.
6829     if (!Previous.empty()) {
6830       if (Previous.isSingleResult() &&
6831           isa<FieldDecl>(Previous.getFoundDecl()) &&
6832           D.getCXXScopeSpec().isSet()) {
6833         // The user tried to define a non-static data member
6834         // out-of-line (C++ [dcl.meaning]p1).
6835         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6836           << D.getCXXScopeSpec().getRange();
6837         Previous.clear();
6838         NewVD->setInvalidDecl();
6839       }
6840     } else if (D.getCXXScopeSpec().isSet()) {
6841       // No previous declaration in the qualifying scope.
6842       Diag(D.getIdentifierLoc(), diag::err_no_member)
6843         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6844         << D.getCXXScopeSpec().getRange();
6845       NewVD->setInvalidDecl();
6846     }
6847 
6848     if (!IsVariableTemplateSpecialization)
6849       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6850 
6851     if (NewTemplate) {
6852       VarTemplateDecl *PrevVarTemplate =
6853           NewVD->getPreviousDecl()
6854               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6855               : nullptr;
6856 
6857       // Check the template parameter list of this declaration, possibly
6858       // merging in the template parameter list from the previous variable
6859       // template declaration.
6860       if (CheckTemplateParameterList(
6861               TemplateParams,
6862               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6863                               : nullptr,
6864               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6865                DC->isDependentContext())
6866                   ? TPC_ClassTemplateMember
6867                   : TPC_VarTemplate))
6868         NewVD->setInvalidDecl();
6869 
6870       // If we are providing an explicit specialization of a static variable
6871       // template, make a note of that.
6872       if (PrevVarTemplate &&
6873           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6874         PrevVarTemplate->setMemberSpecialization();
6875     }
6876   }
6877 
6878   // Diagnose shadowed variables iff this isn't a redeclaration.
6879   if (ShadowedDecl && !D.isRedeclaration())
6880     CheckShadow(NewVD, ShadowedDecl, Previous);
6881 
6882   ProcessPragmaWeak(S, NewVD);
6883 
6884   // If this is the first declaration of an extern C variable, update
6885   // the map of such variables.
6886   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6887       isIncompleteDeclExternC(*this, NewVD))
6888     RegisterLocallyScopedExternCDecl(NewVD, S);
6889 
6890   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6891     Decl *ManglingContextDecl;
6892     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6893             NewVD->getDeclContext(), ManglingContextDecl)) {
6894       Context.setManglingNumber(
6895           NewVD, MCtx->getManglingNumber(
6896                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6897       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6898     }
6899   }
6900 
6901   // Special handling of variable named 'main'.
6902   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6903       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6904       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6905 
6906     // C++ [basic.start.main]p3
6907     // A program that declares a variable main at global scope is ill-formed.
6908     if (getLangOpts().CPlusPlus)
6909       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6910 
6911     // In C, and external-linkage variable named main results in undefined
6912     // behavior.
6913     else if (NewVD->hasExternalFormalLinkage())
6914       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6915   }
6916 
6917   if (D.isRedeclaration() && !Previous.empty()) {
6918     NamedDecl *Prev = Previous.getRepresentativeDecl();
6919     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6920                                    D.isFunctionDefinition());
6921   }
6922 
6923   if (NewTemplate) {
6924     if (NewVD->isInvalidDecl())
6925       NewTemplate->setInvalidDecl();
6926     ActOnDocumentableDecl(NewTemplate);
6927     return NewTemplate;
6928   }
6929 
6930   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6931     CompleteMemberSpecialization(NewVD, Previous);
6932 
6933   return NewVD;
6934 }
6935 
6936 /// Enum describing the %select options in diag::warn_decl_shadow.
6937 enum ShadowedDeclKind {
6938   SDK_Local,
6939   SDK_Global,
6940   SDK_StaticMember,
6941   SDK_Field,
6942   SDK_Typedef,
6943   SDK_Using
6944 };
6945 
6946 /// Determine what kind of declaration we're shadowing.
6947 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6948                                                 const DeclContext *OldDC) {
6949   if (isa<TypeAliasDecl>(ShadowedDecl))
6950     return SDK_Using;
6951   else if (isa<TypedefDecl>(ShadowedDecl))
6952     return SDK_Typedef;
6953   else if (isa<RecordDecl>(OldDC))
6954     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6955 
6956   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6957 }
6958 
6959 /// Return the location of the capture if the given lambda captures the given
6960 /// variable \p VD, or an invalid source location otherwise.
6961 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6962                                          const VarDecl *VD) {
6963   for (const Capture &Capture : LSI->Captures) {
6964     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6965       return Capture.getLocation();
6966   }
6967   return SourceLocation();
6968 }
6969 
6970 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6971                                      const LookupResult &R) {
6972   // Only diagnose if we're shadowing an unambiguous field or variable.
6973   if (R.getResultKind() != LookupResult::Found)
6974     return false;
6975 
6976   // Return false if warning is ignored.
6977   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6978 }
6979 
6980 /// Return the declaration shadowed by the given variable \p D, or null
6981 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6982 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6983                                         const LookupResult &R) {
6984   if (!shouldWarnIfShadowedDecl(Diags, R))
6985     return nullptr;
6986 
6987   // Don't diagnose declarations at file scope.
6988   if (D->hasGlobalStorage())
6989     return nullptr;
6990 
6991   NamedDecl *ShadowedDecl = R.getFoundDecl();
6992   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6993              ? ShadowedDecl
6994              : nullptr;
6995 }
6996 
6997 /// Return the declaration shadowed by the given typedef \p D, or null
6998 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6999 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7000                                         const LookupResult &R) {
7001   // Don't warn if typedef declaration is part of a class
7002   if (D->getDeclContext()->isRecord())
7003     return nullptr;
7004 
7005   if (!shouldWarnIfShadowedDecl(Diags, R))
7006     return nullptr;
7007 
7008   NamedDecl *ShadowedDecl = R.getFoundDecl();
7009   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7010 }
7011 
7012 /// Diagnose variable or built-in function shadowing.  Implements
7013 /// -Wshadow.
7014 ///
7015 /// This method is called whenever a VarDecl is added to a "useful"
7016 /// scope.
7017 ///
7018 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7019 /// \param R the lookup of the name
7020 ///
7021 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7022                        const LookupResult &R) {
7023   DeclContext *NewDC = D->getDeclContext();
7024 
7025   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7026     // Fields are not shadowed by variables in C++ static methods.
7027     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7028       if (MD->isStatic())
7029         return;
7030 
7031     // Fields shadowed by constructor parameters are a special case. Usually
7032     // the constructor initializes the field with the parameter.
7033     if (isa<CXXConstructorDecl>(NewDC))
7034       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7035         // Remember that this was shadowed so we can either warn about its
7036         // modification or its existence depending on warning settings.
7037         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7038         return;
7039       }
7040   }
7041 
7042   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7043     if (shadowedVar->isExternC()) {
7044       // For shadowing external vars, make sure that we point to the global
7045       // declaration, not a locally scoped extern declaration.
7046       for (auto I : shadowedVar->redecls())
7047         if (I->isFileVarDecl()) {
7048           ShadowedDecl = I;
7049           break;
7050         }
7051     }
7052 
7053   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7054 
7055   unsigned WarningDiag = diag::warn_decl_shadow;
7056   SourceLocation CaptureLoc;
7057   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7058       isa<CXXMethodDecl>(NewDC)) {
7059     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7060       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7061         if (RD->getLambdaCaptureDefault() == LCD_None) {
7062           // Try to avoid warnings for lambdas with an explicit capture list.
7063           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7064           // Warn only when the lambda captures the shadowed decl explicitly.
7065           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7066           if (CaptureLoc.isInvalid())
7067             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7068         } else {
7069           // Remember that this was shadowed so we can avoid the warning if the
7070           // shadowed decl isn't captured and the warning settings allow it.
7071           cast<LambdaScopeInfo>(getCurFunction())
7072               ->ShadowingDecls.push_back(
7073                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7074           return;
7075         }
7076       }
7077 
7078       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7079         // A variable can't shadow a local variable in an enclosing scope, if
7080         // they are separated by a non-capturing declaration context.
7081         for (DeclContext *ParentDC = NewDC;
7082              ParentDC && !ParentDC->Equals(OldDC);
7083              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7084           // Only block literals, captured statements, and lambda expressions
7085           // can capture; other scopes don't.
7086           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7087               !isLambdaCallOperator(ParentDC)) {
7088             return;
7089           }
7090         }
7091       }
7092     }
7093   }
7094 
7095   // Only warn about certain kinds of shadowing for class members.
7096   if (NewDC && NewDC->isRecord()) {
7097     // In particular, don't warn about shadowing non-class members.
7098     if (!OldDC->isRecord())
7099       return;
7100 
7101     // TODO: should we warn about static data members shadowing
7102     // static data members from base classes?
7103 
7104     // TODO: don't diagnose for inaccessible shadowed members.
7105     // This is hard to do perfectly because we might friend the
7106     // shadowing context, but that's just a false negative.
7107   }
7108 
7109 
7110   DeclarationName Name = R.getLookupName();
7111 
7112   // Emit warning and note.
7113   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7114     return;
7115   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7116   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7117   if (!CaptureLoc.isInvalid())
7118     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7119         << Name << /*explicitly*/ 1;
7120   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7121 }
7122 
7123 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7124 /// when these variables are captured by the lambda.
7125 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7126   for (const auto &Shadow : LSI->ShadowingDecls) {
7127     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7128     // Try to avoid the warning when the shadowed decl isn't captured.
7129     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7130     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7131     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7132                                        ? diag::warn_decl_shadow_uncaptured_local
7133                                        : diag::warn_decl_shadow)
7134         << Shadow.VD->getDeclName()
7135         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7136     if (!CaptureLoc.isInvalid())
7137       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7138           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7139     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7140   }
7141 }
7142 
7143 /// Check -Wshadow without the advantage of a previous lookup.
7144 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7145   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7146     return;
7147 
7148   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7149                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7150   LookupName(R, S);
7151   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7152     CheckShadow(D, ShadowedDecl, R);
7153 }
7154 
7155 /// Check if 'E', which is an expression that is about to be modified, refers
7156 /// to a constructor parameter that shadows a field.
7157 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7158   // Quickly ignore expressions that can't be shadowing ctor parameters.
7159   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7160     return;
7161   E = E->IgnoreParenImpCasts();
7162   auto *DRE = dyn_cast<DeclRefExpr>(E);
7163   if (!DRE)
7164     return;
7165   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7166   auto I = ShadowingDecls.find(D);
7167   if (I == ShadowingDecls.end())
7168     return;
7169   const NamedDecl *ShadowedDecl = I->second;
7170   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7171   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7172   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7173   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7174 
7175   // Avoid issuing multiple warnings about the same decl.
7176   ShadowingDecls.erase(I);
7177 }
7178 
7179 /// Check for conflict between this global or extern "C" declaration and
7180 /// previous global or extern "C" declarations. This is only used in C++.
7181 template<typename T>
7182 static bool checkGlobalOrExternCConflict(
7183     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7184   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7185   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7186 
7187   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7188     // The common case: this global doesn't conflict with any extern "C"
7189     // declaration.
7190     return false;
7191   }
7192 
7193   if (Prev) {
7194     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7195       // Both the old and new declarations have C language linkage. This is a
7196       // redeclaration.
7197       Previous.clear();
7198       Previous.addDecl(Prev);
7199       return true;
7200     }
7201 
7202     // This is a global, non-extern "C" declaration, and there is a previous
7203     // non-global extern "C" declaration. Diagnose if this is a variable
7204     // declaration.
7205     if (!isa<VarDecl>(ND))
7206       return false;
7207   } else {
7208     // The declaration is extern "C". Check for any declaration in the
7209     // translation unit which might conflict.
7210     if (IsGlobal) {
7211       // We have already performed the lookup into the translation unit.
7212       IsGlobal = false;
7213       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7214            I != E; ++I) {
7215         if (isa<VarDecl>(*I)) {
7216           Prev = *I;
7217           break;
7218         }
7219       }
7220     } else {
7221       DeclContext::lookup_result R =
7222           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7223       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7224            I != E; ++I) {
7225         if (isa<VarDecl>(*I)) {
7226           Prev = *I;
7227           break;
7228         }
7229         // FIXME: If we have any other entity with this name in global scope,
7230         // the declaration is ill-formed, but that is a defect: it breaks the
7231         // 'stat' hack, for instance. Only variables can have mangled name
7232         // clashes with extern "C" declarations, so only they deserve a
7233         // diagnostic.
7234       }
7235     }
7236 
7237     if (!Prev)
7238       return false;
7239   }
7240 
7241   // Use the first declaration's location to ensure we point at something which
7242   // is lexically inside an extern "C" linkage-spec.
7243   assert(Prev && "should have found a previous declaration to diagnose");
7244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7245     Prev = FD->getFirstDecl();
7246   else
7247     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7248 
7249   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7250     << IsGlobal << ND;
7251   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7252     << IsGlobal;
7253   return false;
7254 }
7255 
7256 /// Apply special rules for handling extern "C" declarations. Returns \c true
7257 /// if we have found that this is a redeclaration of some prior entity.
7258 ///
7259 /// Per C++ [dcl.link]p6:
7260 ///   Two declarations [for a function or variable] with C language linkage
7261 ///   with the same name that appear in different scopes refer to the same
7262 ///   [entity]. An entity with C language linkage shall not be declared with
7263 ///   the same name as an entity in global scope.
7264 template<typename T>
7265 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7266                                                   LookupResult &Previous) {
7267   if (!S.getLangOpts().CPlusPlus) {
7268     // In C, when declaring a global variable, look for a corresponding 'extern'
7269     // variable declared in function scope. We don't need this in C++, because
7270     // we find local extern decls in the surrounding file-scope DeclContext.
7271     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7272       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7273         Previous.clear();
7274         Previous.addDecl(Prev);
7275         return true;
7276       }
7277     }
7278     return false;
7279   }
7280 
7281   // A declaration in the translation unit can conflict with an extern "C"
7282   // declaration.
7283   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7284     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7285 
7286   // An extern "C" declaration can conflict with a declaration in the
7287   // translation unit or can be a redeclaration of an extern "C" declaration
7288   // in another scope.
7289   if (isIncompleteDeclExternC(S,ND))
7290     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7291 
7292   // Neither global nor extern "C": nothing to do.
7293   return false;
7294 }
7295 
7296 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7297   // If the decl is already known invalid, don't check it.
7298   if (NewVD->isInvalidDecl())
7299     return;
7300 
7301   QualType T = NewVD->getType();
7302 
7303   // Defer checking an 'auto' type until its initializer is attached.
7304   if (T->isUndeducedType())
7305     return;
7306 
7307   if (NewVD->hasAttrs())
7308     CheckAlignasUnderalignment(NewVD);
7309 
7310   if (T->isObjCObjectType()) {
7311     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7312       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7313     T = Context.getObjCObjectPointerType(T);
7314     NewVD->setType(T);
7315   }
7316 
7317   // Emit an error if an address space was applied to decl with local storage.
7318   // This includes arrays of objects with address space qualifiers, but not
7319   // automatic variables that point to other address spaces.
7320   // ISO/IEC TR 18037 S5.1.2
7321   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7322       T.getAddressSpace() != LangAS::Default) {
7323     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7324     NewVD->setInvalidDecl();
7325     return;
7326   }
7327 
7328   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7329   // scope.
7330   if (getLangOpts().OpenCLVersion == 120 &&
7331       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7332       NewVD->isStaticLocal()) {
7333     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7334     NewVD->setInvalidDecl();
7335     return;
7336   }
7337 
7338   if (getLangOpts().OpenCL) {
7339     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7340     if (NewVD->hasAttr<BlocksAttr>()) {
7341       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7342       return;
7343     }
7344 
7345     if (T->isBlockPointerType()) {
7346       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7347       // can't use 'extern' storage class.
7348       if (!T.isConstQualified()) {
7349         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7350             << 0 /*const*/;
7351         NewVD->setInvalidDecl();
7352         return;
7353       }
7354       if (NewVD->hasExternalStorage()) {
7355         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7356         NewVD->setInvalidDecl();
7357         return;
7358       }
7359     }
7360     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7361     // __constant address space.
7362     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7363     // variables inside a function can also be declared in the global
7364     // address space.
7365     // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7366     // address space additionally.
7367     // FIXME: Add local AS for OpenCL C++.
7368     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7369         NewVD->hasExternalStorage()) {
7370       if (!T->isSamplerT() &&
7371           !(T.getAddressSpace() == LangAS::opencl_constant ||
7372             (T.getAddressSpace() == LangAS::opencl_global &&
7373              (getLangOpts().OpenCLVersion == 200 ||
7374               getLangOpts().OpenCLCPlusPlus)))) {
7375         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7376         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7377           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7378               << Scope << "global or constant";
7379         else
7380           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7381               << Scope << "constant";
7382         NewVD->setInvalidDecl();
7383         return;
7384       }
7385     } else {
7386       if (T.getAddressSpace() == LangAS::opencl_global) {
7387         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7388             << 1 /*is any function*/ << "global";
7389         NewVD->setInvalidDecl();
7390         return;
7391       }
7392       if (T.getAddressSpace() == LangAS::opencl_constant ||
7393           T.getAddressSpace() == LangAS::opencl_local) {
7394         FunctionDecl *FD = getCurFunctionDecl();
7395         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7396         // in functions.
7397         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7398           if (T.getAddressSpace() == LangAS::opencl_constant)
7399             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7400                 << 0 /*non-kernel only*/ << "constant";
7401           else
7402             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7403                 << 0 /*non-kernel only*/ << "local";
7404           NewVD->setInvalidDecl();
7405           return;
7406         }
7407         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7408         // in the outermost scope of a kernel function.
7409         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7410           if (!getCurScope()->isFunctionScope()) {
7411             if (T.getAddressSpace() == LangAS::opencl_constant)
7412               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7413                   << "constant";
7414             else
7415               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7416                   << "local";
7417             NewVD->setInvalidDecl();
7418             return;
7419           }
7420         }
7421       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7422         // Do not allow other address spaces on automatic variable.
7423         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7424         NewVD->setInvalidDecl();
7425         return;
7426       }
7427     }
7428   }
7429 
7430   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7431       && !NewVD->hasAttr<BlocksAttr>()) {
7432     if (getLangOpts().getGC() != LangOptions::NonGC)
7433       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7434     else {
7435       assert(!getLangOpts().ObjCAutoRefCount);
7436       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7437     }
7438   }
7439 
7440   bool isVM = T->isVariablyModifiedType();
7441   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7442       NewVD->hasAttr<BlocksAttr>())
7443     setFunctionHasBranchProtectedScope();
7444 
7445   if ((isVM && NewVD->hasLinkage()) ||
7446       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7447     bool SizeIsNegative;
7448     llvm::APSInt Oversized;
7449     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7450         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7451     QualType FixedT;
7452     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7453       FixedT = FixedTInfo->getType();
7454     else if (FixedTInfo) {
7455       // Type and type-as-written are canonically different. We need to fix up
7456       // both types separately.
7457       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7458                                                    Oversized);
7459     }
7460     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7461       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7462       // FIXME: This won't give the correct result for
7463       // int a[10][n];
7464       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7465 
7466       if (NewVD->isFileVarDecl())
7467         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7468         << SizeRange;
7469       else if (NewVD->isStaticLocal())
7470         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7471         << SizeRange;
7472       else
7473         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7474         << SizeRange;
7475       NewVD->setInvalidDecl();
7476       return;
7477     }
7478 
7479     if (!FixedTInfo) {
7480       if (NewVD->isFileVarDecl())
7481         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7482       else
7483         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7484       NewVD->setInvalidDecl();
7485       return;
7486     }
7487 
7488     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7489     NewVD->setType(FixedT);
7490     NewVD->setTypeSourceInfo(FixedTInfo);
7491   }
7492 
7493   if (T->isVoidType()) {
7494     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7495     //                    of objects and functions.
7496     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7497       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7498         << T;
7499       NewVD->setInvalidDecl();
7500       return;
7501     }
7502   }
7503 
7504   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7505     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7506     NewVD->setInvalidDecl();
7507     return;
7508   }
7509 
7510   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7511     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7512     NewVD->setInvalidDecl();
7513     return;
7514   }
7515 
7516   if (NewVD->isConstexpr() && !T->isDependentType() &&
7517       RequireLiteralType(NewVD->getLocation(), T,
7518                          diag::err_constexpr_var_non_literal)) {
7519     NewVD->setInvalidDecl();
7520     return;
7521   }
7522 }
7523 
7524 /// Perform semantic checking on a newly-created variable
7525 /// declaration.
7526 ///
7527 /// This routine performs all of the type-checking required for a
7528 /// variable declaration once it has been built. It is used both to
7529 /// check variables after they have been parsed and their declarators
7530 /// have been translated into a declaration, and to check variables
7531 /// that have been instantiated from a template.
7532 ///
7533 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7534 ///
7535 /// Returns true if the variable declaration is a redeclaration.
7536 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7537   CheckVariableDeclarationType(NewVD);
7538 
7539   // If the decl is already known invalid, don't check it.
7540   if (NewVD->isInvalidDecl())
7541     return false;
7542 
7543   // If we did not find anything by this name, look for a non-visible
7544   // extern "C" declaration with the same name.
7545   if (Previous.empty() &&
7546       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7547     Previous.setShadowed();
7548 
7549   if (!Previous.empty()) {
7550     MergeVarDecl(NewVD, Previous);
7551     return true;
7552   }
7553   return false;
7554 }
7555 
7556 namespace {
7557 struct FindOverriddenMethod {
7558   Sema *S;
7559   CXXMethodDecl *Method;
7560 
7561   /// Member lookup function that determines whether a given C++
7562   /// method overrides a method in a base class, to be used with
7563   /// CXXRecordDecl::lookupInBases().
7564   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7565     RecordDecl *BaseRecord =
7566         Specifier->getType()->getAs<RecordType>()->getDecl();
7567 
7568     DeclarationName Name = Method->getDeclName();
7569 
7570     // FIXME: Do we care about other names here too?
7571     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7572       // We really want to find the base class destructor here.
7573       QualType T = S->Context.getTypeDeclType(BaseRecord);
7574       CanQualType CT = S->Context.getCanonicalType(T);
7575 
7576       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7577     }
7578 
7579     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7580          Path.Decls = Path.Decls.slice(1)) {
7581       NamedDecl *D = Path.Decls.front();
7582       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7583         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7584           return true;
7585       }
7586     }
7587 
7588     return false;
7589   }
7590 };
7591 
7592 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7593 } // end anonymous namespace
7594 
7595 /// Report an error regarding overriding, along with any relevant
7596 /// overridden methods.
7597 ///
7598 /// \param DiagID the primary error to report.
7599 /// \param MD the overriding method.
7600 /// \param OEK which overrides to include as notes.
7601 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7602                             OverrideErrorKind OEK = OEK_All) {
7603   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7604   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7605     // This check (& the OEK parameter) could be replaced by a predicate, but
7606     // without lambdas that would be overkill. This is still nicer than writing
7607     // out the diag loop 3 times.
7608     if ((OEK == OEK_All) ||
7609         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7610         (OEK == OEK_Deleted && O->isDeleted()))
7611       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7612   }
7613 }
7614 
7615 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7616 /// and if so, check that it's a valid override and remember it.
7617 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7618   // Look for methods in base classes that this method might override.
7619   CXXBasePaths Paths;
7620   FindOverriddenMethod FOM;
7621   FOM.Method = MD;
7622   FOM.S = this;
7623   bool hasDeletedOverridenMethods = false;
7624   bool hasNonDeletedOverridenMethods = false;
7625   bool AddedAny = false;
7626   if (DC->lookupInBases(FOM, Paths)) {
7627     for (auto *I : Paths.found_decls()) {
7628       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7629         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7630         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7631             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7632             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7633             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7634           hasDeletedOverridenMethods |= OldMD->isDeleted();
7635           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7636           AddedAny = true;
7637         }
7638       }
7639     }
7640   }
7641 
7642   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7643     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7644   }
7645   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7646     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7647   }
7648 
7649   return AddedAny;
7650 }
7651 
7652 namespace {
7653   // Struct for holding all of the extra arguments needed by
7654   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7655   struct ActOnFDArgs {
7656     Scope *S;
7657     Declarator &D;
7658     MultiTemplateParamsArg TemplateParamLists;
7659     bool AddToScope;
7660   };
7661 } // end anonymous namespace
7662 
7663 namespace {
7664 
7665 // Callback to only accept typo corrections that have a non-zero edit distance.
7666 // Also only accept corrections that have the same parent decl.
7667 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7668  public:
7669   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7670                             CXXRecordDecl *Parent)
7671       : Context(Context), OriginalFD(TypoFD),
7672         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7673 
7674   bool ValidateCandidate(const TypoCorrection &candidate) override {
7675     if (candidate.getEditDistance() == 0)
7676       return false;
7677 
7678     SmallVector<unsigned, 1> MismatchedParams;
7679     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7680                                           CDeclEnd = candidate.end();
7681          CDecl != CDeclEnd; ++CDecl) {
7682       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7683 
7684       if (FD && !FD->hasBody() &&
7685           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7686         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7687           CXXRecordDecl *Parent = MD->getParent();
7688           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7689             return true;
7690         } else if (!ExpectedParent) {
7691           return true;
7692         }
7693       }
7694     }
7695 
7696     return false;
7697   }
7698 
7699  private:
7700   ASTContext &Context;
7701   FunctionDecl *OriginalFD;
7702   CXXRecordDecl *ExpectedParent;
7703 };
7704 
7705 } // end anonymous namespace
7706 
7707 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7708   TypoCorrectedFunctionDefinitions.insert(F);
7709 }
7710 
7711 /// Generate diagnostics for an invalid function redeclaration.
7712 ///
7713 /// This routine handles generating the diagnostic messages for an invalid
7714 /// function redeclaration, including finding possible similar declarations
7715 /// or performing typo correction if there are no previous declarations with
7716 /// the same name.
7717 ///
7718 /// Returns a NamedDecl iff typo correction was performed and substituting in
7719 /// the new declaration name does not cause new errors.
7720 static NamedDecl *DiagnoseInvalidRedeclaration(
7721     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7722     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7723   DeclarationName Name = NewFD->getDeclName();
7724   DeclContext *NewDC = NewFD->getDeclContext();
7725   SmallVector<unsigned, 1> MismatchedParams;
7726   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7727   TypoCorrection Correction;
7728   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7729   unsigned DiagMsg =
7730     IsLocalFriend ? diag::err_no_matching_local_friend :
7731     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7732     diag::err_member_decl_does_not_match;
7733   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7734                     IsLocalFriend ? Sema::LookupLocalFriendName
7735                                   : Sema::LookupOrdinaryName,
7736                     Sema::ForVisibleRedeclaration);
7737 
7738   NewFD->setInvalidDecl();
7739   if (IsLocalFriend)
7740     SemaRef.LookupName(Prev, S);
7741   else
7742     SemaRef.LookupQualifiedName(Prev, NewDC);
7743   assert(!Prev.isAmbiguous() &&
7744          "Cannot have an ambiguity in previous-declaration lookup");
7745   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7746   if (!Prev.empty()) {
7747     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7748          Func != FuncEnd; ++Func) {
7749       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7750       if (FD &&
7751           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7752         // Add 1 to the index so that 0 can mean the mismatch didn't
7753         // involve a parameter
7754         unsigned ParamNum =
7755             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7756         NearMatches.push_back(std::make_pair(FD, ParamNum));
7757       }
7758     }
7759   // If the qualified name lookup yielded nothing, try typo correction
7760   } else if ((Correction = SemaRef.CorrectTypo(
7761                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7762                   &ExtraArgs.D.getCXXScopeSpec(),
7763                   llvm::make_unique<DifferentNameValidatorCCC>(
7764                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7765                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7766     // Set up everything for the call to ActOnFunctionDeclarator
7767     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7768                               ExtraArgs.D.getIdentifierLoc());
7769     Previous.clear();
7770     Previous.setLookupName(Correction.getCorrection());
7771     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7772                                     CDeclEnd = Correction.end();
7773          CDecl != CDeclEnd; ++CDecl) {
7774       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7775       if (FD && !FD->hasBody() &&
7776           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7777         Previous.addDecl(FD);
7778       }
7779     }
7780     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7781 
7782     NamedDecl *Result;
7783     // Retry building the function declaration with the new previous
7784     // declarations, and with errors suppressed.
7785     {
7786       // Trap errors.
7787       Sema::SFINAETrap Trap(SemaRef);
7788 
7789       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7790       // pieces need to verify the typo-corrected C++ declaration and hopefully
7791       // eliminate the need for the parameter pack ExtraArgs.
7792       Result = SemaRef.ActOnFunctionDeclarator(
7793           ExtraArgs.S, ExtraArgs.D,
7794           Correction.getCorrectionDecl()->getDeclContext(),
7795           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7796           ExtraArgs.AddToScope);
7797 
7798       if (Trap.hasErrorOccurred())
7799         Result = nullptr;
7800     }
7801 
7802     if (Result) {
7803       // Determine which correction we picked.
7804       Decl *Canonical = Result->getCanonicalDecl();
7805       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7806            I != E; ++I)
7807         if ((*I)->getCanonicalDecl() == Canonical)
7808           Correction.setCorrectionDecl(*I);
7809 
7810       // Let Sema know about the correction.
7811       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7812       SemaRef.diagnoseTypo(
7813           Correction,
7814           SemaRef.PDiag(IsLocalFriend
7815                           ? diag::err_no_matching_local_friend_suggest
7816                           : diag::err_member_decl_does_not_match_suggest)
7817             << Name << NewDC << IsDefinition);
7818       return Result;
7819     }
7820 
7821     // Pretend the typo correction never occurred
7822     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7823                               ExtraArgs.D.getIdentifierLoc());
7824     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7825     Previous.clear();
7826     Previous.setLookupName(Name);
7827   }
7828 
7829   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7830       << Name << NewDC << IsDefinition << NewFD->getLocation();
7831 
7832   bool NewFDisConst = false;
7833   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7834     NewFDisConst = NewMD->isConst();
7835 
7836   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7837        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7838        NearMatch != NearMatchEnd; ++NearMatch) {
7839     FunctionDecl *FD = NearMatch->first;
7840     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7841     bool FDisConst = MD && MD->isConst();
7842     bool IsMember = MD || !IsLocalFriend;
7843 
7844     // FIXME: These notes are poorly worded for the local friend case.
7845     if (unsigned Idx = NearMatch->second) {
7846       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7847       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7848       if (Loc.isInvalid()) Loc = FD->getLocation();
7849       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7850                                  : diag::note_local_decl_close_param_match)
7851         << Idx << FDParam->getType()
7852         << NewFD->getParamDecl(Idx - 1)->getType();
7853     } else if (FDisConst != NewFDisConst) {
7854       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7855           << NewFDisConst << FD->getSourceRange().getEnd();
7856     } else
7857       SemaRef.Diag(FD->getLocation(),
7858                    IsMember ? diag::note_member_def_close_match
7859                             : diag::note_local_decl_close_match);
7860   }
7861   return nullptr;
7862 }
7863 
7864 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7865   switch (D.getDeclSpec().getStorageClassSpec()) {
7866   default: llvm_unreachable("Unknown storage class!");
7867   case DeclSpec::SCS_auto:
7868   case DeclSpec::SCS_register:
7869   case DeclSpec::SCS_mutable:
7870     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7871                  diag::err_typecheck_sclass_func);
7872     D.getMutableDeclSpec().ClearStorageClassSpecs();
7873     D.setInvalidType();
7874     break;
7875   case DeclSpec::SCS_unspecified: break;
7876   case DeclSpec::SCS_extern:
7877     if (D.getDeclSpec().isExternInLinkageSpec())
7878       return SC_None;
7879     return SC_Extern;
7880   case DeclSpec::SCS_static: {
7881     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7882       // C99 6.7.1p5:
7883       //   The declaration of an identifier for a function that has
7884       //   block scope shall have no explicit storage-class specifier
7885       //   other than extern
7886       // See also (C++ [dcl.stc]p4).
7887       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7888                    diag::err_static_block_func);
7889       break;
7890     } else
7891       return SC_Static;
7892   }
7893   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7894   }
7895 
7896   // No explicit storage class has already been returned
7897   return SC_None;
7898 }
7899 
7900 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7901                                            DeclContext *DC, QualType &R,
7902                                            TypeSourceInfo *TInfo,
7903                                            StorageClass SC,
7904                                            bool &IsVirtualOkay) {
7905   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7906   DeclarationName Name = NameInfo.getName();
7907 
7908   FunctionDecl *NewFD = nullptr;
7909   bool isInline = D.getDeclSpec().isInlineSpecified();
7910 
7911   if (!SemaRef.getLangOpts().CPlusPlus) {
7912     // Determine whether the function was written with a
7913     // prototype. This true when:
7914     //   - there is a prototype in the declarator, or
7915     //   - the type R of the function is some kind of typedef or other non-
7916     //     attributed reference to a type name (which eventually refers to a
7917     //     function type).
7918     bool HasPrototype =
7919       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7920       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7921 
7922     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7923                                  R, TInfo, SC, isInline, HasPrototype, false);
7924     if (D.isInvalidType())
7925       NewFD->setInvalidDecl();
7926 
7927     return NewFD;
7928   }
7929 
7930   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7931   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7932 
7933   // Check that the return type is not an abstract class type.
7934   // For record types, this is done by the AbstractClassUsageDiagnoser once
7935   // the class has been completely parsed.
7936   if (!DC->isRecord() &&
7937       SemaRef.RequireNonAbstractType(
7938           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7939           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7940     D.setInvalidType();
7941 
7942   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7943     // This is a C++ constructor declaration.
7944     assert(DC->isRecord() &&
7945            "Constructors can only be declared in a member context");
7946 
7947     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7948     return CXXConstructorDecl::Create(
7949         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7950         TInfo, isExplicit, isInline,
7951         /*isImplicitlyDeclared=*/false, isConstexpr);
7952 
7953   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7954     // This is a C++ destructor declaration.
7955     if (DC->isRecord()) {
7956       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7957       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7958       CXXDestructorDecl *NewDD =
7959           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
7960                                     NameInfo, R, TInfo, isInline,
7961                                     /*isImplicitlyDeclared=*/false);
7962 
7963       // If the destructor needs an implicit exception specification, set it
7964       // now. FIXME: It'd be nice to be able to create the right type to start
7965       // with, but the type needs to reference the destructor declaration.
7966       if (SemaRef.getLangOpts().CPlusPlus11)
7967         SemaRef.AdjustDestructorExceptionSpec(NewDD);
7968 
7969       IsVirtualOkay = true;
7970       return NewDD;
7971 
7972     } else {
7973       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7974       D.setInvalidType();
7975 
7976       // Create a FunctionDecl to satisfy the function definition parsing
7977       // code path.
7978       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
7979                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
7980                                   isInline,
7981                                   /*hasPrototype=*/true, isConstexpr);
7982     }
7983 
7984   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7985     if (!DC->isRecord()) {
7986       SemaRef.Diag(D.getIdentifierLoc(),
7987            diag::err_conv_function_not_member);
7988       return nullptr;
7989     }
7990 
7991     SemaRef.CheckConversionDeclarator(D, R, SC);
7992     IsVirtualOkay = true;
7993     return CXXConversionDecl::Create(
7994         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7995         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
7996 
7997   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7998     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7999 
8000     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8001                                          isExplicit, NameInfo, R, TInfo,
8002                                          D.getEndLoc());
8003   } else if (DC->isRecord()) {
8004     // If the name of the function is the same as the name of the record,
8005     // then this must be an invalid constructor that has a return type.
8006     // (The parser checks for a return type and makes the declarator a
8007     // constructor if it has no return type).
8008     if (Name.getAsIdentifierInfo() &&
8009         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8010       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8011         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8012         << SourceRange(D.getIdentifierLoc());
8013       return nullptr;
8014     }
8015 
8016     // This is a C++ method declaration.
8017     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8018         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8019         TInfo, SC, isInline, isConstexpr, SourceLocation());
8020     IsVirtualOkay = !Ret->isStatic();
8021     return Ret;
8022   } else {
8023     bool isFriend =
8024         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8025     if (!isFriend && SemaRef.CurContext->isRecord())
8026       return nullptr;
8027 
8028     // Determine whether the function was written with a
8029     // prototype. This true when:
8030     //   - we're in C++ (where every function has a prototype),
8031     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8032                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8033                                 isConstexpr);
8034   }
8035 }
8036 
8037 enum OpenCLParamType {
8038   ValidKernelParam,
8039   PtrPtrKernelParam,
8040   PtrKernelParam,
8041   InvalidAddrSpacePtrKernelParam,
8042   InvalidKernelParam,
8043   RecordKernelParam
8044 };
8045 
8046 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8047   // Size dependent types are just typedefs to normal integer types
8048   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8049   // integers other than by their names.
8050   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8051 
8052   // Remove typedefs one by one until we reach a typedef
8053   // for a size dependent type.
8054   QualType DesugaredTy = Ty;
8055   do {
8056     ArrayRef<StringRef> Names(SizeTypeNames);
8057     auto Match =
8058         std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8059     if (Names.end() != Match)
8060       return true;
8061 
8062     Ty = DesugaredTy;
8063     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8064   } while (DesugaredTy != Ty);
8065 
8066   return false;
8067 }
8068 
8069 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8070   if (PT->isPointerType()) {
8071     QualType PointeeType = PT->getPointeeType();
8072     if (PointeeType->isPointerType())
8073       return PtrPtrKernelParam;
8074     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8075         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8076         PointeeType.getAddressSpace() == LangAS::Default)
8077       return InvalidAddrSpacePtrKernelParam;
8078     return PtrKernelParam;
8079   }
8080 
8081   // OpenCL v1.2 s6.9.k:
8082   // Arguments to kernel functions in a program cannot be declared with the
8083   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8084   // uintptr_t or a struct and/or union that contain fields declared to be one
8085   // of these built-in scalar types.
8086   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8087     return InvalidKernelParam;
8088 
8089   if (PT->isImageType())
8090     return PtrKernelParam;
8091 
8092   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8093     return InvalidKernelParam;
8094 
8095   // OpenCL extension spec v1.2 s9.5:
8096   // This extension adds support for half scalar and vector types as built-in
8097   // types that can be used for arithmetic operations, conversions etc.
8098   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8099     return InvalidKernelParam;
8100 
8101   if (PT->isRecordType())
8102     return RecordKernelParam;
8103 
8104   // Look into an array argument to check if it has a forbidden type.
8105   if (PT->isArrayType()) {
8106     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8107     // Call ourself to check an underlying type of an array. Since the
8108     // getPointeeOrArrayElementType returns an innermost type which is not an
8109     // array, this recursive call only happens once.
8110     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8111   }
8112 
8113   return ValidKernelParam;
8114 }
8115 
8116 static void checkIsValidOpenCLKernelParameter(
8117   Sema &S,
8118   Declarator &D,
8119   ParmVarDecl *Param,
8120   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8121   QualType PT = Param->getType();
8122 
8123   // Cache the valid types we encounter to avoid rechecking structs that are
8124   // used again
8125   if (ValidTypes.count(PT.getTypePtr()))
8126     return;
8127 
8128   switch (getOpenCLKernelParameterType(S, PT)) {
8129   case PtrPtrKernelParam:
8130     // OpenCL v1.2 s6.9.a:
8131     // A kernel function argument cannot be declared as a
8132     // pointer to a pointer type.
8133     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8134     D.setInvalidType();
8135     return;
8136 
8137   case InvalidAddrSpacePtrKernelParam:
8138     // OpenCL v1.0 s6.5:
8139     // __kernel function arguments declared to be a pointer of a type can point
8140     // to one of the following address spaces only : __global, __local or
8141     // __constant.
8142     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8143     D.setInvalidType();
8144     return;
8145 
8146     // OpenCL v1.2 s6.9.k:
8147     // Arguments to kernel functions in a program cannot be declared with the
8148     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8149     // uintptr_t or a struct and/or union that contain fields declared to be
8150     // one of these built-in scalar types.
8151 
8152   case InvalidKernelParam:
8153     // OpenCL v1.2 s6.8 n:
8154     // A kernel function argument cannot be declared
8155     // of event_t type.
8156     // Do not diagnose half type since it is diagnosed as invalid argument
8157     // type for any function elsewhere.
8158     if (!PT->isHalfType()) {
8159       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8160 
8161       // Explain what typedefs are involved.
8162       const TypedefType *Typedef = nullptr;
8163       while ((Typedef = PT->getAs<TypedefType>())) {
8164         SourceLocation Loc = Typedef->getDecl()->getLocation();
8165         // SourceLocation may be invalid for a built-in type.
8166         if (Loc.isValid())
8167           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8168         PT = Typedef->desugar();
8169       }
8170     }
8171 
8172     D.setInvalidType();
8173     return;
8174 
8175   case PtrKernelParam:
8176   case ValidKernelParam:
8177     ValidTypes.insert(PT.getTypePtr());
8178     return;
8179 
8180   case RecordKernelParam:
8181     break;
8182   }
8183 
8184   // Track nested structs we will inspect
8185   SmallVector<const Decl *, 4> VisitStack;
8186 
8187   // Track where we are in the nested structs. Items will migrate from
8188   // VisitStack to HistoryStack as we do the DFS for bad field.
8189   SmallVector<const FieldDecl *, 4> HistoryStack;
8190   HistoryStack.push_back(nullptr);
8191 
8192   // At this point we already handled everything except of a RecordType or
8193   // an ArrayType of a RecordType.
8194   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8195   const RecordType *RecTy =
8196       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8197   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8198 
8199   VisitStack.push_back(RecTy->getDecl());
8200   assert(VisitStack.back() && "First decl null?");
8201 
8202   do {
8203     const Decl *Next = VisitStack.pop_back_val();
8204     if (!Next) {
8205       assert(!HistoryStack.empty());
8206       // Found a marker, we have gone up a level
8207       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8208         ValidTypes.insert(Hist->getType().getTypePtr());
8209 
8210       continue;
8211     }
8212 
8213     // Adds everything except the original parameter declaration (which is not a
8214     // field itself) to the history stack.
8215     const RecordDecl *RD;
8216     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8217       HistoryStack.push_back(Field);
8218 
8219       QualType FieldTy = Field->getType();
8220       // Other field types (known to be valid or invalid) are handled while we
8221       // walk around RecordDecl::fields().
8222       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8223              "Unexpected type.");
8224       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8225 
8226       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8227     } else {
8228       RD = cast<RecordDecl>(Next);
8229     }
8230 
8231     // Add a null marker so we know when we've gone back up a level
8232     VisitStack.push_back(nullptr);
8233 
8234     for (const auto *FD : RD->fields()) {
8235       QualType QT = FD->getType();
8236 
8237       if (ValidTypes.count(QT.getTypePtr()))
8238         continue;
8239 
8240       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8241       if (ParamType == ValidKernelParam)
8242         continue;
8243 
8244       if (ParamType == RecordKernelParam) {
8245         VisitStack.push_back(FD);
8246         continue;
8247       }
8248 
8249       // OpenCL v1.2 s6.9.p:
8250       // Arguments to kernel functions that are declared to be a struct or union
8251       // do not allow OpenCL objects to be passed as elements of the struct or
8252       // union.
8253       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8254           ParamType == InvalidAddrSpacePtrKernelParam) {
8255         S.Diag(Param->getLocation(),
8256                diag::err_record_with_pointers_kernel_param)
8257           << PT->isUnionType()
8258           << PT;
8259       } else {
8260         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8261       }
8262 
8263       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8264           << OrigRecDecl->getDeclName();
8265 
8266       // We have an error, now let's go back up through history and show where
8267       // the offending field came from
8268       for (ArrayRef<const FieldDecl *>::const_iterator
8269                I = HistoryStack.begin() + 1,
8270                E = HistoryStack.end();
8271            I != E; ++I) {
8272         const FieldDecl *OuterField = *I;
8273         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8274           << OuterField->getType();
8275       }
8276 
8277       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8278         << QT->isPointerType()
8279         << QT;
8280       D.setInvalidType();
8281       return;
8282     }
8283   } while (!VisitStack.empty());
8284 }
8285 
8286 /// Find the DeclContext in which a tag is implicitly declared if we see an
8287 /// elaborated type specifier in the specified context, and lookup finds
8288 /// nothing.
8289 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8290   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8291     DC = DC->getParent();
8292   return DC;
8293 }
8294 
8295 /// Find the Scope in which a tag is implicitly declared if we see an
8296 /// elaborated type specifier in the specified context, and lookup finds
8297 /// nothing.
8298 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8299   while (S->isClassScope() ||
8300          (LangOpts.CPlusPlus &&
8301           S->isFunctionPrototypeScope()) ||
8302          ((S->getFlags() & Scope::DeclScope) == 0) ||
8303          (S->getEntity() && S->getEntity()->isTransparentContext()))
8304     S = S->getParent();
8305   return S;
8306 }
8307 
8308 NamedDecl*
8309 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8310                               TypeSourceInfo *TInfo, LookupResult &Previous,
8311                               MultiTemplateParamsArg TemplateParamLists,
8312                               bool &AddToScope) {
8313   QualType R = TInfo->getType();
8314 
8315   assert(R->isFunctionType());
8316 
8317   // TODO: consider using NameInfo for diagnostic.
8318   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8319   DeclarationName Name = NameInfo.getName();
8320   StorageClass SC = getFunctionStorageClass(*this, D);
8321 
8322   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8323     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8324          diag::err_invalid_thread)
8325       << DeclSpec::getSpecifierName(TSCS);
8326 
8327   if (D.isFirstDeclarationOfMember())
8328     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8329                            D.getIdentifierLoc());
8330 
8331   bool isFriend = false;
8332   FunctionTemplateDecl *FunctionTemplate = nullptr;
8333   bool isMemberSpecialization = false;
8334   bool isFunctionTemplateSpecialization = false;
8335 
8336   bool isDependentClassScopeExplicitSpecialization = false;
8337   bool HasExplicitTemplateArgs = false;
8338   TemplateArgumentListInfo TemplateArgs;
8339 
8340   bool isVirtualOkay = false;
8341 
8342   DeclContext *OriginalDC = DC;
8343   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8344 
8345   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8346                                               isVirtualOkay);
8347   if (!NewFD) return nullptr;
8348 
8349   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8350     NewFD->setTopLevelDeclInObjCContainer();
8351 
8352   // Set the lexical context. If this is a function-scope declaration, or has a
8353   // C++ scope specifier, or is the object of a friend declaration, the lexical
8354   // context will be different from the semantic context.
8355   NewFD->setLexicalDeclContext(CurContext);
8356 
8357   if (IsLocalExternDecl)
8358     NewFD->setLocalExternDecl();
8359 
8360   if (getLangOpts().CPlusPlus) {
8361     bool isInline = D.getDeclSpec().isInlineSpecified();
8362     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8363     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8364     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8365     isFriend = D.getDeclSpec().isFriendSpecified();
8366     if (isFriend && !isInline && D.isFunctionDefinition()) {
8367       // C++ [class.friend]p5
8368       //   A function can be defined in a friend declaration of a
8369       //   class . . . . Such a function is implicitly inline.
8370       NewFD->setImplicitlyInline();
8371     }
8372 
8373     // If this is a method defined in an __interface, and is not a constructor
8374     // or an overloaded operator, then set the pure flag (isVirtual will already
8375     // return true).
8376     if (const CXXRecordDecl *Parent =
8377           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8378       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8379         NewFD->setPure(true);
8380 
8381       // C++ [class.union]p2
8382       //   A union can have member functions, but not virtual functions.
8383       if (isVirtual && Parent->isUnion())
8384         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8385     }
8386 
8387     SetNestedNameSpecifier(*this, NewFD, D);
8388     isMemberSpecialization = false;
8389     isFunctionTemplateSpecialization = false;
8390     if (D.isInvalidType())
8391       NewFD->setInvalidDecl();
8392 
8393     // Match up the template parameter lists with the scope specifier, then
8394     // determine whether we have a template or a template specialization.
8395     bool Invalid = false;
8396     if (TemplateParameterList *TemplateParams =
8397             MatchTemplateParametersToScopeSpecifier(
8398                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8399                 D.getCXXScopeSpec(),
8400                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8401                     ? D.getName().TemplateId
8402                     : nullptr,
8403                 TemplateParamLists, isFriend, isMemberSpecialization,
8404                 Invalid)) {
8405       if (TemplateParams->size() > 0) {
8406         // This is a function template
8407 
8408         // Check that we can declare a template here.
8409         if (CheckTemplateDeclScope(S, TemplateParams))
8410           NewFD->setInvalidDecl();
8411 
8412         // A destructor cannot be a template.
8413         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8414           Diag(NewFD->getLocation(), diag::err_destructor_template);
8415           NewFD->setInvalidDecl();
8416         }
8417 
8418         // If we're adding a template to a dependent context, we may need to
8419         // rebuilding some of the types used within the template parameter list,
8420         // now that we know what the current instantiation is.
8421         if (DC->isDependentContext()) {
8422           ContextRAII SavedContext(*this, DC);
8423           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8424             Invalid = true;
8425         }
8426 
8427         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8428                                                         NewFD->getLocation(),
8429                                                         Name, TemplateParams,
8430                                                         NewFD);
8431         FunctionTemplate->setLexicalDeclContext(CurContext);
8432         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8433 
8434         // For source fidelity, store the other template param lists.
8435         if (TemplateParamLists.size() > 1) {
8436           NewFD->setTemplateParameterListsInfo(Context,
8437                                                TemplateParamLists.drop_back(1));
8438         }
8439       } else {
8440         // This is a function template specialization.
8441         isFunctionTemplateSpecialization = true;
8442         // For source fidelity, store all the template param lists.
8443         if (TemplateParamLists.size() > 0)
8444           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8445 
8446         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8447         if (isFriend) {
8448           // We want to remove the "template<>", found here.
8449           SourceRange RemoveRange = TemplateParams->getSourceRange();
8450 
8451           // If we remove the template<> and the name is not a
8452           // template-id, we're actually silently creating a problem:
8453           // the friend declaration will refer to an untemplated decl,
8454           // and clearly the user wants a template specialization.  So
8455           // we need to insert '<>' after the name.
8456           SourceLocation InsertLoc;
8457           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8458             InsertLoc = D.getName().getSourceRange().getEnd();
8459             InsertLoc = getLocForEndOfToken(InsertLoc);
8460           }
8461 
8462           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8463             << Name << RemoveRange
8464             << FixItHint::CreateRemoval(RemoveRange)
8465             << FixItHint::CreateInsertion(InsertLoc, "<>");
8466         }
8467       }
8468     } else {
8469       // All template param lists were matched against the scope specifier:
8470       // this is NOT (an explicit specialization of) a template.
8471       if (TemplateParamLists.size() > 0)
8472         // For source fidelity, store all the template param lists.
8473         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8474     }
8475 
8476     if (Invalid) {
8477       NewFD->setInvalidDecl();
8478       if (FunctionTemplate)
8479         FunctionTemplate->setInvalidDecl();
8480     }
8481 
8482     // C++ [dcl.fct.spec]p5:
8483     //   The virtual specifier shall only be used in declarations of
8484     //   nonstatic class member functions that appear within a
8485     //   member-specification of a class declaration; see 10.3.
8486     //
8487     if (isVirtual && !NewFD->isInvalidDecl()) {
8488       if (!isVirtualOkay) {
8489         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8490              diag::err_virtual_non_function);
8491       } else if (!CurContext->isRecord()) {
8492         // 'virtual' was specified outside of the class.
8493         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8494              diag::err_virtual_out_of_class)
8495           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8496       } else if (NewFD->getDescribedFunctionTemplate()) {
8497         // C++ [temp.mem]p3:
8498         //  A member function template shall not be virtual.
8499         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8500              diag::err_virtual_member_function_template)
8501           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8502       } else {
8503         // Okay: Add virtual to the method.
8504         NewFD->setVirtualAsWritten(true);
8505       }
8506 
8507       if (getLangOpts().CPlusPlus14 &&
8508           NewFD->getReturnType()->isUndeducedType())
8509         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8510     }
8511 
8512     if (getLangOpts().CPlusPlus14 &&
8513         (NewFD->isDependentContext() ||
8514          (isFriend && CurContext->isDependentContext())) &&
8515         NewFD->getReturnType()->isUndeducedType()) {
8516       // If the function template is referenced directly (for instance, as a
8517       // member of the current instantiation), pretend it has a dependent type.
8518       // This is not really justified by the standard, but is the only sane
8519       // thing to do.
8520       // FIXME: For a friend function, we have not marked the function as being
8521       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8522       const FunctionProtoType *FPT =
8523           NewFD->getType()->castAs<FunctionProtoType>();
8524       QualType Result =
8525           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8526       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8527                                              FPT->getExtProtoInfo()));
8528     }
8529 
8530     // C++ [dcl.fct.spec]p3:
8531     //  The inline specifier shall not appear on a block scope function
8532     //  declaration.
8533     if (isInline && !NewFD->isInvalidDecl()) {
8534       if (CurContext->isFunctionOrMethod()) {
8535         // 'inline' is not allowed on block scope function declaration.
8536         Diag(D.getDeclSpec().getInlineSpecLoc(),
8537              diag::err_inline_declaration_block_scope) << Name
8538           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8539       }
8540     }
8541 
8542     // C++ [dcl.fct.spec]p6:
8543     //  The explicit specifier shall be used only in the declaration of a
8544     //  constructor or conversion function within its class definition;
8545     //  see 12.3.1 and 12.3.2.
8546     if (isExplicit && !NewFD->isInvalidDecl() &&
8547         !isa<CXXDeductionGuideDecl>(NewFD)) {
8548       if (!CurContext->isRecord()) {
8549         // 'explicit' was specified outside of the class.
8550         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8551              diag::err_explicit_out_of_class)
8552           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8553       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8554                  !isa<CXXConversionDecl>(NewFD)) {
8555         // 'explicit' was specified on a function that wasn't a constructor
8556         // or conversion function.
8557         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8558              diag::err_explicit_non_ctor_or_conv_function)
8559           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8560       }
8561     }
8562 
8563     if (isConstexpr) {
8564       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8565       // are implicitly inline.
8566       NewFD->setImplicitlyInline();
8567 
8568       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8569       // be either constructors or to return a literal type. Therefore,
8570       // destructors cannot be declared constexpr.
8571       if (isa<CXXDestructorDecl>(NewFD))
8572         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8573     }
8574 
8575     // If __module_private__ was specified, mark the function accordingly.
8576     if (D.getDeclSpec().isModulePrivateSpecified()) {
8577       if (isFunctionTemplateSpecialization) {
8578         SourceLocation ModulePrivateLoc
8579           = D.getDeclSpec().getModulePrivateSpecLoc();
8580         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8581           << 0
8582           << FixItHint::CreateRemoval(ModulePrivateLoc);
8583       } else {
8584         NewFD->setModulePrivate();
8585         if (FunctionTemplate)
8586           FunctionTemplate->setModulePrivate();
8587       }
8588     }
8589 
8590     if (isFriend) {
8591       if (FunctionTemplate) {
8592         FunctionTemplate->setObjectOfFriendDecl();
8593         FunctionTemplate->setAccess(AS_public);
8594       }
8595       NewFD->setObjectOfFriendDecl();
8596       NewFD->setAccess(AS_public);
8597     }
8598 
8599     // If a function is defined as defaulted or deleted, mark it as such now.
8600     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8601     // definition kind to FDK_Definition.
8602     switch (D.getFunctionDefinitionKind()) {
8603       case FDK_Declaration:
8604       case FDK_Definition:
8605         break;
8606 
8607       case FDK_Defaulted:
8608         NewFD->setDefaulted();
8609         break;
8610 
8611       case FDK_Deleted:
8612         NewFD->setDeletedAsWritten();
8613         break;
8614     }
8615 
8616     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8617         D.isFunctionDefinition()) {
8618       // C++ [class.mfct]p2:
8619       //   A member function may be defined (8.4) in its class definition, in
8620       //   which case it is an inline member function (7.1.2)
8621       NewFD->setImplicitlyInline();
8622     }
8623 
8624     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8625         !CurContext->isRecord()) {
8626       // C++ [class.static]p1:
8627       //   A data or function member of a class may be declared static
8628       //   in a class definition, in which case it is a static member of
8629       //   the class.
8630 
8631       // Complain about the 'static' specifier if it's on an out-of-line
8632       // member function definition.
8633 
8634       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8635       // member function template declaration, warn about this.
8636       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8637            NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
8638            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8639         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8640     }
8641 
8642     // C++11 [except.spec]p15:
8643     //   A deallocation function with no exception-specification is treated
8644     //   as if it were specified with noexcept(true).
8645     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8646     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8647          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8648         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8649       NewFD->setType(Context.getFunctionType(
8650           FPT->getReturnType(), FPT->getParamTypes(),
8651           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8652   }
8653 
8654   // Filter out previous declarations that don't match the scope.
8655   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8656                        D.getCXXScopeSpec().isNotEmpty() ||
8657                        isMemberSpecialization ||
8658                        isFunctionTemplateSpecialization);
8659 
8660   // Handle GNU asm-label extension (encoded as an attribute).
8661   if (Expr *E = (Expr*) D.getAsmLabel()) {
8662     // The parser guarantees this is a string.
8663     StringLiteral *SE = cast<StringLiteral>(E);
8664     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8665                                                 SE->getString(), 0));
8666   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8667     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8668       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8669     if (I != ExtnameUndeclaredIdentifiers.end()) {
8670       if (isDeclExternC(NewFD)) {
8671         NewFD->addAttr(I->second);
8672         ExtnameUndeclaredIdentifiers.erase(I);
8673       } else
8674         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8675             << /*Variable*/0 << NewFD;
8676     }
8677   }
8678 
8679   // Copy the parameter declarations from the declarator D to the function
8680   // declaration NewFD, if they are available.  First scavenge them into Params.
8681   SmallVector<ParmVarDecl*, 16> Params;
8682   unsigned FTIIdx;
8683   if (D.isFunctionDeclarator(FTIIdx)) {
8684     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8685 
8686     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8687     // function that takes no arguments, not a function that takes a
8688     // single void argument.
8689     // We let through "const void" here because Sema::GetTypeForDeclarator
8690     // already checks for that case.
8691     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8692       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8693         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8694         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8695         Param->setDeclContext(NewFD);
8696         Params.push_back(Param);
8697 
8698         if (Param->isInvalidDecl())
8699           NewFD->setInvalidDecl();
8700       }
8701     }
8702 
8703     if (!getLangOpts().CPlusPlus) {
8704       // In C, find all the tag declarations from the prototype and move them
8705       // into the function DeclContext. Remove them from the surrounding tag
8706       // injection context of the function, which is typically but not always
8707       // the TU.
8708       DeclContext *PrototypeTagContext =
8709           getTagInjectionContext(NewFD->getLexicalDeclContext());
8710       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8711         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8712 
8713         // We don't want to reparent enumerators. Look at their parent enum
8714         // instead.
8715         if (!TD) {
8716           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8717             TD = cast<EnumDecl>(ECD->getDeclContext());
8718         }
8719         if (!TD)
8720           continue;
8721         DeclContext *TagDC = TD->getLexicalDeclContext();
8722         if (!TagDC->containsDecl(TD))
8723           continue;
8724         TagDC->removeDecl(TD);
8725         TD->setDeclContext(NewFD);
8726         NewFD->addDecl(TD);
8727 
8728         // Preserve the lexical DeclContext if it is not the surrounding tag
8729         // injection context of the FD. In this example, the semantic context of
8730         // E will be f and the lexical context will be S, while both the
8731         // semantic and lexical contexts of S will be f:
8732         //   void f(struct S { enum E { a } f; } s);
8733         if (TagDC != PrototypeTagContext)
8734           TD->setLexicalDeclContext(TagDC);
8735       }
8736     }
8737   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8738     // When we're declaring a function with a typedef, typeof, etc as in the
8739     // following example, we'll need to synthesize (unnamed)
8740     // parameters for use in the declaration.
8741     //
8742     // @code
8743     // typedef void fn(int);
8744     // fn f;
8745     // @endcode
8746 
8747     // Synthesize a parameter for each argument type.
8748     for (const auto &AI : FT->param_types()) {
8749       ParmVarDecl *Param =
8750           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8751       Param->setScopeInfo(0, Params.size());
8752       Params.push_back(Param);
8753     }
8754   } else {
8755     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8756            "Should not need args for typedef of non-prototype fn");
8757   }
8758 
8759   // Finally, we know we have the right number of parameters, install them.
8760   NewFD->setParams(Params);
8761 
8762   if (D.getDeclSpec().isNoreturnSpecified())
8763     NewFD->addAttr(
8764         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8765                                        Context, 0));
8766 
8767   // Functions returning a variably modified type violate C99 6.7.5.2p2
8768   // because all functions have linkage.
8769   if (!NewFD->isInvalidDecl() &&
8770       NewFD->getReturnType()->isVariablyModifiedType()) {
8771     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8772     NewFD->setInvalidDecl();
8773   }
8774 
8775   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8776   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8777       !NewFD->hasAttr<SectionAttr>()) {
8778     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8779                                                  PragmaClangTextSection.SectionName,
8780                                                  PragmaClangTextSection.PragmaLocation));
8781   }
8782 
8783   // Apply an implicit SectionAttr if #pragma code_seg is active.
8784   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8785       !NewFD->hasAttr<SectionAttr>()) {
8786     NewFD->addAttr(
8787         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8788                                     CodeSegStack.CurrentValue->getString(),
8789                                     CodeSegStack.CurrentPragmaLocation));
8790     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8791                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8792                          ASTContext::PSF_Read,
8793                      NewFD))
8794       NewFD->dropAttr<SectionAttr>();
8795   }
8796 
8797   // Apply an implicit CodeSegAttr from class declspec or
8798   // apply an implicit SectionAttr from #pragma code_seg if active.
8799   if (!NewFD->hasAttr<CodeSegAttr>()) {
8800     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8801                                                                  D.isFunctionDefinition())) {
8802       NewFD->addAttr(SAttr);
8803     }
8804   }
8805 
8806   // Handle attributes.
8807   ProcessDeclAttributes(S, NewFD, D);
8808 
8809   if (getLangOpts().OpenCL) {
8810     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8811     // type declaration will generate a compilation error.
8812     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8813     if (AddressSpace != LangAS::Default) {
8814       Diag(NewFD->getLocation(),
8815            diag::err_opencl_return_value_with_address_space);
8816       NewFD->setInvalidDecl();
8817     }
8818   }
8819 
8820   if (!getLangOpts().CPlusPlus) {
8821     // Perform semantic checking on the function declaration.
8822     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8823       CheckMain(NewFD, D.getDeclSpec());
8824 
8825     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8826       CheckMSVCRTEntryPoint(NewFD);
8827 
8828     if (!NewFD->isInvalidDecl())
8829       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8830                                                   isMemberSpecialization));
8831     else if (!Previous.empty())
8832       // Recover gracefully from an invalid redeclaration.
8833       D.setRedeclaration(true);
8834     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8835             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8836            "previous declaration set still overloaded");
8837 
8838     // Diagnose no-prototype function declarations with calling conventions that
8839     // don't support variadic calls. Only do this in C and do it after merging
8840     // possibly prototyped redeclarations.
8841     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8842     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8843       CallingConv CC = FT->getExtInfo().getCC();
8844       if (!supportsVariadicCall(CC)) {
8845         // Windows system headers sometimes accidentally use stdcall without
8846         // (void) parameters, so we relax this to a warning.
8847         int DiagID =
8848             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8849         Diag(NewFD->getLocation(), DiagID)
8850             << FunctionType::getNameForCallConv(CC);
8851       }
8852     }
8853   } else {
8854     // C++11 [replacement.functions]p3:
8855     //  The program's definitions shall not be specified as inline.
8856     //
8857     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8858     //
8859     // Suppress the diagnostic if the function is __attribute__((used)), since
8860     // that forces an external definition to be emitted.
8861     if (D.getDeclSpec().isInlineSpecified() &&
8862         NewFD->isReplaceableGlobalAllocationFunction() &&
8863         !NewFD->hasAttr<UsedAttr>())
8864       Diag(D.getDeclSpec().getInlineSpecLoc(),
8865            diag::ext_operator_new_delete_declared_inline)
8866         << NewFD->getDeclName();
8867 
8868     // If the declarator is a template-id, translate the parser's template
8869     // argument list into our AST format.
8870     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8871       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8872       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8873       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8874       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8875                                          TemplateId->NumArgs);
8876       translateTemplateArguments(TemplateArgsPtr,
8877                                  TemplateArgs);
8878 
8879       HasExplicitTemplateArgs = true;
8880 
8881       if (NewFD->isInvalidDecl()) {
8882         HasExplicitTemplateArgs = false;
8883       } else if (FunctionTemplate) {
8884         // Function template with explicit template arguments.
8885         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8886           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8887 
8888         HasExplicitTemplateArgs = false;
8889       } else {
8890         assert((isFunctionTemplateSpecialization ||
8891                 D.getDeclSpec().isFriendSpecified()) &&
8892                "should have a 'template<>' for this decl");
8893         // "friend void foo<>(int);" is an implicit specialization decl.
8894         isFunctionTemplateSpecialization = true;
8895       }
8896     } else if (isFriend && isFunctionTemplateSpecialization) {
8897       // This combination is only possible in a recovery case;  the user
8898       // wrote something like:
8899       //   template <> friend void foo(int);
8900       // which we're recovering from as if the user had written:
8901       //   friend void foo<>(int);
8902       // Go ahead and fake up a template id.
8903       HasExplicitTemplateArgs = true;
8904       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8905       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8906     }
8907 
8908     // We do not add HD attributes to specializations here because
8909     // they may have different constexpr-ness compared to their
8910     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8911     // may end up with different effective targets. Instead, a
8912     // specialization inherits its target attributes from its template
8913     // in the CheckFunctionTemplateSpecialization() call below.
8914     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8915       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8916 
8917     // If it's a friend (and only if it's a friend), it's possible
8918     // that either the specialized function type or the specialized
8919     // template is dependent, and therefore matching will fail.  In
8920     // this case, don't check the specialization yet.
8921     bool InstantiationDependent = false;
8922     if (isFunctionTemplateSpecialization && isFriend &&
8923         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8924          TemplateSpecializationType::anyDependentTemplateArguments(
8925             TemplateArgs,
8926             InstantiationDependent))) {
8927       assert(HasExplicitTemplateArgs &&
8928              "friend function specialization without template args");
8929       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8930                                                        Previous))
8931         NewFD->setInvalidDecl();
8932     } else if (isFunctionTemplateSpecialization) {
8933       if (CurContext->isDependentContext() && CurContext->isRecord()
8934           && !isFriend) {
8935         isDependentClassScopeExplicitSpecialization = true;
8936       } else if (!NewFD->isInvalidDecl() &&
8937                  CheckFunctionTemplateSpecialization(
8938                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8939                      Previous))
8940         NewFD->setInvalidDecl();
8941 
8942       // C++ [dcl.stc]p1:
8943       //   A storage-class-specifier shall not be specified in an explicit
8944       //   specialization (14.7.3)
8945       FunctionTemplateSpecializationInfo *Info =
8946           NewFD->getTemplateSpecializationInfo();
8947       if (Info && SC != SC_None) {
8948         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8949           Diag(NewFD->getLocation(),
8950                diag::err_explicit_specialization_inconsistent_storage_class)
8951             << SC
8952             << FixItHint::CreateRemoval(
8953                                       D.getDeclSpec().getStorageClassSpecLoc());
8954 
8955         else
8956           Diag(NewFD->getLocation(),
8957                diag::ext_explicit_specialization_storage_class)
8958             << FixItHint::CreateRemoval(
8959                                       D.getDeclSpec().getStorageClassSpecLoc());
8960       }
8961     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8962       if (CheckMemberSpecialization(NewFD, Previous))
8963           NewFD->setInvalidDecl();
8964     }
8965 
8966     // Perform semantic checking on the function declaration.
8967     if (!isDependentClassScopeExplicitSpecialization) {
8968       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8969         CheckMain(NewFD, D.getDeclSpec());
8970 
8971       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8972         CheckMSVCRTEntryPoint(NewFD);
8973 
8974       if (!NewFD->isInvalidDecl())
8975         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8976                                                     isMemberSpecialization));
8977       else if (!Previous.empty())
8978         // Recover gracefully from an invalid redeclaration.
8979         D.setRedeclaration(true);
8980     }
8981 
8982     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8983             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8984            "previous declaration set still overloaded");
8985 
8986     NamedDecl *PrincipalDecl = (FunctionTemplate
8987                                 ? cast<NamedDecl>(FunctionTemplate)
8988                                 : NewFD);
8989 
8990     if (isFriend && NewFD->getPreviousDecl()) {
8991       AccessSpecifier Access = AS_public;
8992       if (!NewFD->isInvalidDecl())
8993         Access = NewFD->getPreviousDecl()->getAccess();
8994 
8995       NewFD->setAccess(Access);
8996       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8997     }
8998 
8999     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9000         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9001       PrincipalDecl->setNonMemberOperator();
9002 
9003     // If we have a function template, check the template parameter
9004     // list. This will check and merge default template arguments.
9005     if (FunctionTemplate) {
9006       FunctionTemplateDecl *PrevTemplate =
9007                                      FunctionTemplate->getPreviousDecl();
9008       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9009                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9010                                     : nullptr,
9011                             D.getDeclSpec().isFriendSpecified()
9012                               ? (D.isFunctionDefinition()
9013                                    ? TPC_FriendFunctionTemplateDefinition
9014                                    : TPC_FriendFunctionTemplate)
9015                               : (D.getCXXScopeSpec().isSet() &&
9016                                  DC && DC->isRecord() &&
9017                                  DC->isDependentContext())
9018                                   ? TPC_ClassTemplateMember
9019                                   : TPC_FunctionTemplate);
9020     }
9021 
9022     if (NewFD->isInvalidDecl()) {
9023       // Ignore all the rest of this.
9024     } else if (!D.isRedeclaration()) {
9025       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9026                                        AddToScope };
9027       // Fake up an access specifier if it's supposed to be a class member.
9028       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9029         NewFD->setAccess(AS_public);
9030 
9031       // Qualified decls generally require a previous declaration.
9032       if (D.getCXXScopeSpec().isSet()) {
9033         // ...with the major exception of templated-scope or
9034         // dependent-scope friend declarations.
9035 
9036         // TODO: we currently also suppress this check in dependent
9037         // contexts because (1) the parameter depth will be off when
9038         // matching friend templates and (2) we might actually be
9039         // selecting a friend based on a dependent factor.  But there
9040         // are situations where these conditions don't apply and we
9041         // can actually do this check immediately.
9042         //
9043         // Unless the scope is dependent, it's always an error if qualified
9044         // redeclaration lookup found nothing at all. Diagnose that now;
9045         // nothing will diagnose that error later.
9046         if (isFriend &&
9047             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9048              (!Previous.empty() && (TemplateParamLists.size() ||
9049                                     CurContext->isDependentContext())))) {
9050           // ignore these
9051         } else {
9052           // The user tried to provide an out-of-line definition for a
9053           // function that is a member of a class or namespace, but there
9054           // was no such member function declared (C++ [class.mfct]p2,
9055           // C++ [namespace.memdef]p2). For example:
9056           //
9057           // class X {
9058           //   void f() const;
9059           // };
9060           //
9061           // void X::f() { } // ill-formed
9062           //
9063           // Complain about this problem, and attempt to suggest close
9064           // matches (e.g., those that differ only in cv-qualifiers and
9065           // whether the parameter types are references).
9066 
9067           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9068                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9069             AddToScope = ExtraArgs.AddToScope;
9070             return Result;
9071           }
9072         }
9073 
9074         // Unqualified local friend declarations are required to resolve
9075         // to something.
9076       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9077         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9078                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9079           AddToScope = ExtraArgs.AddToScope;
9080           return Result;
9081         }
9082       }
9083     } else if (!D.isFunctionDefinition() &&
9084                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9085                !isFriend && !isFunctionTemplateSpecialization &&
9086                !isMemberSpecialization) {
9087       // An out-of-line member function declaration must also be a
9088       // definition (C++ [class.mfct]p2).
9089       // Note that this is not the case for explicit specializations of
9090       // function templates or member functions of class templates, per
9091       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9092       // extension for compatibility with old SWIG code which likes to
9093       // generate them.
9094       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9095         << D.getCXXScopeSpec().getRange();
9096     }
9097   }
9098 
9099   ProcessPragmaWeak(S, NewFD);
9100   checkAttributesAfterMerging(*this, *NewFD);
9101 
9102   AddKnownFunctionAttributes(NewFD);
9103 
9104   if (NewFD->hasAttr<OverloadableAttr>() &&
9105       !NewFD->getType()->getAs<FunctionProtoType>()) {
9106     Diag(NewFD->getLocation(),
9107          diag::err_attribute_overloadable_no_prototype)
9108       << NewFD;
9109 
9110     // Turn this into a variadic function with no parameters.
9111     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9112     FunctionProtoType::ExtProtoInfo EPI(
9113         Context.getDefaultCallingConvention(true, false));
9114     EPI.Variadic = true;
9115     EPI.ExtInfo = FT->getExtInfo();
9116 
9117     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9118     NewFD->setType(R);
9119   }
9120 
9121   // If there's a #pragma GCC visibility in scope, and this isn't a class
9122   // member, set the visibility of this function.
9123   if (!DC->isRecord() && NewFD->isExternallyVisible())
9124     AddPushedVisibilityAttribute(NewFD);
9125 
9126   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9127   // marking the function.
9128   AddCFAuditedAttribute(NewFD);
9129 
9130   // If this is a function definition, check if we have to apply optnone due to
9131   // a pragma.
9132   if(D.isFunctionDefinition())
9133     AddRangeBasedOptnone(NewFD);
9134 
9135   // If this is the first declaration of an extern C variable, update
9136   // the map of such variables.
9137   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9138       isIncompleteDeclExternC(*this, NewFD))
9139     RegisterLocallyScopedExternCDecl(NewFD, S);
9140 
9141   // Set this FunctionDecl's range up to the right paren.
9142   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9143 
9144   if (D.isRedeclaration() && !Previous.empty()) {
9145     NamedDecl *Prev = Previous.getRepresentativeDecl();
9146     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9147                                    isMemberSpecialization ||
9148                                        isFunctionTemplateSpecialization,
9149                                    D.isFunctionDefinition());
9150   }
9151 
9152   if (getLangOpts().CUDA) {
9153     IdentifierInfo *II = NewFD->getIdentifier();
9154     if (II && II->isStr(getCudaConfigureFuncName()) &&
9155         !NewFD->isInvalidDecl() &&
9156         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9157       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9158         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9159             << getCudaConfigureFuncName();
9160       Context.setcudaConfigureCallDecl(NewFD);
9161     }
9162 
9163     // Variadic functions, other than a *declaration* of printf, are not allowed
9164     // in device-side CUDA code, unless someone passed
9165     // -fcuda-allow-variadic-functions.
9166     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9167         (NewFD->hasAttr<CUDADeviceAttr>() ||
9168          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9169         !(II && II->isStr("printf") && NewFD->isExternC() &&
9170           !D.isFunctionDefinition())) {
9171       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9172     }
9173   }
9174 
9175   MarkUnusedFileScopedDecl(NewFD);
9176 
9177   if (getLangOpts().CPlusPlus) {
9178     if (FunctionTemplate) {
9179       if (NewFD->isInvalidDecl())
9180         FunctionTemplate->setInvalidDecl();
9181       return FunctionTemplate;
9182     }
9183 
9184     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9185       CompleteMemberSpecialization(NewFD, Previous);
9186   }
9187 
9188   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9189     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9190     if ((getLangOpts().OpenCLVersion >= 120)
9191         && (SC == SC_Static)) {
9192       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9193       D.setInvalidType();
9194     }
9195 
9196     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9197     if (!NewFD->getReturnType()->isVoidType()) {
9198       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9199       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9200           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9201                                 : FixItHint());
9202       D.setInvalidType();
9203     }
9204 
9205     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9206     for (auto Param : NewFD->parameters())
9207       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9208   }
9209   for (const ParmVarDecl *Param : NewFD->parameters()) {
9210     QualType PT = Param->getType();
9211 
9212     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9213     // types.
9214     if (getLangOpts().OpenCLVersion >= 200) {
9215       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9216         QualType ElemTy = PipeTy->getElementType();
9217           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9218             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9219             D.setInvalidType();
9220           }
9221       }
9222     }
9223   }
9224 
9225   // Here we have an function template explicit specialization at class scope.
9226   // The actual specialization will be postponed to template instatiation
9227   // time via the ClassScopeFunctionSpecializationDecl node.
9228   if (isDependentClassScopeExplicitSpecialization) {
9229     ClassScopeFunctionSpecializationDecl *NewSpec =
9230                          ClassScopeFunctionSpecializationDecl::Create(
9231                                 Context, CurContext, NewFD->getLocation(),
9232                                 cast<CXXMethodDecl>(NewFD),
9233                                 HasExplicitTemplateArgs, TemplateArgs);
9234     CurContext->addDecl(NewSpec);
9235     AddToScope = false;
9236   }
9237 
9238   // Diagnose availability attributes. Availability cannot be used on functions
9239   // that are run during load/unload.
9240   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9241     if (NewFD->hasAttr<ConstructorAttr>()) {
9242       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9243           << 1;
9244       NewFD->dropAttr<AvailabilityAttr>();
9245     }
9246     if (NewFD->hasAttr<DestructorAttr>()) {
9247       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9248           << 2;
9249       NewFD->dropAttr<AvailabilityAttr>();
9250     }
9251   }
9252 
9253   return NewFD;
9254 }
9255 
9256 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9257 /// when __declspec(code_seg) "is applied to a class, all member functions of
9258 /// the class and nested classes -- this includes compiler-generated special
9259 /// member functions -- are put in the specified segment."
9260 /// The actual behavior is a little more complicated. The Microsoft compiler
9261 /// won't check outer classes if there is an active value from #pragma code_seg.
9262 /// The CodeSeg is always applied from the direct parent but only from outer
9263 /// classes when the #pragma code_seg stack is empty. See:
9264 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9265 /// available since MS has removed the page.
9266 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9267   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9268   if (!Method)
9269     return nullptr;
9270   const CXXRecordDecl *Parent = Method->getParent();
9271   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9272     Attr *NewAttr = SAttr->clone(S.getASTContext());
9273     NewAttr->setImplicit(true);
9274     return NewAttr;
9275   }
9276 
9277   // The Microsoft compiler won't check outer classes for the CodeSeg
9278   // when the #pragma code_seg stack is active.
9279   if (S.CodeSegStack.CurrentValue)
9280    return nullptr;
9281 
9282   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9283     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9284       Attr *NewAttr = SAttr->clone(S.getASTContext());
9285       NewAttr->setImplicit(true);
9286       return NewAttr;
9287     }
9288   }
9289   return nullptr;
9290 }
9291 
9292 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9293 /// containing class. Otherwise it will return implicit SectionAttr if the
9294 /// function is a definition and there is an active value on CodeSegStack
9295 /// (from the current #pragma code-seg value).
9296 ///
9297 /// \param FD Function being declared.
9298 /// \param IsDefinition Whether it is a definition or just a declarartion.
9299 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9300 ///          nullptr if no attribute should be added.
9301 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9302                                                        bool IsDefinition) {
9303   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9304     return A;
9305   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9306       CodeSegStack.CurrentValue) {
9307     return SectionAttr::CreateImplicit(getASTContext(),
9308                                        SectionAttr::Declspec_allocate,
9309                                        CodeSegStack.CurrentValue->getString(),
9310                                        CodeSegStack.CurrentPragmaLocation);
9311   }
9312   return nullptr;
9313 }
9314 
9315 /// Determines if we can perform a correct type check for \p D as a
9316 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9317 /// best-effort check.
9318 ///
9319 /// \param NewD The new declaration.
9320 /// \param OldD The old declaration.
9321 /// \param NewT The portion of the type of the new declaration to check.
9322 /// \param OldT The portion of the type of the old declaration to check.
9323 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9324                                           QualType NewT, QualType OldT) {
9325   if (!NewD->getLexicalDeclContext()->isDependentContext())
9326     return true;
9327 
9328   // For dependently-typed local extern declarations and friends, we can't
9329   // perform a correct type check in general until instantiation:
9330   //
9331   //   int f();
9332   //   template<typename T> void g() { T f(); }
9333   //
9334   // (valid if g() is only instantiated with T = int).
9335   if (NewT->isDependentType() &&
9336       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9337     return false;
9338 
9339   // Similarly, if the previous declaration was a dependent local extern
9340   // declaration, we don't really know its type yet.
9341   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9342     return false;
9343 
9344   return true;
9345 }
9346 
9347 /// Checks if the new declaration declared in dependent context must be
9348 /// put in the same redeclaration chain as the specified declaration.
9349 ///
9350 /// \param D Declaration that is checked.
9351 /// \param PrevDecl Previous declaration found with proper lookup method for the
9352 ///                 same declaration name.
9353 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9354 ///          belongs to.
9355 ///
9356 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9357   if (!D->getLexicalDeclContext()->isDependentContext())
9358     return true;
9359 
9360   // Don't chain dependent friend function definitions until instantiation, to
9361   // permit cases like
9362   //
9363   //   void func();
9364   //   template<typename T> class C1 { friend void func() {} };
9365   //   template<typename T> class C2 { friend void func() {} };
9366   //
9367   // ... which is valid if only one of C1 and C2 is ever instantiated.
9368   //
9369   // FIXME: This need only apply to function definitions. For now, we proxy
9370   // this by checking for a file-scope function. We do not want this to apply
9371   // to friend declarations nominating member functions, because that gets in
9372   // the way of access checks.
9373   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9374     return false;
9375 
9376   auto *VD = dyn_cast<ValueDecl>(D);
9377   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9378   return !VD || !PrevVD ||
9379          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9380                                         PrevVD->getType());
9381 }
9382 
9383 /// Check the target attribute of the function for MultiVersion
9384 /// validity.
9385 ///
9386 /// Returns true if there was an error, false otherwise.
9387 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9388   const auto *TA = FD->getAttr<TargetAttr>();
9389   assert(TA && "MultiVersion Candidate requires a target attribute");
9390   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9391   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9392   enum ErrType { Feature = 0, Architecture = 1 };
9393 
9394   if (!ParseInfo.Architecture.empty() &&
9395       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9396     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9397         << Architecture << ParseInfo.Architecture;
9398     return true;
9399   }
9400 
9401   for (const auto &Feat : ParseInfo.Features) {
9402     auto BareFeat = StringRef{Feat}.substr(1);
9403     if (Feat[0] == '-') {
9404       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9405           << Feature << ("no-" + BareFeat).str();
9406       return true;
9407     }
9408 
9409     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9410         !TargetInfo.isValidFeatureName(BareFeat)) {
9411       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9412           << Feature << BareFeat;
9413       return true;
9414     }
9415   }
9416   return false;
9417 }
9418 
9419 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9420                                          MultiVersionKind MVType) {
9421   for (const Attr *A : FD->attrs()) {
9422     switch (A->getKind()) {
9423     case attr::CPUDispatch:
9424     case attr::CPUSpecific:
9425       if (MVType != MultiVersionKind::CPUDispatch &&
9426           MVType != MultiVersionKind::CPUSpecific)
9427         return true;
9428       break;
9429     case attr::Target:
9430       if (MVType != MultiVersionKind::Target)
9431         return true;
9432       break;
9433     default:
9434       return true;
9435     }
9436   }
9437   return false;
9438 }
9439 
9440 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9441                                              const FunctionDecl *NewFD,
9442                                              bool CausesMV,
9443                                              MultiVersionKind MVType) {
9444   enum DoesntSupport {
9445     FuncTemplates = 0,
9446     VirtFuncs = 1,
9447     DeducedReturn = 2,
9448     Constructors = 3,
9449     Destructors = 4,
9450     DeletedFuncs = 5,
9451     DefaultedFuncs = 6,
9452     ConstexprFuncs = 7,
9453   };
9454   enum Different {
9455     CallingConv = 0,
9456     ReturnType = 1,
9457     ConstexprSpec = 2,
9458     InlineSpec = 3,
9459     StorageClass = 4,
9460     Linkage = 5
9461   };
9462 
9463   bool IsCPUSpecificCPUDispatchMVType =
9464       MVType == MultiVersionKind::CPUDispatch ||
9465       MVType == MultiVersionKind::CPUSpecific;
9466 
9467   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9468     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9469     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9470     return true;
9471   }
9472 
9473   if (!NewFD->getType()->getAs<FunctionProtoType>())
9474     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9475 
9476   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9477     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9478     if (OldFD)
9479       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9480     return true;
9481   }
9482 
9483   // For now, disallow all other attributes.  These should be opt-in, but
9484   // an analysis of all of them is a future FIXME.
9485   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9486     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9487         << IsCPUSpecificCPUDispatchMVType;
9488     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9489     return true;
9490   }
9491 
9492   if (HasNonMultiVersionAttributes(NewFD, MVType))
9493     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9494            << IsCPUSpecificCPUDispatchMVType;
9495 
9496   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9497     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9498            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9499 
9500   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9501     if (NewCXXFD->isVirtual())
9502       return S.Diag(NewCXXFD->getLocation(),
9503                     diag::err_multiversion_doesnt_support)
9504              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9505 
9506     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9507       return S.Diag(NewCXXCtor->getLocation(),
9508                     diag::err_multiversion_doesnt_support)
9509              << IsCPUSpecificCPUDispatchMVType << Constructors;
9510 
9511     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9512       return S.Diag(NewCXXDtor->getLocation(),
9513                     diag::err_multiversion_doesnt_support)
9514              << IsCPUSpecificCPUDispatchMVType << Destructors;
9515   }
9516 
9517   if (NewFD->isDeleted())
9518     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9519            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9520 
9521   if (NewFD->isDefaulted())
9522     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9523            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9524 
9525   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9526                                MVType == MultiVersionKind::CPUSpecific))
9527     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9528            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9529 
9530   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9531   const auto *NewType = cast<FunctionType>(NewQType);
9532   QualType NewReturnType = NewType->getReturnType();
9533 
9534   if (NewReturnType->isUndeducedType())
9535     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9536            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9537 
9538   // Only allow transition to MultiVersion if it hasn't been used.
9539   if (OldFD && CausesMV && OldFD->isUsed(false))
9540     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9541 
9542   // Ensure the return type is identical.
9543   if (OldFD) {
9544     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9545     const auto *OldType = cast<FunctionType>(OldQType);
9546     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9547     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9548 
9549     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9550       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9551              << CallingConv;
9552 
9553     QualType OldReturnType = OldType->getReturnType();
9554 
9555     if (OldReturnType != NewReturnType)
9556       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9557              << ReturnType;
9558 
9559     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9560       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9561              << ConstexprSpec;
9562 
9563     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9564       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9565              << InlineSpec;
9566 
9567     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9568       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9569              << StorageClass;
9570 
9571     if (OldFD->isExternC() != NewFD->isExternC())
9572       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9573              << Linkage;
9574 
9575     if (S.CheckEquivalentExceptionSpec(
9576             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9577             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9578       return true;
9579   }
9580   return false;
9581 }
9582 
9583 /// Check the validity of a multiversion function declaration that is the
9584 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9585 ///
9586 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9587 ///
9588 /// Returns true if there was an error, false otherwise.
9589 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9590                                            MultiVersionKind MVType,
9591                                            const TargetAttr *TA,
9592                                            const CPUDispatchAttr *CPUDisp,
9593                                            const CPUSpecificAttr *CPUSpec) {
9594   assert(MVType != MultiVersionKind::None &&
9595          "Function lacks multiversion attribute");
9596 
9597   // Target only causes MV if it is default, otherwise this is a normal
9598   // function.
9599   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9600     return false;
9601 
9602   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9603     FD->setInvalidDecl();
9604     return true;
9605   }
9606 
9607   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9608     FD->setInvalidDecl();
9609     return true;
9610   }
9611 
9612   FD->setIsMultiVersion();
9613   return false;
9614 }
9615 
9616 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9617   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9618     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9619       return true;
9620   }
9621 
9622   return false;
9623 }
9624 
9625 static bool CheckTargetCausesMultiVersioning(
9626     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9627     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9628     LookupResult &Previous) {
9629   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9630   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9631   // Sort order doesn't matter, it just needs to be consistent.
9632   llvm::sort(NewParsed.Features);
9633 
9634   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9635   // to change, this is a simple redeclaration.
9636   if (!NewTA->isDefaultVersion() &&
9637       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9638     return false;
9639 
9640   // Otherwise, this decl causes MultiVersioning.
9641   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9642     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9643     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9644     NewFD->setInvalidDecl();
9645     return true;
9646   }
9647 
9648   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9649                                        MultiVersionKind::Target)) {
9650     NewFD->setInvalidDecl();
9651     return true;
9652   }
9653 
9654   if (CheckMultiVersionValue(S, NewFD)) {
9655     NewFD->setInvalidDecl();
9656     return true;
9657   }
9658 
9659   // If this is 'default', permit the forward declaration.
9660   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9661     Redeclaration = true;
9662     OldDecl = OldFD;
9663     OldFD->setIsMultiVersion();
9664     NewFD->setIsMultiVersion();
9665     return false;
9666   }
9667 
9668   if (CheckMultiVersionValue(S, OldFD)) {
9669     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9670     NewFD->setInvalidDecl();
9671     return true;
9672   }
9673 
9674   TargetAttr::ParsedTargetAttr OldParsed =
9675       OldTA->parse(std::less<std::string>());
9676 
9677   if (OldParsed == NewParsed) {
9678     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9679     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9680     NewFD->setInvalidDecl();
9681     return true;
9682   }
9683 
9684   for (const auto *FD : OldFD->redecls()) {
9685     const auto *CurTA = FD->getAttr<TargetAttr>();
9686     // We allow forward declarations before ANY multiversioning attributes, but
9687     // nothing after the fact.
9688     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9689         (!CurTA || CurTA->isInherited())) {
9690       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9691           << 0;
9692       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9693       NewFD->setInvalidDecl();
9694       return true;
9695     }
9696   }
9697 
9698   OldFD->setIsMultiVersion();
9699   NewFD->setIsMultiVersion();
9700   Redeclaration = false;
9701   MergeTypeWithPrevious = false;
9702   OldDecl = nullptr;
9703   Previous.clear();
9704   return false;
9705 }
9706 
9707 /// Check the validity of a new function declaration being added to an existing
9708 /// multiversioned declaration collection.
9709 static bool CheckMultiVersionAdditionalDecl(
9710     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9711     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9712     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9713     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9714     LookupResult &Previous) {
9715 
9716   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9717   // Disallow mixing of multiversioning types.
9718   if ((OldMVType == MultiVersionKind::Target &&
9719        NewMVType != MultiVersionKind::Target) ||
9720       (NewMVType == MultiVersionKind::Target &&
9721        OldMVType != MultiVersionKind::Target)) {
9722     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9723     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9724     NewFD->setInvalidDecl();
9725     return true;
9726   }
9727 
9728   TargetAttr::ParsedTargetAttr NewParsed;
9729   if (NewTA) {
9730     NewParsed = NewTA->parse();
9731     llvm::sort(NewParsed.Features);
9732   }
9733 
9734   bool UseMemberUsingDeclRules =
9735       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9736 
9737   // Next, check ALL non-overloads to see if this is a redeclaration of a
9738   // previous member of the MultiVersion set.
9739   for (NamedDecl *ND : Previous) {
9740     FunctionDecl *CurFD = ND->getAsFunction();
9741     if (!CurFD)
9742       continue;
9743     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9744       continue;
9745 
9746     if (NewMVType == MultiVersionKind::Target) {
9747       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9748       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9749         NewFD->setIsMultiVersion();
9750         Redeclaration = true;
9751         OldDecl = ND;
9752         return false;
9753       }
9754 
9755       TargetAttr::ParsedTargetAttr CurParsed =
9756           CurTA->parse(std::less<std::string>());
9757       if (CurParsed == NewParsed) {
9758         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9759         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9760         NewFD->setInvalidDecl();
9761         return true;
9762       }
9763     } else {
9764       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9765       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9766       // Handle CPUDispatch/CPUSpecific versions.
9767       // Only 1 CPUDispatch function is allowed, this will make it go through
9768       // the redeclaration errors.
9769       if (NewMVType == MultiVersionKind::CPUDispatch &&
9770           CurFD->hasAttr<CPUDispatchAttr>()) {
9771         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9772             std::equal(
9773                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9774                 NewCPUDisp->cpus_begin(),
9775                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9776                   return Cur->getName() == New->getName();
9777                 })) {
9778           NewFD->setIsMultiVersion();
9779           Redeclaration = true;
9780           OldDecl = ND;
9781           return false;
9782         }
9783 
9784         // If the declarations don't match, this is an error condition.
9785         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9786         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9787         NewFD->setInvalidDecl();
9788         return true;
9789       }
9790       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9791 
9792         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9793             std::equal(
9794                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9795                 NewCPUSpec->cpus_begin(),
9796                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9797                   return Cur->getName() == New->getName();
9798                 })) {
9799           NewFD->setIsMultiVersion();
9800           Redeclaration = true;
9801           OldDecl = ND;
9802           return false;
9803         }
9804 
9805         // Only 1 version of CPUSpecific is allowed for each CPU.
9806         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9807           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9808             if (CurII == NewII) {
9809               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9810                   << NewII;
9811               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9812               NewFD->setInvalidDecl();
9813               return true;
9814             }
9815           }
9816         }
9817       }
9818       // If the two decls aren't the same MVType, there is no possible error
9819       // condition.
9820     }
9821   }
9822 
9823   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9824   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9825   // handled in the attribute adding step.
9826   if (NewMVType == MultiVersionKind::Target &&
9827       CheckMultiVersionValue(S, NewFD)) {
9828     NewFD->setInvalidDecl();
9829     return true;
9830   }
9831 
9832   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9833                                        !OldFD->isMultiVersion(), NewMVType)) {
9834     NewFD->setInvalidDecl();
9835     return true;
9836   }
9837 
9838   // Permit forward declarations in the case where these two are compatible.
9839   if (!OldFD->isMultiVersion()) {
9840     OldFD->setIsMultiVersion();
9841     NewFD->setIsMultiVersion();
9842     Redeclaration = true;
9843     OldDecl = OldFD;
9844     return false;
9845   }
9846 
9847   NewFD->setIsMultiVersion();
9848   Redeclaration = false;
9849   MergeTypeWithPrevious = false;
9850   OldDecl = nullptr;
9851   Previous.clear();
9852   return false;
9853 }
9854 
9855 
9856 /// Check the validity of a mulitversion function declaration.
9857 /// Also sets the multiversion'ness' of the function itself.
9858 ///
9859 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9860 ///
9861 /// Returns true if there was an error, false otherwise.
9862 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9863                                       bool &Redeclaration, NamedDecl *&OldDecl,
9864                                       bool &MergeTypeWithPrevious,
9865                                       LookupResult &Previous) {
9866   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9867   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9868   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9869 
9870   // Mixing Multiversioning types is prohibited.
9871   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9872       (NewCPUDisp && NewCPUSpec)) {
9873     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9874     NewFD->setInvalidDecl();
9875     return true;
9876   }
9877 
9878   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9879 
9880   // Main isn't allowed to become a multiversion function, however it IS
9881   // permitted to have 'main' be marked with the 'target' optimization hint.
9882   if (NewFD->isMain()) {
9883     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9884         MVType == MultiVersionKind::CPUDispatch ||
9885         MVType == MultiVersionKind::CPUSpecific) {
9886       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9887       NewFD->setInvalidDecl();
9888       return true;
9889     }
9890     return false;
9891   }
9892 
9893   if (!OldDecl || !OldDecl->getAsFunction() ||
9894       OldDecl->getDeclContext()->getRedeclContext() !=
9895           NewFD->getDeclContext()->getRedeclContext()) {
9896     // If there's no previous declaration, AND this isn't attempting to cause
9897     // multiversioning, this isn't an error condition.
9898     if (MVType == MultiVersionKind::None)
9899       return false;
9900     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9901                                           NewCPUSpec);
9902   }
9903 
9904   FunctionDecl *OldFD = OldDecl->getAsFunction();
9905 
9906   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9907     return false;
9908 
9909   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9910     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9911         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9912     NewFD->setInvalidDecl();
9913     return true;
9914   }
9915 
9916   // Handle the target potentially causes multiversioning case.
9917   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
9918     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9919                                             Redeclaration, OldDecl,
9920                                             MergeTypeWithPrevious, Previous);
9921 
9922   // At this point, we have a multiversion function decl (in OldFD) AND an
9923   // appropriate attribute in the current function decl.  Resolve that these are
9924   // still compatible with previous declarations.
9925   return CheckMultiVersionAdditionalDecl(
9926       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9927       OldDecl, MergeTypeWithPrevious, Previous);
9928 }
9929 
9930 /// Perform semantic checking of a new function declaration.
9931 ///
9932 /// Performs semantic analysis of the new function declaration
9933 /// NewFD. This routine performs all semantic checking that does not
9934 /// require the actual declarator involved in the declaration, and is
9935 /// used both for the declaration of functions as they are parsed
9936 /// (called via ActOnDeclarator) and for the declaration of functions
9937 /// that have been instantiated via C++ template instantiation (called
9938 /// via InstantiateDecl).
9939 ///
9940 /// \param IsMemberSpecialization whether this new function declaration is
9941 /// a member specialization (that replaces any definition provided by the
9942 /// previous declaration).
9943 ///
9944 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9945 ///
9946 /// \returns true if the function declaration is a redeclaration.
9947 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9948                                     LookupResult &Previous,
9949                                     bool IsMemberSpecialization) {
9950   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9951          "Variably modified return types are not handled here");
9952 
9953   // Determine whether the type of this function should be merged with
9954   // a previous visible declaration. This never happens for functions in C++,
9955   // and always happens in C if the previous declaration was visible.
9956   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9957                                !Previous.isShadowed();
9958 
9959   bool Redeclaration = false;
9960   NamedDecl *OldDecl = nullptr;
9961   bool MayNeedOverloadableChecks = false;
9962 
9963   // Merge or overload the declaration with an existing declaration of
9964   // the same name, if appropriate.
9965   if (!Previous.empty()) {
9966     // Determine whether NewFD is an overload of PrevDecl or
9967     // a declaration that requires merging. If it's an overload,
9968     // there's no more work to do here; we'll just add the new
9969     // function to the scope.
9970     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9971       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9972       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9973         Redeclaration = true;
9974         OldDecl = Candidate;
9975       }
9976     } else {
9977       MayNeedOverloadableChecks = true;
9978       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9979                             /*NewIsUsingDecl*/ false)) {
9980       case Ovl_Match:
9981         Redeclaration = true;
9982         break;
9983 
9984       case Ovl_NonFunction:
9985         Redeclaration = true;
9986         break;
9987 
9988       case Ovl_Overload:
9989         Redeclaration = false;
9990         break;
9991       }
9992     }
9993   }
9994 
9995   // Check for a previous extern "C" declaration with this name.
9996   if (!Redeclaration &&
9997       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9998     if (!Previous.empty()) {
9999       // This is an extern "C" declaration with the same name as a previous
10000       // declaration, and thus redeclares that entity...
10001       Redeclaration = true;
10002       OldDecl = Previous.getFoundDecl();
10003       MergeTypeWithPrevious = false;
10004 
10005       // ... except in the presence of __attribute__((overloadable)).
10006       if (OldDecl->hasAttr<OverloadableAttr>() ||
10007           NewFD->hasAttr<OverloadableAttr>()) {
10008         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10009           MayNeedOverloadableChecks = true;
10010           Redeclaration = false;
10011           OldDecl = nullptr;
10012         }
10013       }
10014     }
10015   }
10016 
10017   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10018                                 MergeTypeWithPrevious, Previous))
10019     return Redeclaration;
10020 
10021   // C++11 [dcl.constexpr]p8:
10022   //   A constexpr specifier for a non-static member function that is not
10023   //   a constructor declares that member function to be const.
10024   //
10025   // This needs to be delayed until we know whether this is an out-of-line
10026   // definition of a static member function.
10027   //
10028   // This rule is not present in C++1y, so we produce a backwards
10029   // compatibility warning whenever it happens in C++11.
10030   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10031   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10032       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10033       !MD->getMethodQualifiers().hasConst()) {
10034     CXXMethodDecl *OldMD = nullptr;
10035     if (OldDecl)
10036       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10037     if (!OldMD || !OldMD->isStatic()) {
10038       const FunctionProtoType *FPT =
10039         MD->getType()->castAs<FunctionProtoType>();
10040       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10041       EPI.TypeQuals.addConst();
10042       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10043                                           FPT->getParamTypes(), EPI));
10044 
10045       // Warn that we did this, if we're not performing template instantiation.
10046       // In that case, we'll have warned already when the template was defined.
10047       if (!inTemplateInstantiation()) {
10048         SourceLocation AddConstLoc;
10049         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10050                 .IgnoreParens().getAs<FunctionTypeLoc>())
10051           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10052 
10053         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10054           << FixItHint::CreateInsertion(AddConstLoc, " const");
10055       }
10056     }
10057   }
10058 
10059   if (Redeclaration) {
10060     // NewFD and OldDecl represent declarations that need to be
10061     // merged.
10062     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10063       NewFD->setInvalidDecl();
10064       return Redeclaration;
10065     }
10066 
10067     Previous.clear();
10068     Previous.addDecl(OldDecl);
10069 
10070     if (FunctionTemplateDecl *OldTemplateDecl =
10071             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10072       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10073       FunctionTemplateDecl *NewTemplateDecl
10074         = NewFD->getDescribedFunctionTemplate();
10075       assert(NewTemplateDecl && "Template/non-template mismatch");
10076 
10077       // The call to MergeFunctionDecl above may have created some state in
10078       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10079       // can add it as a redeclaration.
10080       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10081 
10082       NewFD->setPreviousDeclaration(OldFD);
10083       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10084       if (NewFD->isCXXClassMember()) {
10085         NewFD->setAccess(OldTemplateDecl->getAccess());
10086         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10087       }
10088 
10089       // If this is an explicit specialization of a member that is a function
10090       // template, mark it as a member specialization.
10091       if (IsMemberSpecialization &&
10092           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10093         NewTemplateDecl->setMemberSpecialization();
10094         assert(OldTemplateDecl->isMemberSpecialization());
10095         // Explicit specializations of a member template do not inherit deleted
10096         // status from the parent member template that they are specializing.
10097         if (OldFD->isDeleted()) {
10098           // FIXME: This assert will not hold in the presence of modules.
10099           assert(OldFD->getCanonicalDecl() == OldFD);
10100           // FIXME: We need an update record for this AST mutation.
10101           OldFD->setDeletedAsWritten(false);
10102         }
10103       }
10104 
10105     } else {
10106       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10107         auto *OldFD = cast<FunctionDecl>(OldDecl);
10108         // This needs to happen first so that 'inline' propagates.
10109         NewFD->setPreviousDeclaration(OldFD);
10110         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10111         if (NewFD->isCXXClassMember())
10112           NewFD->setAccess(OldFD->getAccess());
10113       }
10114     }
10115   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10116              !NewFD->getAttr<OverloadableAttr>()) {
10117     assert((Previous.empty() ||
10118             llvm::any_of(Previous,
10119                          [](const NamedDecl *ND) {
10120                            return ND->hasAttr<OverloadableAttr>();
10121                          })) &&
10122            "Non-redecls shouldn't happen without overloadable present");
10123 
10124     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10125       const auto *FD = dyn_cast<FunctionDecl>(ND);
10126       return FD && !FD->hasAttr<OverloadableAttr>();
10127     });
10128 
10129     if (OtherUnmarkedIter != Previous.end()) {
10130       Diag(NewFD->getLocation(),
10131            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10132       Diag((*OtherUnmarkedIter)->getLocation(),
10133            diag::note_attribute_overloadable_prev_overload)
10134           << false;
10135 
10136       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10137     }
10138   }
10139 
10140   // Semantic checking for this function declaration (in isolation).
10141 
10142   if (getLangOpts().CPlusPlus) {
10143     // C++-specific checks.
10144     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10145       CheckConstructor(Constructor);
10146     } else if (CXXDestructorDecl *Destructor =
10147                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10148       CXXRecordDecl *Record = Destructor->getParent();
10149       QualType ClassType = Context.getTypeDeclType(Record);
10150 
10151       // FIXME: Shouldn't we be able to perform this check even when the class
10152       // type is dependent? Both gcc and edg can handle that.
10153       if (!ClassType->isDependentType()) {
10154         DeclarationName Name
10155           = Context.DeclarationNames.getCXXDestructorName(
10156                                         Context.getCanonicalType(ClassType));
10157         if (NewFD->getDeclName() != Name) {
10158           Diag(NewFD->getLocation(), diag::err_destructor_name);
10159           NewFD->setInvalidDecl();
10160           return Redeclaration;
10161         }
10162       }
10163     } else if (CXXConversionDecl *Conversion
10164                = dyn_cast<CXXConversionDecl>(NewFD)) {
10165       ActOnConversionDeclarator(Conversion);
10166     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10167       if (auto *TD = Guide->getDescribedFunctionTemplate())
10168         CheckDeductionGuideTemplate(TD);
10169 
10170       // A deduction guide is not on the list of entities that can be
10171       // explicitly specialized.
10172       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10173         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10174             << /*explicit specialization*/ 1;
10175     }
10176 
10177     // Find any virtual functions that this function overrides.
10178     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10179       if (!Method->isFunctionTemplateSpecialization() &&
10180           !Method->getDescribedFunctionTemplate() &&
10181           Method->isCanonicalDecl()) {
10182         if (AddOverriddenMethods(Method->getParent(), Method)) {
10183           // If the function was marked as "static", we have a problem.
10184           if (NewFD->getStorageClass() == SC_Static) {
10185             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10186           }
10187         }
10188       }
10189 
10190       if (Method->isStatic())
10191         checkThisInStaticMemberFunctionType(Method);
10192     }
10193 
10194     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10195     if (NewFD->isOverloadedOperator() &&
10196         CheckOverloadedOperatorDeclaration(NewFD)) {
10197       NewFD->setInvalidDecl();
10198       return Redeclaration;
10199     }
10200 
10201     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10202     if (NewFD->getLiteralIdentifier() &&
10203         CheckLiteralOperatorDeclaration(NewFD)) {
10204       NewFD->setInvalidDecl();
10205       return Redeclaration;
10206     }
10207 
10208     // In C++, check default arguments now that we have merged decls. Unless
10209     // the lexical context is the class, because in this case this is done
10210     // during delayed parsing anyway.
10211     if (!CurContext->isRecord())
10212       CheckCXXDefaultArguments(NewFD);
10213 
10214     // If this function declares a builtin function, check the type of this
10215     // declaration against the expected type for the builtin.
10216     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10217       ASTContext::GetBuiltinTypeError Error;
10218       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10219       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10220       // If the type of the builtin differs only in its exception
10221       // specification, that's OK.
10222       // FIXME: If the types do differ in this way, it would be better to
10223       // retain the 'noexcept' form of the type.
10224       if (!T.isNull() &&
10225           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10226                                                             NewFD->getType()))
10227         // The type of this function differs from the type of the builtin,
10228         // so forget about the builtin entirely.
10229         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10230     }
10231 
10232     // If this function is declared as being extern "C", then check to see if
10233     // the function returns a UDT (class, struct, or union type) that is not C
10234     // compatible, and if it does, warn the user.
10235     // But, issue any diagnostic on the first declaration only.
10236     if (Previous.empty() && NewFD->isExternC()) {
10237       QualType R = NewFD->getReturnType();
10238       if (R->isIncompleteType() && !R->isVoidType())
10239         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10240             << NewFD << R;
10241       else if (!R.isPODType(Context) && !R->isVoidType() &&
10242                !R->isObjCObjectPointerType())
10243         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10244     }
10245 
10246     // C++1z [dcl.fct]p6:
10247     //   [...] whether the function has a non-throwing exception-specification
10248     //   [is] part of the function type
10249     //
10250     // This results in an ABI break between C++14 and C++17 for functions whose
10251     // declared type includes an exception-specification in a parameter or
10252     // return type. (Exception specifications on the function itself are OK in
10253     // most cases, and exception specifications are not permitted in most other
10254     // contexts where they could make it into a mangling.)
10255     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10256       auto HasNoexcept = [&](QualType T) -> bool {
10257         // Strip off declarator chunks that could be between us and a function
10258         // type. We don't need to look far, exception specifications are very
10259         // restricted prior to C++17.
10260         if (auto *RT = T->getAs<ReferenceType>())
10261           T = RT->getPointeeType();
10262         else if (T->isAnyPointerType())
10263           T = T->getPointeeType();
10264         else if (auto *MPT = T->getAs<MemberPointerType>())
10265           T = MPT->getPointeeType();
10266         if (auto *FPT = T->getAs<FunctionProtoType>())
10267           if (FPT->isNothrow())
10268             return true;
10269         return false;
10270       };
10271 
10272       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10273       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10274       for (QualType T : FPT->param_types())
10275         AnyNoexcept |= HasNoexcept(T);
10276       if (AnyNoexcept)
10277         Diag(NewFD->getLocation(),
10278              diag::warn_cxx17_compat_exception_spec_in_signature)
10279             << NewFD;
10280     }
10281 
10282     if (!Redeclaration && LangOpts.CUDA)
10283       checkCUDATargetOverload(NewFD, Previous);
10284   }
10285   return Redeclaration;
10286 }
10287 
10288 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10289   // C++11 [basic.start.main]p3:
10290   //   A program that [...] declares main to be inline, static or
10291   //   constexpr is ill-formed.
10292   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10293   //   appear in a declaration of main.
10294   // static main is not an error under C99, but we should warn about it.
10295   // We accept _Noreturn main as an extension.
10296   if (FD->getStorageClass() == SC_Static)
10297     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10298          ? diag::err_static_main : diag::warn_static_main)
10299       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10300   if (FD->isInlineSpecified())
10301     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10302       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10303   if (DS.isNoreturnSpecified()) {
10304     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10305     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10306     Diag(NoreturnLoc, diag::ext_noreturn_main);
10307     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10308       << FixItHint::CreateRemoval(NoreturnRange);
10309   }
10310   if (FD->isConstexpr()) {
10311     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10312       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10313     FD->setConstexpr(false);
10314   }
10315 
10316   if (getLangOpts().OpenCL) {
10317     Diag(FD->getLocation(), diag::err_opencl_no_main)
10318         << FD->hasAttr<OpenCLKernelAttr>();
10319     FD->setInvalidDecl();
10320     return;
10321   }
10322 
10323   QualType T = FD->getType();
10324   assert(T->isFunctionType() && "function decl is not of function type");
10325   const FunctionType* FT = T->castAs<FunctionType>();
10326 
10327   // Set default calling convention for main()
10328   if (FT->getCallConv() != CC_C) {
10329     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10330     FD->setType(QualType(FT, 0));
10331     T = Context.getCanonicalType(FD->getType());
10332   }
10333 
10334   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10335     // In C with GNU extensions we allow main() to have non-integer return
10336     // type, but we should warn about the extension, and we disable the
10337     // implicit-return-zero rule.
10338 
10339     // GCC in C mode accepts qualified 'int'.
10340     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10341       FD->setHasImplicitReturnZero(true);
10342     else {
10343       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10344       SourceRange RTRange = FD->getReturnTypeSourceRange();
10345       if (RTRange.isValid())
10346         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10347             << FixItHint::CreateReplacement(RTRange, "int");
10348     }
10349   } else {
10350     // In C and C++, main magically returns 0 if you fall off the end;
10351     // set the flag which tells us that.
10352     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10353 
10354     // All the standards say that main() should return 'int'.
10355     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10356       FD->setHasImplicitReturnZero(true);
10357     else {
10358       // Otherwise, this is just a flat-out error.
10359       SourceRange RTRange = FD->getReturnTypeSourceRange();
10360       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10361           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10362                                 : FixItHint());
10363       FD->setInvalidDecl(true);
10364     }
10365   }
10366 
10367   // Treat protoless main() as nullary.
10368   if (isa<FunctionNoProtoType>(FT)) return;
10369 
10370   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10371   unsigned nparams = FTP->getNumParams();
10372   assert(FD->getNumParams() == nparams);
10373 
10374   bool HasExtraParameters = (nparams > 3);
10375 
10376   if (FTP->isVariadic()) {
10377     Diag(FD->getLocation(), diag::ext_variadic_main);
10378     // FIXME: if we had information about the location of the ellipsis, we
10379     // could add a FixIt hint to remove it as a parameter.
10380   }
10381 
10382   // Darwin passes an undocumented fourth argument of type char**.  If
10383   // other platforms start sprouting these, the logic below will start
10384   // getting shifty.
10385   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10386     HasExtraParameters = false;
10387 
10388   if (HasExtraParameters) {
10389     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10390     FD->setInvalidDecl(true);
10391     nparams = 3;
10392   }
10393 
10394   // FIXME: a lot of the following diagnostics would be improved
10395   // if we had some location information about types.
10396 
10397   QualType CharPP =
10398     Context.getPointerType(Context.getPointerType(Context.CharTy));
10399   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10400 
10401   for (unsigned i = 0; i < nparams; ++i) {
10402     QualType AT = FTP->getParamType(i);
10403 
10404     bool mismatch = true;
10405 
10406     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10407       mismatch = false;
10408     else if (Expected[i] == CharPP) {
10409       // As an extension, the following forms are okay:
10410       //   char const **
10411       //   char const * const *
10412       //   char * const *
10413 
10414       QualifierCollector qs;
10415       const PointerType* PT;
10416       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10417           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10418           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10419                               Context.CharTy)) {
10420         qs.removeConst();
10421         mismatch = !qs.empty();
10422       }
10423     }
10424 
10425     if (mismatch) {
10426       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10427       // TODO: suggest replacing given type with expected type
10428       FD->setInvalidDecl(true);
10429     }
10430   }
10431 
10432   if (nparams == 1 && !FD->isInvalidDecl()) {
10433     Diag(FD->getLocation(), diag::warn_main_one_arg);
10434   }
10435 
10436   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10437     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10438     FD->setInvalidDecl();
10439   }
10440 }
10441 
10442 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10443   QualType T = FD->getType();
10444   assert(T->isFunctionType() && "function decl is not of function type");
10445   const FunctionType *FT = T->castAs<FunctionType>();
10446 
10447   // Set an implicit return of 'zero' if the function can return some integral,
10448   // enumeration, pointer or nullptr type.
10449   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10450       FT->getReturnType()->isAnyPointerType() ||
10451       FT->getReturnType()->isNullPtrType())
10452     // DllMain is exempt because a return value of zero means it failed.
10453     if (FD->getName() != "DllMain")
10454       FD->setHasImplicitReturnZero(true);
10455 
10456   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10457     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10458     FD->setInvalidDecl();
10459   }
10460 }
10461 
10462 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10463   // FIXME: Need strict checking.  In C89, we need to check for
10464   // any assignment, increment, decrement, function-calls, or
10465   // commas outside of a sizeof.  In C99, it's the same list,
10466   // except that the aforementioned are allowed in unevaluated
10467   // expressions.  Everything else falls under the
10468   // "may accept other forms of constant expressions" exception.
10469   // (We never end up here for C++, so the constant expression
10470   // rules there don't matter.)
10471   const Expr *Culprit;
10472   if (Init->isConstantInitializer(Context, false, &Culprit))
10473     return false;
10474   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10475     << Culprit->getSourceRange();
10476   return true;
10477 }
10478 
10479 namespace {
10480   // Visits an initialization expression to see if OrigDecl is evaluated in
10481   // its own initialization and throws a warning if it does.
10482   class SelfReferenceChecker
10483       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10484     Sema &S;
10485     Decl *OrigDecl;
10486     bool isRecordType;
10487     bool isPODType;
10488     bool isReferenceType;
10489 
10490     bool isInitList;
10491     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10492 
10493   public:
10494     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10495 
10496     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10497                                                     S(S), OrigDecl(OrigDecl) {
10498       isPODType = false;
10499       isRecordType = false;
10500       isReferenceType = false;
10501       isInitList = false;
10502       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10503         isPODType = VD->getType().isPODType(S.Context);
10504         isRecordType = VD->getType()->isRecordType();
10505         isReferenceType = VD->getType()->isReferenceType();
10506       }
10507     }
10508 
10509     // For most expressions, just call the visitor.  For initializer lists,
10510     // track the index of the field being initialized since fields are
10511     // initialized in order allowing use of previously initialized fields.
10512     void CheckExpr(Expr *E) {
10513       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10514       if (!InitList) {
10515         Visit(E);
10516         return;
10517       }
10518 
10519       // Track and increment the index here.
10520       isInitList = true;
10521       InitFieldIndex.push_back(0);
10522       for (auto Child : InitList->children()) {
10523         CheckExpr(cast<Expr>(Child));
10524         ++InitFieldIndex.back();
10525       }
10526       InitFieldIndex.pop_back();
10527     }
10528 
10529     // Returns true if MemberExpr is checked and no further checking is needed.
10530     // Returns false if additional checking is required.
10531     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10532       llvm::SmallVector<FieldDecl*, 4> Fields;
10533       Expr *Base = E;
10534       bool ReferenceField = false;
10535 
10536       // Get the field members used.
10537       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10538         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10539         if (!FD)
10540           return false;
10541         Fields.push_back(FD);
10542         if (FD->getType()->isReferenceType())
10543           ReferenceField = true;
10544         Base = ME->getBase()->IgnoreParenImpCasts();
10545       }
10546 
10547       // Keep checking only if the base Decl is the same.
10548       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10549       if (!DRE || DRE->getDecl() != OrigDecl)
10550         return false;
10551 
10552       // A reference field can be bound to an unininitialized field.
10553       if (CheckReference && !ReferenceField)
10554         return true;
10555 
10556       // Convert FieldDecls to their index number.
10557       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10558       for (const FieldDecl *I : llvm::reverse(Fields))
10559         UsedFieldIndex.push_back(I->getFieldIndex());
10560 
10561       // See if a warning is needed by checking the first difference in index
10562       // numbers.  If field being used has index less than the field being
10563       // initialized, then the use is safe.
10564       for (auto UsedIter = UsedFieldIndex.begin(),
10565                 UsedEnd = UsedFieldIndex.end(),
10566                 OrigIter = InitFieldIndex.begin(),
10567                 OrigEnd = InitFieldIndex.end();
10568            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10569         if (*UsedIter < *OrigIter)
10570           return true;
10571         if (*UsedIter > *OrigIter)
10572           break;
10573       }
10574 
10575       // TODO: Add a different warning which will print the field names.
10576       HandleDeclRefExpr(DRE);
10577       return true;
10578     }
10579 
10580     // For most expressions, the cast is directly above the DeclRefExpr.
10581     // For conditional operators, the cast can be outside the conditional
10582     // operator if both expressions are DeclRefExpr's.
10583     void HandleValue(Expr *E) {
10584       E = E->IgnoreParens();
10585       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10586         HandleDeclRefExpr(DRE);
10587         return;
10588       }
10589 
10590       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10591         Visit(CO->getCond());
10592         HandleValue(CO->getTrueExpr());
10593         HandleValue(CO->getFalseExpr());
10594         return;
10595       }
10596 
10597       if (BinaryConditionalOperator *BCO =
10598               dyn_cast<BinaryConditionalOperator>(E)) {
10599         Visit(BCO->getCond());
10600         HandleValue(BCO->getFalseExpr());
10601         return;
10602       }
10603 
10604       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10605         HandleValue(OVE->getSourceExpr());
10606         return;
10607       }
10608 
10609       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10610         if (BO->getOpcode() == BO_Comma) {
10611           Visit(BO->getLHS());
10612           HandleValue(BO->getRHS());
10613           return;
10614         }
10615       }
10616 
10617       if (isa<MemberExpr>(E)) {
10618         if (isInitList) {
10619           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10620                                       false /*CheckReference*/))
10621             return;
10622         }
10623 
10624         Expr *Base = E->IgnoreParenImpCasts();
10625         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10626           // Check for static member variables and don't warn on them.
10627           if (!isa<FieldDecl>(ME->getMemberDecl()))
10628             return;
10629           Base = ME->getBase()->IgnoreParenImpCasts();
10630         }
10631         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10632           HandleDeclRefExpr(DRE);
10633         return;
10634       }
10635 
10636       Visit(E);
10637     }
10638 
10639     // Reference types not handled in HandleValue are handled here since all
10640     // uses of references are bad, not just r-value uses.
10641     void VisitDeclRefExpr(DeclRefExpr *E) {
10642       if (isReferenceType)
10643         HandleDeclRefExpr(E);
10644     }
10645 
10646     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10647       if (E->getCastKind() == CK_LValueToRValue) {
10648         HandleValue(E->getSubExpr());
10649         return;
10650       }
10651 
10652       Inherited::VisitImplicitCastExpr(E);
10653     }
10654 
10655     void VisitMemberExpr(MemberExpr *E) {
10656       if (isInitList) {
10657         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10658           return;
10659       }
10660 
10661       // Don't warn on arrays since they can be treated as pointers.
10662       if (E->getType()->canDecayToPointerType()) return;
10663 
10664       // Warn when a non-static method call is followed by non-static member
10665       // field accesses, which is followed by a DeclRefExpr.
10666       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10667       bool Warn = (MD && !MD->isStatic());
10668       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10669       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10670         if (!isa<FieldDecl>(ME->getMemberDecl()))
10671           Warn = false;
10672         Base = ME->getBase()->IgnoreParenImpCasts();
10673       }
10674 
10675       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10676         if (Warn)
10677           HandleDeclRefExpr(DRE);
10678         return;
10679       }
10680 
10681       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10682       // Visit that expression.
10683       Visit(Base);
10684     }
10685 
10686     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10687       Expr *Callee = E->getCallee();
10688 
10689       if (isa<UnresolvedLookupExpr>(Callee))
10690         return Inherited::VisitCXXOperatorCallExpr(E);
10691 
10692       Visit(Callee);
10693       for (auto Arg: E->arguments())
10694         HandleValue(Arg->IgnoreParenImpCasts());
10695     }
10696 
10697     void VisitUnaryOperator(UnaryOperator *E) {
10698       // For POD record types, addresses of its own members are well-defined.
10699       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10700           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10701         if (!isPODType)
10702           HandleValue(E->getSubExpr());
10703         return;
10704       }
10705 
10706       if (E->isIncrementDecrementOp()) {
10707         HandleValue(E->getSubExpr());
10708         return;
10709       }
10710 
10711       Inherited::VisitUnaryOperator(E);
10712     }
10713 
10714     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10715 
10716     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10717       if (E->getConstructor()->isCopyConstructor()) {
10718         Expr *ArgExpr = E->getArg(0);
10719         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10720           if (ILE->getNumInits() == 1)
10721             ArgExpr = ILE->getInit(0);
10722         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10723           if (ICE->getCastKind() == CK_NoOp)
10724             ArgExpr = ICE->getSubExpr();
10725         HandleValue(ArgExpr);
10726         return;
10727       }
10728       Inherited::VisitCXXConstructExpr(E);
10729     }
10730 
10731     void VisitCallExpr(CallExpr *E) {
10732       // Treat std::move as a use.
10733       if (E->isCallToStdMove()) {
10734         HandleValue(E->getArg(0));
10735         return;
10736       }
10737 
10738       Inherited::VisitCallExpr(E);
10739     }
10740 
10741     void VisitBinaryOperator(BinaryOperator *E) {
10742       if (E->isCompoundAssignmentOp()) {
10743         HandleValue(E->getLHS());
10744         Visit(E->getRHS());
10745         return;
10746       }
10747 
10748       Inherited::VisitBinaryOperator(E);
10749     }
10750 
10751     // A custom visitor for BinaryConditionalOperator is needed because the
10752     // regular visitor would check the condition and true expression separately
10753     // but both point to the same place giving duplicate diagnostics.
10754     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10755       Visit(E->getCond());
10756       Visit(E->getFalseExpr());
10757     }
10758 
10759     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10760       Decl* ReferenceDecl = DRE->getDecl();
10761       if (OrigDecl != ReferenceDecl) return;
10762       unsigned diag;
10763       if (isReferenceType) {
10764         diag = diag::warn_uninit_self_reference_in_reference_init;
10765       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10766         diag = diag::warn_static_self_reference_in_init;
10767       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10768                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10769                  DRE->getDecl()->getType()->isRecordType()) {
10770         diag = diag::warn_uninit_self_reference_in_init;
10771       } else {
10772         // Local variables will be handled by the CFG analysis.
10773         return;
10774       }
10775 
10776       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10777                             S.PDiag(diag)
10778                                 << DRE->getDecl() << OrigDecl->getLocation()
10779                                 << DRE->getSourceRange());
10780     }
10781   };
10782 
10783   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10784   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10785                                  bool DirectInit) {
10786     // Parameters arguments are occassionially constructed with itself,
10787     // for instance, in recursive functions.  Skip them.
10788     if (isa<ParmVarDecl>(OrigDecl))
10789       return;
10790 
10791     E = E->IgnoreParens();
10792 
10793     // Skip checking T a = a where T is not a record or reference type.
10794     // Doing so is a way to silence uninitialized warnings.
10795     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10796       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10797         if (ICE->getCastKind() == CK_LValueToRValue)
10798           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10799             if (DRE->getDecl() == OrigDecl)
10800               return;
10801 
10802     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10803   }
10804 } // end anonymous namespace
10805 
10806 namespace {
10807   // Simple wrapper to add the name of a variable or (if no variable is
10808   // available) a DeclarationName into a diagnostic.
10809   struct VarDeclOrName {
10810     VarDecl *VDecl;
10811     DeclarationName Name;
10812 
10813     friend const Sema::SemaDiagnosticBuilder &
10814     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10815       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10816     }
10817   };
10818 } // end anonymous namespace
10819 
10820 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10821                                             DeclarationName Name, QualType Type,
10822                                             TypeSourceInfo *TSI,
10823                                             SourceRange Range, bool DirectInit,
10824                                             Expr *&Init) {
10825   bool IsInitCapture = !VDecl;
10826   assert((!VDecl || !VDecl->isInitCapture()) &&
10827          "init captures are expected to be deduced prior to initialization");
10828 
10829   VarDeclOrName VN{VDecl, Name};
10830 
10831   DeducedType *Deduced = Type->getContainedDeducedType();
10832   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10833 
10834   // C++11 [dcl.spec.auto]p3
10835   if (!Init) {
10836     assert(VDecl && "no init for init capture deduction?");
10837 
10838     // Except for class argument deduction, and then for an initializing
10839     // declaration only, i.e. no static at class scope or extern.
10840     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10841         VDecl->hasExternalStorage() ||
10842         VDecl->isStaticDataMember()) {
10843       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10844         << VDecl->getDeclName() << Type;
10845       return QualType();
10846     }
10847   }
10848 
10849   ArrayRef<Expr*> DeduceInits;
10850   if (Init)
10851     DeduceInits = Init;
10852 
10853   if (DirectInit) {
10854     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10855       DeduceInits = PL->exprs();
10856   }
10857 
10858   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10859     assert(VDecl && "non-auto type for init capture deduction?");
10860     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10861     InitializationKind Kind = InitializationKind::CreateForInit(
10862         VDecl->getLocation(), DirectInit, Init);
10863     // FIXME: Initialization should not be taking a mutable list of inits.
10864     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10865     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10866                                                        InitsCopy);
10867   }
10868 
10869   if (DirectInit) {
10870     if (auto *IL = dyn_cast<InitListExpr>(Init))
10871       DeduceInits = IL->inits();
10872   }
10873 
10874   // Deduction only works if we have exactly one source expression.
10875   if (DeduceInits.empty()) {
10876     // It isn't possible to write this directly, but it is possible to
10877     // end up in this situation with "auto x(some_pack...);"
10878     Diag(Init->getBeginLoc(), IsInitCapture
10879                                   ? diag::err_init_capture_no_expression
10880                                   : diag::err_auto_var_init_no_expression)
10881         << VN << Type << Range;
10882     return QualType();
10883   }
10884 
10885   if (DeduceInits.size() > 1) {
10886     Diag(DeduceInits[1]->getBeginLoc(),
10887          IsInitCapture ? diag::err_init_capture_multiple_expressions
10888                        : diag::err_auto_var_init_multiple_expressions)
10889         << VN << Type << Range;
10890     return QualType();
10891   }
10892 
10893   Expr *DeduceInit = DeduceInits[0];
10894   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10895     Diag(Init->getBeginLoc(), IsInitCapture
10896                                   ? diag::err_init_capture_paren_braces
10897                                   : diag::err_auto_var_init_paren_braces)
10898         << isa<InitListExpr>(Init) << VN << Type << Range;
10899     return QualType();
10900   }
10901 
10902   // Expressions default to 'id' when we're in a debugger.
10903   bool DefaultedAnyToId = false;
10904   if (getLangOpts().DebuggerCastResultToId &&
10905       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10906     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10907     if (Result.isInvalid()) {
10908       return QualType();
10909     }
10910     Init = Result.get();
10911     DefaultedAnyToId = true;
10912   }
10913 
10914   // C++ [dcl.decomp]p1:
10915   //   If the assignment-expression [...] has array type A and no ref-qualifier
10916   //   is present, e has type cv A
10917   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10918       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10919       DeduceInit->getType()->isConstantArrayType())
10920     return Context.getQualifiedType(DeduceInit->getType(),
10921                                     Type.getQualifiers());
10922 
10923   QualType DeducedType;
10924   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10925     if (!IsInitCapture)
10926       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10927     else if (isa<InitListExpr>(Init))
10928       Diag(Range.getBegin(),
10929            diag::err_init_capture_deduction_failure_from_init_list)
10930           << VN
10931           << (DeduceInit->getType().isNull() ? TSI->getType()
10932                                              : DeduceInit->getType())
10933           << DeduceInit->getSourceRange();
10934     else
10935       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10936           << VN << TSI->getType()
10937           << (DeduceInit->getType().isNull() ? TSI->getType()
10938                                              : DeduceInit->getType())
10939           << DeduceInit->getSourceRange();
10940   } else
10941     Init = DeduceInit;
10942 
10943   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10944   // 'id' instead of a specific object type prevents most of our usual
10945   // checks.
10946   // We only want to warn outside of template instantiations, though:
10947   // inside a template, the 'id' could have come from a parameter.
10948   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10949       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10950     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10951     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10952   }
10953 
10954   return DeducedType;
10955 }
10956 
10957 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10958                                          Expr *&Init) {
10959   QualType DeducedType = deduceVarTypeFromInitializer(
10960       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10961       VDecl->getSourceRange(), DirectInit, Init);
10962   if (DeducedType.isNull()) {
10963     VDecl->setInvalidDecl();
10964     return true;
10965   }
10966 
10967   VDecl->setType(DeducedType);
10968   assert(VDecl->isLinkageValid());
10969 
10970   // In ARC, infer lifetime.
10971   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10972     VDecl->setInvalidDecl();
10973 
10974   // If this is a redeclaration, check that the type we just deduced matches
10975   // the previously declared type.
10976   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10977     // We never need to merge the type, because we cannot form an incomplete
10978     // array of auto, nor deduce such a type.
10979     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10980   }
10981 
10982   // Check the deduced type is valid for a variable declaration.
10983   CheckVariableDeclarationType(VDecl);
10984   return VDecl->isInvalidDecl();
10985 }
10986 
10987 /// AddInitializerToDecl - Adds the initializer Init to the
10988 /// declaration dcl. If DirectInit is true, this is C++ direct
10989 /// initialization rather than copy initialization.
10990 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10991   // If there is no declaration, there was an error parsing it.  Just ignore
10992   // the initializer.
10993   if (!RealDecl || RealDecl->isInvalidDecl()) {
10994     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10995     return;
10996   }
10997 
10998   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10999     // Pure-specifiers are handled in ActOnPureSpecifier.
11000     Diag(Method->getLocation(), diag::err_member_function_initialization)
11001       << Method->getDeclName() << Init->getSourceRange();
11002     Method->setInvalidDecl();
11003     return;
11004   }
11005 
11006   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11007   if (!VDecl) {
11008     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11009     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11010     RealDecl->setInvalidDecl();
11011     return;
11012   }
11013 
11014   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11015   if (VDecl->getType()->isUndeducedType()) {
11016     // Attempt typo correction early so that the type of the init expression can
11017     // be deduced based on the chosen correction if the original init contains a
11018     // TypoExpr.
11019     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11020     if (!Res.isUsable()) {
11021       RealDecl->setInvalidDecl();
11022       return;
11023     }
11024     Init = Res.get();
11025 
11026     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11027       return;
11028   }
11029 
11030   // dllimport cannot be used on variable definitions.
11031   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11032     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11033     VDecl->setInvalidDecl();
11034     return;
11035   }
11036 
11037   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11038     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11039     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11040     VDecl->setInvalidDecl();
11041     return;
11042   }
11043 
11044   if (!VDecl->getType()->isDependentType()) {
11045     // A definition must end up with a complete type, which means it must be
11046     // complete with the restriction that an array type might be completed by
11047     // the initializer; note that later code assumes this restriction.
11048     QualType BaseDeclType = VDecl->getType();
11049     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11050       BaseDeclType = Array->getElementType();
11051     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11052                             diag::err_typecheck_decl_incomplete_type)) {
11053       RealDecl->setInvalidDecl();
11054       return;
11055     }
11056 
11057     // The variable can not have an abstract class type.
11058     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11059                                diag::err_abstract_type_in_decl,
11060                                AbstractVariableType))
11061       VDecl->setInvalidDecl();
11062   }
11063 
11064   // If adding the initializer will turn this declaration into a definition,
11065   // and we already have a definition for this variable, diagnose or otherwise
11066   // handle the situation.
11067   VarDecl *Def;
11068   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11069       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11070       !VDecl->isThisDeclarationADemotedDefinition() &&
11071       checkVarDeclRedefinition(Def, VDecl))
11072     return;
11073 
11074   if (getLangOpts().CPlusPlus) {
11075     // C++ [class.static.data]p4
11076     //   If a static data member is of const integral or const
11077     //   enumeration type, its declaration in the class definition can
11078     //   specify a constant-initializer which shall be an integral
11079     //   constant expression (5.19). In that case, the member can appear
11080     //   in integral constant expressions. The member shall still be
11081     //   defined in a namespace scope if it is used in the program and the
11082     //   namespace scope definition shall not contain an initializer.
11083     //
11084     // We already performed a redefinition check above, but for static
11085     // data members we also need to check whether there was an in-class
11086     // declaration with an initializer.
11087     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11088       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11089           << VDecl->getDeclName();
11090       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11091            diag::note_previous_initializer)
11092           << 0;
11093       return;
11094     }
11095 
11096     if (VDecl->hasLocalStorage())
11097       setFunctionHasBranchProtectedScope();
11098 
11099     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11100       VDecl->setInvalidDecl();
11101       return;
11102     }
11103   }
11104 
11105   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11106   // a kernel function cannot be initialized."
11107   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11108     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11109     VDecl->setInvalidDecl();
11110     return;
11111   }
11112 
11113   // Get the decls type and save a reference for later, since
11114   // CheckInitializerTypes may change it.
11115   QualType DclT = VDecl->getType(), SavT = DclT;
11116 
11117   // Expressions default to 'id' when we're in a debugger
11118   // and we are assigning it to a variable of Objective-C pointer type.
11119   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11120       Init->getType() == Context.UnknownAnyTy) {
11121     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11122     if (Result.isInvalid()) {
11123       VDecl->setInvalidDecl();
11124       return;
11125     }
11126     Init = Result.get();
11127   }
11128 
11129   // Perform the initialization.
11130   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11131   if (!VDecl->isInvalidDecl()) {
11132     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11133     InitializationKind Kind = InitializationKind::CreateForInit(
11134         VDecl->getLocation(), DirectInit, Init);
11135 
11136     MultiExprArg Args = Init;
11137     if (CXXDirectInit)
11138       Args = MultiExprArg(CXXDirectInit->getExprs(),
11139                           CXXDirectInit->getNumExprs());
11140 
11141     // Try to correct any TypoExprs in the initialization arguments.
11142     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11143       ExprResult Res = CorrectDelayedTyposInExpr(
11144           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11145             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11146             return Init.Failed() ? ExprError() : E;
11147           });
11148       if (Res.isInvalid()) {
11149         VDecl->setInvalidDecl();
11150       } else if (Res.get() != Args[Idx]) {
11151         Args[Idx] = Res.get();
11152       }
11153     }
11154     if (VDecl->isInvalidDecl())
11155       return;
11156 
11157     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11158                                    /*TopLevelOfInitList=*/false,
11159                                    /*TreatUnavailableAsInvalid=*/false);
11160     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11161     if (Result.isInvalid()) {
11162       VDecl->setInvalidDecl();
11163       return;
11164     }
11165 
11166     Init = Result.getAs<Expr>();
11167   }
11168 
11169   // Check for self-references within variable initializers.
11170   // Variables declared within a function/method body (except for references)
11171   // are handled by a dataflow analysis.
11172   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11173       VDecl->getType()->isReferenceType()) {
11174     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11175   }
11176 
11177   // If the type changed, it means we had an incomplete type that was
11178   // completed by the initializer. For example:
11179   //   int ary[] = { 1, 3, 5 };
11180   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11181   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11182     VDecl->setType(DclT);
11183 
11184   if (!VDecl->isInvalidDecl()) {
11185     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11186 
11187     if (VDecl->hasAttr<BlocksAttr>())
11188       checkRetainCycles(VDecl, Init);
11189 
11190     // It is safe to assign a weak reference into a strong variable.
11191     // Although this code can still have problems:
11192     //   id x = self.weakProp;
11193     //   id y = self.weakProp;
11194     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11195     // paths through the function. This should be revisited if
11196     // -Wrepeated-use-of-weak is made flow-sensitive.
11197     if (FunctionScopeInfo *FSI = getCurFunction())
11198       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11199            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11200           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11201                            Init->getBeginLoc()))
11202         FSI->markSafeWeakUse(Init);
11203   }
11204 
11205   // The initialization is usually a full-expression.
11206   //
11207   // FIXME: If this is a braced initialization of an aggregate, it is not
11208   // an expression, and each individual field initializer is a separate
11209   // full-expression. For instance, in:
11210   //
11211   //   struct Temp { ~Temp(); };
11212   //   struct S { S(Temp); };
11213   //   struct T { S a, b; } t = { Temp(), Temp() }
11214   //
11215   // we should destroy the first Temp before constructing the second.
11216   ExprResult Result =
11217       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11218                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11219   if (Result.isInvalid()) {
11220     VDecl->setInvalidDecl();
11221     return;
11222   }
11223   Init = Result.get();
11224 
11225   // Attach the initializer to the decl.
11226   VDecl->setInit(Init);
11227 
11228   if (VDecl->isLocalVarDecl()) {
11229     // Don't check the initializer if the declaration is malformed.
11230     if (VDecl->isInvalidDecl()) {
11231       // do nothing
11232 
11233     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11234     // This is true even in OpenCL C++.
11235     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11236       CheckForConstantInitializer(Init, DclT);
11237 
11238     // Otherwise, C++ does not restrict the initializer.
11239     } else if (getLangOpts().CPlusPlus) {
11240       // do nothing
11241 
11242     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11243     // static storage duration shall be constant expressions or string literals.
11244     } else if (VDecl->getStorageClass() == SC_Static) {
11245       CheckForConstantInitializer(Init, DclT);
11246 
11247     // C89 is stricter than C99 for aggregate initializers.
11248     // C89 6.5.7p3: All the expressions [...] in an initializer list
11249     // for an object that has aggregate or union type shall be
11250     // constant expressions.
11251     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11252                isa<InitListExpr>(Init)) {
11253       const Expr *Culprit;
11254       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11255         Diag(Culprit->getExprLoc(),
11256              diag::ext_aggregate_init_not_constant)
11257           << Culprit->getSourceRange();
11258       }
11259     }
11260   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11261              VDecl->getLexicalDeclContext()->isRecord()) {
11262     // This is an in-class initialization for a static data member, e.g.,
11263     //
11264     // struct S {
11265     //   static const int value = 17;
11266     // };
11267 
11268     // C++ [class.mem]p4:
11269     //   A member-declarator can contain a constant-initializer only
11270     //   if it declares a static member (9.4) of const integral or
11271     //   const enumeration type, see 9.4.2.
11272     //
11273     // C++11 [class.static.data]p3:
11274     //   If a non-volatile non-inline const static data member is of integral
11275     //   or enumeration type, its declaration in the class definition can
11276     //   specify a brace-or-equal-initializer in which every initializer-clause
11277     //   that is an assignment-expression is a constant expression. A static
11278     //   data member of literal type can be declared in the class definition
11279     //   with the constexpr specifier; if so, its declaration shall specify a
11280     //   brace-or-equal-initializer in which every initializer-clause that is
11281     //   an assignment-expression is a constant expression.
11282 
11283     // Do nothing on dependent types.
11284     if (DclT->isDependentType()) {
11285 
11286     // Allow any 'static constexpr' members, whether or not they are of literal
11287     // type. We separately check that every constexpr variable is of literal
11288     // type.
11289     } else if (VDecl->isConstexpr()) {
11290 
11291     // Require constness.
11292     } else if (!DclT.isConstQualified()) {
11293       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11294         << Init->getSourceRange();
11295       VDecl->setInvalidDecl();
11296 
11297     // We allow integer constant expressions in all cases.
11298     } else if (DclT->isIntegralOrEnumerationType()) {
11299       // Check whether the expression is a constant expression.
11300       SourceLocation Loc;
11301       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11302         // In C++11, a non-constexpr const static data member with an
11303         // in-class initializer cannot be volatile.
11304         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11305       else if (Init->isValueDependent())
11306         ; // Nothing to check.
11307       else if (Init->isIntegerConstantExpr(Context, &Loc))
11308         ; // Ok, it's an ICE!
11309       else if (Init->getType()->isScopedEnumeralType() &&
11310                Init->isCXX11ConstantExpr(Context))
11311         ; // Ok, it is a scoped-enum constant expression.
11312       else if (Init->isEvaluatable(Context)) {
11313         // If we can constant fold the initializer through heroics, accept it,
11314         // but report this as a use of an extension for -pedantic.
11315         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11316           << Init->getSourceRange();
11317       } else {
11318         // Otherwise, this is some crazy unknown case.  Report the issue at the
11319         // location provided by the isIntegerConstantExpr failed check.
11320         Diag(Loc, diag::err_in_class_initializer_non_constant)
11321           << Init->getSourceRange();
11322         VDecl->setInvalidDecl();
11323       }
11324 
11325     // We allow foldable floating-point constants as an extension.
11326     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11327       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11328       // it anyway and provide a fixit to add the 'constexpr'.
11329       if (getLangOpts().CPlusPlus11) {
11330         Diag(VDecl->getLocation(),
11331              diag::ext_in_class_initializer_float_type_cxx11)
11332             << DclT << Init->getSourceRange();
11333         Diag(VDecl->getBeginLoc(),
11334              diag::note_in_class_initializer_float_type_cxx11)
11335             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11336       } else {
11337         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11338           << DclT << Init->getSourceRange();
11339 
11340         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11341           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11342             << Init->getSourceRange();
11343           VDecl->setInvalidDecl();
11344         }
11345       }
11346 
11347     // Suggest adding 'constexpr' in C++11 for literal types.
11348     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11349       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11350           << DclT << Init->getSourceRange()
11351           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11352       VDecl->setConstexpr(true);
11353 
11354     } else {
11355       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11356         << DclT << Init->getSourceRange();
11357       VDecl->setInvalidDecl();
11358     }
11359   } else if (VDecl->isFileVarDecl()) {
11360     // In C, extern is typically used to avoid tentative definitions when
11361     // declaring variables in headers, but adding an intializer makes it a
11362     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11363     // In C++, extern is often used to give implictly static const variables
11364     // external linkage, so don't warn in that case. If selectany is present,
11365     // this might be header code intended for C and C++ inclusion, so apply the
11366     // C++ rules.
11367     if (VDecl->getStorageClass() == SC_Extern &&
11368         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11369          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11370         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11371         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11372       Diag(VDecl->getLocation(), diag::warn_extern_init);
11373 
11374     // C99 6.7.8p4. All file scoped initializers need to be constant.
11375     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11376       CheckForConstantInitializer(Init, DclT);
11377   }
11378 
11379   // We will represent direct-initialization similarly to copy-initialization:
11380   //    int x(1);  -as-> int x = 1;
11381   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11382   //
11383   // Clients that want to distinguish between the two forms, can check for
11384   // direct initializer using VarDecl::getInitStyle().
11385   // A major benefit is that clients that don't particularly care about which
11386   // exactly form was it (like the CodeGen) can handle both cases without
11387   // special case code.
11388 
11389   // C++ 8.5p11:
11390   // The form of initialization (using parentheses or '=') is generally
11391   // insignificant, but does matter when the entity being initialized has a
11392   // class type.
11393   if (CXXDirectInit) {
11394     assert(DirectInit && "Call-style initializer must be direct init.");
11395     VDecl->setInitStyle(VarDecl::CallInit);
11396   } else if (DirectInit) {
11397     // This must be list-initialization. No other way is direct-initialization.
11398     VDecl->setInitStyle(VarDecl::ListInit);
11399   }
11400 
11401   CheckCompleteVariableDeclaration(VDecl);
11402 }
11403 
11404 /// ActOnInitializerError - Given that there was an error parsing an
11405 /// initializer for the given declaration, try to return to some form
11406 /// of sanity.
11407 void Sema::ActOnInitializerError(Decl *D) {
11408   // Our main concern here is re-establishing invariants like "a
11409   // variable's type is either dependent or complete".
11410   if (!D || D->isInvalidDecl()) return;
11411 
11412   VarDecl *VD = dyn_cast<VarDecl>(D);
11413   if (!VD) return;
11414 
11415   // Bindings are not usable if we can't make sense of the initializer.
11416   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11417     for (auto *BD : DD->bindings())
11418       BD->setInvalidDecl();
11419 
11420   // Auto types are meaningless if we can't make sense of the initializer.
11421   if (ParsingInitForAutoVars.count(D)) {
11422     D->setInvalidDecl();
11423     return;
11424   }
11425 
11426   QualType Ty = VD->getType();
11427   if (Ty->isDependentType()) return;
11428 
11429   // Require a complete type.
11430   if (RequireCompleteType(VD->getLocation(),
11431                           Context.getBaseElementType(Ty),
11432                           diag::err_typecheck_decl_incomplete_type)) {
11433     VD->setInvalidDecl();
11434     return;
11435   }
11436 
11437   // Require a non-abstract type.
11438   if (RequireNonAbstractType(VD->getLocation(), Ty,
11439                              diag::err_abstract_type_in_decl,
11440                              AbstractVariableType)) {
11441     VD->setInvalidDecl();
11442     return;
11443   }
11444 
11445   // Don't bother complaining about constructors or destructors,
11446   // though.
11447 }
11448 
11449 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11450   // If there is no declaration, there was an error parsing it. Just ignore it.
11451   if (!RealDecl)
11452     return;
11453 
11454   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11455     QualType Type = Var->getType();
11456 
11457     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11458     if (isa<DecompositionDecl>(RealDecl)) {
11459       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11460       Var->setInvalidDecl();
11461       return;
11462     }
11463 
11464     Expr *TmpInit = nullptr;
11465     if (Type->isUndeducedType() &&
11466         DeduceVariableDeclarationType(Var, false, TmpInit))
11467       return;
11468 
11469     // C++11 [class.static.data]p3: A static data member can be declared with
11470     // the constexpr specifier; if so, its declaration shall specify
11471     // a brace-or-equal-initializer.
11472     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11473     // the definition of a variable [...] or the declaration of a static data
11474     // member.
11475     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11476         !Var->isThisDeclarationADemotedDefinition()) {
11477       if (Var->isStaticDataMember()) {
11478         // C++1z removes the relevant rule; the in-class declaration is always
11479         // a definition there.
11480         if (!getLangOpts().CPlusPlus17) {
11481           Diag(Var->getLocation(),
11482                diag::err_constexpr_static_mem_var_requires_init)
11483             << Var->getDeclName();
11484           Var->setInvalidDecl();
11485           return;
11486         }
11487       } else {
11488         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11489         Var->setInvalidDecl();
11490         return;
11491       }
11492     }
11493 
11494     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11495     // be initialized.
11496     if (!Var->isInvalidDecl() &&
11497         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11498         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11499       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11500       Var->setInvalidDecl();
11501       return;
11502     }
11503 
11504     switch (Var->isThisDeclarationADefinition()) {
11505     case VarDecl::Definition:
11506       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11507         break;
11508 
11509       // We have an out-of-line definition of a static data member
11510       // that has an in-class initializer, so we type-check this like
11511       // a declaration.
11512       //
11513       LLVM_FALLTHROUGH;
11514 
11515     case VarDecl::DeclarationOnly:
11516       // It's only a declaration.
11517 
11518       // Block scope. C99 6.7p7: If an identifier for an object is
11519       // declared with no linkage (C99 6.2.2p6), the type for the
11520       // object shall be complete.
11521       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11522           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11523           RequireCompleteType(Var->getLocation(), Type,
11524                               diag::err_typecheck_decl_incomplete_type))
11525         Var->setInvalidDecl();
11526 
11527       // Make sure that the type is not abstract.
11528       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11529           RequireNonAbstractType(Var->getLocation(), Type,
11530                                  diag::err_abstract_type_in_decl,
11531                                  AbstractVariableType))
11532         Var->setInvalidDecl();
11533       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11534           Var->getStorageClass() == SC_PrivateExtern) {
11535         Diag(Var->getLocation(), diag::warn_private_extern);
11536         Diag(Var->getLocation(), diag::note_private_extern);
11537       }
11538 
11539       return;
11540 
11541     case VarDecl::TentativeDefinition:
11542       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11543       // object that has file scope without an initializer, and without a
11544       // storage-class specifier or with the storage-class specifier "static",
11545       // constitutes a tentative definition. Note: A tentative definition with
11546       // external linkage is valid (C99 6.2.2p5).
11547       if (!Var->isInvalidDecl()) {
11548         if (const IncompleteArrayType *ArrayT
11549                                     = Context.getAsIncompleteArrayType(Type)) {
11550           if (RequireCompleteType(Var->getLocation(),
11551                                   ArrayT->getElementType(),
11552                                   diag::err_illegal_decl_array_incomplete_type))
11553             Var->setInvalidDecl();
11554         } else if (Var->getStorageClass() == SC_Static) {
11555           // C99 6.9.2p3: If the declaration of an identifier for an object is
11556           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11557           // declared type shall not be an incomplete type.
11558           // NOTE: code such as the following
11559           //     static struct s;
11560           //     struct s { int a; };
11561           // is accepted by gcc. Hence here we issue a warning instead of
11562           // an error and we do not invalidate the static declaration.
11563           // NOTE: to avoid multiple warnings, only check the first declaration.
11564           if (Var->isFirstDecl())
11565             RequireCompleteType(Var->getLocation(), Type,
11566                                 diag::ext_typecheck_decl_incomplete_type);
11567         }
11568       }
11569 
11570       // Record the tentative definition; we're done.
11571       if (!Var->isInvalidDecl())
11572         TentativeDefinitions.push_back(Var);
11573       return;
11574     }
11575 
11576     // Provide a specific diagnostic for uninitialized variable
11577     // definitions with incomplete array type.
11578     if (Type->isIncompleteArrayType()) {
11579       Diag(Var->getLocation(),
11580            diag::err_typecheck_incomplete_array_needs_initializer);
11581       Var->setInvalidDecl();
11582       return;
11583     }
11584 
11585     // Provide a specific diagnostic for uninitialized variable
11586     // definitions with reference type.
11587     if (Type->isReferenceType()) {
11588       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11589         << Var->getDeclName()
11590         << SourceRange(Var->getLocation(), Var->getLocation());
11591       Var->setInvalidDecl();
11592       return;
11593     }
11594 
11595     // Do not attempt to type-check the default initializer for a
11596     // variable with dependent type.
11597     if (Type->isDependentType())
11598       return;
11599 
11600     if (Var->isInvalidDecl())
11601       return;
11602 
11603     if (!Var->hasAttr<AliasAttr>()) {
11604       if (RequireCompleteType(Var->getLocation(),
11605                               Context.getBaseElementType(Type),
11606                               diag::err_typecheck_decl_incomplete_type)) {
11607         Var->setInvalidDecl();
11608         return;
11609       }
11610     } else {
11611       return;
11612     }
11613 
11614     // The variable can not have an abstract class type.
11615     if (RequireNonAbstractType(Var->getLocation(), Type,
11616                                diag::err_abstract_type_in_decl,
11617                                AbstractVariableType)) {
11618       Var->setInvalidDecl();
11619       return;
11620     }
11621 
11622     // Check for jumps past the implicit initializer.  C++0x
11623     // clarifies that this applies to a "variable with automatic
11624     // storage duration", not a "local variable".
11625     // C++11 [stmt.dcl]p3
11626     //   A program that jumps from a point where a variable with automatic
11627     //   storage duration is not in scope to a point where it is in scope is
11628     //   ill-formed unless the variable has scalar type, class type with a
11629     //   trivial default constructor and a trivial destructor, a cv-qualified
11630     //   version of one of these types, or an array of one of the preceding
11631     //   types and is declared without an initializer.
11632     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11633       if (const RecordType *Record
11634             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11635         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11636         // Mark the function (if we're in one) for further checking even if the
11637         // looser rules of C++11 do not require such checks, so that we can
11638         // diagnose incompatibilities with C++98.
11639         if (!CXXRecord->isPOD())
11640           setFunctionHasBranchProtectedScope();
11641       }
11642     }
11643 
11644     // C++03 [dcl.init]p9:
11645     //   If no initializer is specified for an object, and the
11646     //   object is of (possibly cv-qualified) non-POD class type (or
11647     //   array thereof), the object shall be default-initialized; if
11648     //   the object is of const-qualified type, the underlying class
11649     //   type shall have a user-declared default
11650     //   constructor. Otherwise, if no initializer is specified for
11651     //   a non- static object, the object and its subobjects, if
11652     //   any, have an indeterminate initial value); if the object
11653     //   or any of its subobjects are of const-qualified type, the
11654     //   program is ill-formed.
11655     // C++0x [dcl.init]p11:
11656     //   If no initializer is specified for an object, the object is
11657     //   default-initialized; [...].
11658     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11659     InitializationKind Kind
11660       = InitializationKind::CreateDefault(Var->getLocation());
11661 
11662     InitializationSequence InitSeq(*this, Entity, Kind, None);
11663     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11664     if (Init.isInvalid())
11665       Var->setInvalidDecl();
11666     else if (Init.get()) {
11667       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11668       // This is important for template substitution.
11669       Var->setInitStyle(VarDecl::CallInit);
11670     }
11671 
11672     CheckCompleteVariableDeclaration(Var);
11673   }
11674 }
11675 
11676 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11677   // If there is no declaration, there was an error parsing it. Ignore it.
11678   if (!D)
11679     return;
11680 
11681   VarDecl *VD = dyn_cast<VarDecl>(D);
11682   if (!VD) {
11683     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11684     D->setInvalidDecl();
11685     return;
11686   }
11687 
11688   VD->setCXXForRangeDecl(true);
11689 
11690   // for-range-declaration cannot be given a storage class specifier.
11691   int Error = -1;
11692   switch (VD->getStorageClass()) {
11693   case SC_None:
11694     break;
11695   case SC_Extern:
11696     Error = 0;
11697     break;
11698   case SC_Static:
11699     Error = 1;
11700     break;
11701   case SC_PrivateExtern:
11702     Error = 2;
11703     break;
11704   case SC_Auto:
11705     Error = 3;
11706     break;
11707   case SC_Register:
11708     Error = 4;
11709     break;
11710   }
11711   if (Error != -1) {
11712     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11713       << VD->getDeclName() << Error;
11714     D->setInvalidDecl();
11715   }
11716 }
11717 
11718 StmtResult
11719 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11720                                  IdentifierInfo *Ident,
11721                                  ParsedAttributes &Attrs,
11722                                  SourceLocation AttrEnd) {
11723   // C++1y [stmt.iter]p1:
11724   //   A range-based for statement of the form
11725   //      for ( for-range-identifier : for-range-initializer ) statement
11726   //   is equivalent to
11727   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11728   DeclSpec DS(Attrs.getPool().getFactory());
11729 
11730   const char *PrevSpec;
11731   unsigned DiagID;
11732   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11733                      getPrintingPolicy());
11734 
11735   Declarator D(DS, DeclaratorContext::ForContext);
11736   D.SetIdentifier(Ident, IdentLoc);
11737   D.takeAttributes(Attrs, AttrEnd);
11738 
11739   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11740   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11741                 IdentLoc);
11742   Decl *Var = ActOnDeclarator(S, D);
11743   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11744   FinalizeDeclaration(Var);
11745   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11746                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11747 }
11748 
11749 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11750   if (var->isInvalidDecl()) return;
11751 
11752   if (getLangOpts().OpenCL) {
11753     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11754     // initialiser
11755     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11756         !var->hasInit()) {
11757       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11758           << 1 /*Init*/;
11759       var->setInvalidDecl();
11760       return;
11761     }
11762   }
11763 
11764   // In Objective-C, don't allow jumps past the implicit initialization of a
11765   // local retaining variable.
11766   if (getLangOpts().ObjC &&
11767       var->hasLocalStorage()) {
11768     switch (var->getType().getObjCLifetime()) {
11769     case Qualifiers::OCL_None:
11770     case Qualifiers::OCL_ExplicitNone:
11771     case Qualifiers::OCL_Autoreleasing:
11772       break;
11773 
11774     case Qualifiers::OCL_Weak:
11775     case Qualifiers::OCL_Strong:
11776       setFunctionHasBranchProtectedScope();
11777       break;
11778     }
11779   }
11780 
11781   if (var->hasLocalStorage() &&
11782       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11783     setFunctionHasBranchProtectedScope();
11784 
11785   // Warn about externally-visible variables being defined without a
11786   // prior declaration.  We only want to do this for global
11787   // declarations, but we also specifically need to avoid doing it for
11788   // class members because the linkage of an anonymous class can
11789   // change if it's later given a typedef name.
11790   if (var->isThisDeclarationADefinition() &&
11791       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11792       var->isExternallyVisible() && var->hasLinkage() &&
11793       !var->isInline() && !var->getDescribedVarTemplate() &&
11794       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11795       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11796                                   var->getLocation())) {
11797     // Find a previous declaration that's not a definition.
11798     VarDecl *prev = var->getPreviousDecl();
11799     while (prev && prev->isThisDeclarationADefinition())
11800       prev = prev->getPreviousDecl();
11801 
11802     if (!prev)
11803       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11804   }
11805 
11806   // Cache the result of checking for constant initialization.
11807   Optional<bool> CacheHasConstInit;
11808   const Expr *CacheCulprit;
11809   auto checkConstInit = [&]() mutable {
11810     if (!CacheHasConstInit)
11811       CacheHasConstInit = var->getInit()->isConstantInitializer(
11812             Context, var->getType()->isReferenceType(), &CacheCulprit);
11813     return *CacheHasConstInit;
11814   };
11815 
11816   if (var->getTLSKind() == VarDecl::TLS_Static) {
11817     if (var->getType().isDestructedType()) {
11818       // GNU C++98 edits for __thread, [basic.start.term]p3:
11819       //   The type of an object with thread storage duration shall not
11820       //   have a non-trivial destructor.
11821       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11822       if (getLangOpts().CPlusPlus11)
11823         Diag(var->getLocation(), diag::note_use_thread_local);
11824     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11825       if (!checkConstInit()) {
11826         // GNU C++98 edits for __thread, [basic.start.init]p4:
11827         //   An object of thread storage duration shall not require dynamic
11828         //   initialization.
11829         // FIXME: Need strict checking here.
11830         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11831           << CacheCulprit->getSourceRange();
11832         if (getLangOpts().CPlusPlus11)
11833           Diag(var->getLocation(), diag::note_use_thread_local);
11834       }
11835     }
11836   }
11837 
11838   // Apply section attributes and pragmas to global variables.
11839   bool GlobalStorage = var->hasGlobalStorage();
11840   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11841       !inTemplateInstantiation()) {
11842     PragmaStack<StringLiteral *> *Stack = nullptr;
11843     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11844     if (var->getType().isConstQualified())
11845       Stack = &ConstSegStack;
11846     else if (!var->getInit()) {
11847       Stack = &BSSSegStack;
11848       SectionFlags |= ASTContext::PSF_Write;
11849     } else {
11850       Stack = &DataSegStack;
11851       SectionFlags |= ASTContext::PSF_Write;
11852     }
11853     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11854       var->addAttr(SectionAttr::CreateImplicit(
11855           Context, SectionAttr::Declspec_allocate,
11856           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11857     }
11858     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11859       if (UnifySection(SA->getName(), SectionFlags, var))
11860         var->dropAttr<SectionAttr>();
11861 
11862     // Apply the init_seg attribute if this has an initializer.  If the
11863     // initializer turns out to not be dynamic, we'll end up ignoring this
11864     // attribute.
11865     if (CurInitSeg && var->getInit())
11866       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11867                                                CurInitSegLoc));
11868   }
11869 
11870   // All the following checks are C++ only.
11871   if (!getLangOpts().CPlusPlus) {
11872       // If this variable must be emitted, add it as an initializer for the
11873       // current module.
11874      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11875        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11876      return;
11877   }
11878 
11879   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11880     CheckCompleteDecompositionDeclaration(DD);
11881 
11882   QualType type = var->getType();
11883   if (type->isDependentType()) return;
11884 
11885   if (var->hasAttr<BlocksAttr>())
11886     getCurFunction()->addByrefBlockVar(var);
11887 
11888   Expr *Init = var->getInit();
11889   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11890   QualType baseType = Context.getBaseElementType(type);
11891 
11892   if (Init && !Init->isValueDependent()) {
11893     if (var->isConstexpr()) {
11894       SmallVector<PartialDiagnosticAt, 8> Notes;
11895       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11896         SourceLocation DiagLoc = var->getLocation();
11897         // If the note doesn't add any useful information other than a source
11898         // location, fold it into the primary diagnostic.
11899         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11900               diag::note_invalid_subexpr_in_const_expr) {
11901           DiagLoc = Notes[0].first;
11902           Notes.clear();
11903         }
11904         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11905           << var << Init->getSourceRange();
11906         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11907           Diag(Notes[I].first, Notes[I].second);
11908       }
11909     } else if (var->isUsableInConstantExpressions(Context)) {
11910       // Check whether the initializer of a const variable of integral or
11911       // enumeration type is an ICE now, since we can't tell whether it was
11912       // initialized by a constant expression if we check later.
11913       var->checkInitIsICE();
11914     }
11915 
11916     // Don't emit further diagnostics about constexpr globals since they
11917     // were just diagnosed.
11918     if (!var->isConstexpr() && GlobalStorage &&
11919             var->hasAttr<RequireConstantInitAttr>()) {
11920       // FIXME: Need strict checking in C++03 here.
11921       bool DiagErr = getLangOpts().CPlusPlus11
11922           ? !var->checkInitIsICE() : !checkConstInit();
11923       if (DiagErr) {
11924         auto attr = var->getAttr<RequireConstantInitAttr>();
11925         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11926           << Init->getSourceRange();
11927         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11928           << attr->getRange();
11929         if (getLangOpts().CPlusPlus11) {
11930           APValue Value;
11931           SmallVector<PartialDiagnosticAt, 8> Notes;
11932           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11933           for (auto &it : Notes)
11934             Diag(it.first, it.second);
11935         } else {
11936           Diag(CacheCulprit->getExprLoc(),
11937                diag::note_invalid_subexpr_in_const_expr)
11938               << CacheCulprit->getSourceRange();
11939         }
11940       }
11941     }
11942     else if (!var->isConstexpr() && IsGlobal &&
11943              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11944                                     var->getLocation())) {
11945       // Warn about globals which don't have a constant initializer.  Don't
11946       // warn about globals with a non-trivial destructor because we already
11947       // warned about them.
11948       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11949       if (!(RD && !RD->hasTrivialDestructor())) {
11950         if (!checkConstInit())
11951           Diag(var->getLocation(), diag::warn_global_constructor)
11952             << Init->getSourceRange();
11953       }
11954     }
11955   }
11956 
11957   // Require the destructor.
11958   if (const RecordType *recordType = baseType->getAs<RecordType>())
11959     FinalizeVarWithDestructor(var, recordType);
11960 
11961   // If this variable must be emitted, add it as an initializer for the current
11962   // module.
11963   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11964     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11965 }
11966 
11967 /// Determines if a variable's alignment is dependent.
11968 static bool hasDependentAlignment(VarDecl *VD) {
11969   if (VD->getType()->isDependentType())
11970     return true;
11971   for (auto *I : VD->specific_attrs<AlignedAttr>())
11972     if (I->isAlignmentDependent())
11973       return true;
11974   return false;
11975 }
11976 
11977 /// Check if VD needs to be dllexport/dllimport due to being in a
11978 /// dllexport/import function.
11979 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
11980   assert(VD->isStaticLocal());
11981 
11982   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11983 
11984   // Find outermost function when VD is in lambda function.
11985   while (FD && !getDLLAttr(FD) &&
11986          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
11987          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
11988     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
11989   }
11990 
11991   if (!FD)
11992     return;
11993 
11994   // Static locals inherit dll attributes from their function.
11995   if (Attr *A = getDLLAttr(FD)) {
11996     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11997     NewAttr->setInherited(true);
11998     VD->addAttr(NewAttr);
11999   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12000     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12001                                                           getASTContext(),
12002                                                           A->getSpellingListIndex());
12003     NewAttr->setInherited(true);
12004     VD->addAttr(NewAttr);
12005 
12006     // Export this function to enforce exporting this static variable even
12007     // if it is not used in this compilation unit.
12008     if (!FD->hasAttr<DLLExportAttr>())
12009       FD->addAttr(NewAttr);
12010 
12011   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12012     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12013                                                           getASTContext(),
12014                                                           A->getSpellingListIndex());
12015     NewAttr->setInherited(true);
12016     VD->addAttr(NewAttr);
12017   }
12018 }
12019 
12020 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12021 /// any semantic actions necessary after any initializer has been attached.
12022 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12023   // Note that we are no longer parsing the initializer for this declaration.
12024   ParsingInitForAutoVars.erase(ThisDecl);
12025 
12026   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12027   if (!VD)
12028     return;
12029 
12030   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12031   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12032       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12033     if (PragmaClangBSSSection.Valid)
12034       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12035                                                             PragmaClangBSSSection.SectionName,
12036                                                             PragmaClangBSSSection.PragmaLocation));
12037     if (PragmaClangDataSection.Valid)
12038       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12039                                                              PragmaClangDataSection.SectionName,
12040                                                              PragmaClangDataSection.PragmaLocation));
12041     if (PragmaClangRodataSection.Valid)
12042       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12043                                                                PragmaClangRodataSection.SectionName,
12044                                                                PragmaClangRodataSection.PragmaLocation));
12045   }
12046 
12047   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12048     for (auto *BD : DD->bindings()) {
12049       FinalizeDeclaration(BD);
12050     }
12051   }
12052 
12053   checkAttributesAfterMerging(*this, *VD);
12054 
12055   // Perform TLS alignment check here after attributes attached to the variable
12056   // which may affect the alignment have been processed. Only perform the check
12057   // if the target has a maximum TLS alignment (zero means no constraints).
12058   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12059     // Protect the check so that it's not performed on dependent types and
12060     // dependent alignments (we can't determine the alignment in that case).
12061     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12062         !VD->isInvalidDecl()) {
12063       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12064       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12065         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12066           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12067           << (unsigned)MaxAlignChars.getQuantity();
12068       }
12069     }
12070   }
12071 
12072   if (VD->isStaticLocal()) {
12073     CheckStaticLocalForDllExport(VD);
12074 
12075     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12076       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12077       // function, only __shared__ variables or variables without any device
12078       // memory qualifiers may be declared with static storage class.
12079       // Note: It is unclear how a function-scope non-const static variable
12080       // without device memory qualifier is implemented, therefore only static
12081       // const variable without device memory qualifier is allowed.
12082       [&]() {
12083         if (!getLangOpts().CUDA)
12084           return;
12085         if (VD->hasAttr<CUDASharedAttr>())
12086           return;
12087         if (VD->getType().isConstQualified() &&
12088             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12089           return;
12090         if (CUDADiagIfDeviceCode(VD->getLocation(),
12091                                  diag::err_device_static_local_var)
12092             << CurrentCUDATarget())
12093           VD->setInvalidDecl();
12094       }();
12095     }
12096   }
12097 
12098   // Perform check for initializers of device-side global variables.
12099   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12100   // 7.5). We must also apply the same checks to all __shared__
12101   // variables whether they are local or not. CUDA also allows
12102   // constant initializers for __constant__ and __device__ variables.
12103   if (getLangOpts().CUDA)
12104     checkAllowedCUDAInitializer(VD);
12105 
12106   // Grab the dllimport or dllexport attribute off of the VarDecl.
12107   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12108 
12109   // Imported static data members cannot be defined out-of-line.
12110   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12111     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12112         VD->isThisDeclarationADefinition()) {
12113       // We allow definitions of dllimport class template static data members
12114       // with a warning.
12115       CXXRecordDecl *Context =
12116         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12117       bool IsClassTemplateMember =
12118           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12119           Context->getDescribedClassTemplate();
12120 
12121       Diag(VD->getLocation(),
12122            IsClassTemplateMember
12123                ? diag::warn_attribute_dllimport_static_field_definition
12124                : diag::err_attribute_dllimport_static_field_definition);
12125       Diag(IA->getLocation(), diag::note_attribute);
12126       if (!IsClassTemplateMember)
12127         VD->setInvalidDecl();
12128     }
12129   }
12130 
12131   // dllimport/dllexport variables cannot be thread local, their TLS index
12132   // isn't exported with the variable.
12133   if (DLLAttr && VD->getTLSKind()) {
12134     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12135     if (F && getDLLAttr(F)) {
12136       assert(VD->isStaticLocal());
12137       // But if this is a static local in a dlimport/dllexport function, the
12138       // function will never be inlined, which means the var would never be
12139       // imported, so having it marked import/export is safe.
12140     } else {
12141       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12142                                                                     << DLLAttr;
12143       VD->setInvalidDecl();
12144     }
12145   }
12146 
12147   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12148     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12149       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12150       VD->dropAttr<UsedAttr>();
12151     }
12152   }
12153 
12154   const DeclContext *DC = VD->getDeclContext();
12155   // If there's a #pragma GCC visibility in scope, and this isn't a class
12156   // member, set the visibility of this variable.
12157   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12158     AddPushedVisibilityAttribute(VD);
12159 
12160   // FIXME: Warn on unused var template partial specializations.
12161   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12162     MarkUnusedFileScopedDecl(VD);
12163 
12164   // Now we have parsed the initializer and can update the table of magic
12165   // tag values.
12166   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12167       !VD->getType()->isIntegralOrEnumerationType())
12168     return;
12169 
12170   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12171     const Expr *MagicValueExpr = VD->getInit();
12172     if (!MagicValueExpr) {
12173       continue;
12174     }
12175     llvm::APSInt MagicValueInt;
12176     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12177       Diag(I->getRange().getBegin(),
12178            diag::err_type_tag_for_datatype_not_ice)
12179         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12180       continue;
12181     }
12182     if (MagicValueInt.getActiveBits() > 64) {
12183       Diag(I->getRange().getBegin(),
12184            diag::err_type_tag_for_datatype_too_large)
12185         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12186       continue;
12187     }
12188     uint64_t MagicValue = MagicValueInt.getZExtValue();
12189     RegisterTypeTagForDatatype(I->getArgumentKind(),
12190                                MagicValue,
12191                                I->getMatchingCType(),
12192                                I->getLayoutCompatible(),
12193                                I->getMustBeNull());
12194   }
12195 }
12196 
12197 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12198   auto *VD = dyn_cast<VarDecl>(DD);
12199   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12200 }
12201 
12202 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12203                                                    ArrayRef<Decl *> Group) {
12204   SmallVector<Decl*, 8> Decls;
12205 
12206   if (DS.isTypeSpecOwned())
12207     Decls.push_back(DS.getRepAsDecl());
12208 
12209   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12210   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12211   bool DiagnosedMultipleDecomps = false;
12212   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12213   bool DiagnosedNonDeducedAuto = false;
12214 
12215   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12216     if (Decl *D = Group[i]) {
12217       // For declarators, there are some additional syntactic-ish checks we need
12218       // to perform.
12219       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12220         if (!FirstDeclaratorInGroup)
12221           FirstDeclaratorInGroup = DD;
12222         if (!FirstDecompDeclaratorInGroup)
12223           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12224         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12225             !hasDeducedAuto(DD))
12226           FirstNonDeducedAutoInGroup = DD;
12227 
12228         if (FirstDeclaratorInGroup != DD) {
12229           // A decomposition declaration cannot be combined with any other
12230           // declaration in the same group.
12231           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12232             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12233                  diag::err_decomp_decl_not_alone)
12234                 << FirstDeclaratorInGroup->getSourceRange()
12235                 << DD->getSourceRange();
12236             DiagnosedMultipleDecomps = true;
12237           }
12238 
12239           // A declarator that uses 'auto' in any way other than to declare a
12240           // variable with a deduced type cannot be combined with any other
12241           // declarator in the same group.
12242           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12243             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12244                  diag::err_auto_non_deduced_not_alone)
12245                 << FirstNonDeducedAutoInGroup->getType()
12246                        ->hasAutoForTrailingReturnType()
12247                 << FirstDeclaratorInGroup->getSourceRange()
12248                 << DD->getSourceRange();
12249             DiagnosedNonDeducedAuto = true;
12250           }
12251         }
12252       }
12253 
12254       Decls.push_back(D);
12255     }
12256   }
12257 
12258   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12259     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12260       handleTagNumbering(Tag, S);
12261       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12262           getLangOpts().CPlusPlus)
12263         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12264     }
12265   }
12266 
12267   return BuildDeclaratorGroup(Decls);
12268 }
12269 
12270 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12271 /// group, performing any necessary semantic checking.
12272 Sema::DeclGroupPtrTy
12273 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12274   // C++14 [dcl.spec.auto]p7: (DR1347)
12275   //   If the type that replaces the placeholder type is not the same in each
12276   //   deduction, the program is ill-formed.
12277   if (Group.size() > 1) {
12278     QualType Deduced;
12279     VarDecl *DeducedDecl = nullptr;
12280     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12281       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12282       if (!D || D->isInvalidDecl())
12283         break;
12284       DeducedType *DT = D->getType()->getContainedDeducedType();
12285       if (!DT || DT->getDeducedType().isNull())
12286         continue;
12287       if (Deduced.isNull()) {
12288         Deduced = DT->getDeducedType();
12289         DeducedDecl = D;
12290       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12291         auto *AT = dyn_cast<AutoType>(DT);
12292         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12293              diag::err_auto_different_deductions)
12294           << (AT ? (unsigned)AT->getKeyword() : 3)
12295           << Deduced << DeducedDecl->getDeclName()
12296           << DT->getDeducedType() << D->getDeclName()
12297           << DeducedDecl->getInit()->getSourceRange()
12298           << D->getInit()->getSourceRange();
12299         D->setInvalidDecl();
12300         break;
12301       }
12302     }
12303   }
12304 
12305   ActOnDocumentableDecls(Group);
12306 
12307   return DeclGroupPtrTy::make(
12308       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12309 }
12310 
12311 void Sema::ActOnDocumentableDecl(Decl *D) {
12312   ActOnDocumentableDecls(D);
12313 }
12314 
12315 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12316   // Don't parse the comment if Doxygen diagnostics are ignored.
12317   if (Group.empty() || !Group[0])
12318     return;
12319 
12320   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12321                       Group[0]->getLocation()) &&
12322       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12323                       Group[0]->getLocation()))
12324     return;
12325 
12326   if (Group.size() >= 2) {
12327     // This is a decl group.  Normally it will contain only declarations
12328     // produced from declarator list.  But in case we have any definitions or
12329     // additional declaration references:
12330     //   'typedef struct S {} S;'
12331     //   'typedef struct S *S;'
12332     //   'struct S *pS;'
12333     // FinalizeDeclaratorGroup adds these as separate declarations.
12334     Decl *MaybeTagDecl = Group[0];
12335     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12336       Group = Group.slice(1);
12337     }
12338   }
12339 
12340   // See if there are any new comments that are not attached to a decl.
12341   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12342   if (!Comments.empty() &&
12343       !Comments.back()->isAttached()) {
12344     // There is at least one comment that not attached to a decl.
12345     // Maybe it should be attached to one of these decls?
12346     //
12347     // Note that this way we pick up not only comments that precede the
12348     // declaration, but also comments that *follow* the declaration -- thanks to
12349     // the lookahead in the lexer: we've consumed the semicolon and looked
12350     // ahead through comments.
12351     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12352       Context.getCommentForDecl(Group[i], &PP);
12353   }
12354 }
12355 
12356 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12357 /// to introduce parameters into function prototype scope.
12358 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12359   const DeclSpec &DS = D.getDeclSpec();
12360 
12361   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12362 
12363   // C++03 [dcl.stc]p2 also permits 'auto'.
12364   StorageClass SC = SC_None;
12365   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12366     SC = SC_Register;
12367     // In C++11, the 'register' storage class specifier is deprecated.
12368     // In C++17, it is not allowed, but we tolerate it as an extension.
12369     if (getLangOpts().CPlusPlus11) {
12370       Diag(DS.getStorageClassSpecLoc(),
12371            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12372                                      : diag::warn_deprecated_register)
12373         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12374     }
12375   } else if (getLangOpts().CPlusPlus &&
12376              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12377     SC = SC_Auto;
12378   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12379     Diag(DS.getStorageClassSpecLoc(),
12380          diag::err_invalid_storage_class_in_func_decl);
12381     D.getMutableDeclSpec().ClearStorageClassSpecs();
12382   }
12383 
12384   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12385     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12386       << DeclSpec::getSpecifierName(TSCS);
12387   if (DS.isInlineSpecified())
12388     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12389         << getLangOpts().CPlusPlus17;
12390   if (DS.isConstexprSpecified())
12391     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12392       << 0;
12393 
12394   DiagnoseFunctionSpecifiers(DS);
12395 
12396   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12397   QualType parmDeclType = TInfo->getType();
12398 
12399   if (getLangOpts().CPlusPlus) {
12400     // Check that there are no default arguments inside the type of this
12401     // parameter.
12402     CheckExtraCXXDefaultArguments(D);
12403 
12404     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12405     if (D.getCXXScopeSpec().isSet()) {
12406       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12407         << D.getCXXScopeSpec().getRange();
12408       D.getCXXScopeSpec().clear();
12409     }
12410   }
12411 
12412   // Ensure we have a valid name
12413   IdentifierInfo *II = nullptr;
12414   if (D.hasName()) {
12415     II = D.getIdentifier();
12416     if (!II) {
12417       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12418         << GetNameForDeclarator(D).getName();
12419       D.setInvalidType(true);
12420     }
12421   }
12422 
12423   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12424   if (II) {
12425     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12426                    ForVisibleRedeclaration);
12427     LookupName(R, S);
12428     if (R.isSingleResult()) {
12429       NamedDecl *PrevDecl = R.getFoundDecl();
12430       if (PrevDecl->isTemplateParameter()) {
12431         // Maybe we will complain about the shadowed template parameter.
12432         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12433         // Just pretend that we didn't see the previous declaration.
12434         PrevDecl = nullptr;
12435       } else if (S->isDeclScope(PrevDecl)) {
12436         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12437         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12438 
12439         // Recover by removing the name
12440         II = nullptr;
12441         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12442         D.setInvalidType(true);
12443       }
12444     }
12445   }
12446 
12447   // Temporarily put parameter variables in the translation unit, not
12448   // the enclosing context.  This prevents them from accidentally
12449   // looking like class members in C++.
12450   ParmVarDecl *New =
12451       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12452                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12453 
12454   if (D.isInvalidType())
12455     New->setInvalidDecl();
12456 
12457   assert(S->isFunctionPrototypeScope());
12458   assert(S->getFunctionPrototypeDepth() >= 1);
12459   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12460                     S->getNextFunctionPrototypeIndex());
12461 
12462   // Add the parameter declaration into this scope.
12463   S->AddDecl(New);
12464   if (II)
12465     IdResolver.AddDecl(New);
12466 
12467   ProcessDeclAttributes(S, New, D);
12468 
12469   if (D.getDeclSpec().isModulePrivateSpecified())
12470     Diag(New->getLocation(), diag::err_module_private_local)
12471       << 1 << New->getDeclName()
12472       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12473       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12474 
12475   if (New->hasAttr<BlocksAttr>()) {
12476     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12477   }
12478   return New;
12479 }
12480 
12481 /// Synthesizes a variable for a parameter arising from a
12482 /// typedef.
12483 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12484                                               SourceLocation Loc,
12485                                               QualType T) {
12486   /* FIXME: setting StartLoc == Loc.
12487      Would it be worth to modify callers so as to provide proper source
12488      location for the unnamed parameters, embedding the parameter's type? */
12489   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12490                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12491                                            SC_None, nullptr);
12492   Param->setImplicit();
12493   return Param;
12494 }
12495 
12496 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12497   // Don't diagnose unused-parameter errors in template instantiations; we
12498   // will already have done so in the template itself.
12499   if (inTemplateInstantiation())
12500     return;
12501 
12502   for (const ParmVarDecl *Parameter : Parameters) {
12503     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12504         !Parameter->hasAttr<UnusedAttr>()) {
12505       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12506         << Parameter->getDeclName();
12507     }
12508   }
12509 }
12510 
12511 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12512     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12513   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12514     return;
12515 
12516   // Warn if the return value is pass-by-value and larger than the specified
12517   // threshold.
12518   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12519     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12520     if (Size > LangOpts.NumLargeByValueCopy)
12521       Diag(D->getLocation(), diag::warn_return_value_size)
12522           << D->getDeclName() << Size;
12523   }
12524 
12525   // Warn if any parameter is pass-by-value and larger than the specified
12526   // threshold.
12527   for (const ParmVarDecl *Parameter : Parameters) {
12528     QualType T = Parameter->getType();
12529     if (T->isDependentType() || !T.isPODType(Context))
12530       continue;
12531     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12532     if (Size > LangOpts.NumLargeByValueCopy)
12533       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12534           << Parameter->getDeclName() << Size;
12535   }
12536 }
12537 
12538 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12539                                   SourceLocation NameLoc, IdentifierInfo *Name,
12540                                   QualType T, TypeSourceInfo *TSInfo,
12541                                   StorageClass SC) {
12542   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12543   if (getLangOpts().ObjCAutoRefCount &&
12544       T.getObjCLifetime() == Qualifiers::OCL_None &&
12545       T->isObjCLifetimeType()) {
12546 
12547     Qualifiers::ObjCLifetime lifetime;
12548 
12549     // Special cases for arrays:
12550     //   - if it's const, use __unsafe_unretained
12551     //   - otherwise, it's an error
12552     if (T->isArrayType()) {
12553       if (!T.isConstQualified()) {
12554         if (DelayedDiagnostics.shouldDelayDiagnostics())
12555           DelayedDiagnostics.add(
12556               sema::DelayedDiagnostic::makeForbiddenType(
12557               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12558         else
12559           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12560               << TSInfo->getTypeLoc().getSourceRange();
12561       }
12562       lifetime = Qualifiers::OCL_ExplicitNone;
12563     } else {
12564       lifetime = T->getObjCARCImplicitLifetime();
12565     }
12566     T = Context.getLifetimeQualifiedType(T, lifetime);
12567   }
12568 
12569   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12570                                          Context.getAdjustedParameterType(T),
12571                                          TSInfo, SC, nullptr);
12572 
12573   // Parameters can not be abstract class types.
12574   // For record types, this is done by the AbstractClassUsageDiagnoser once
12575   // the class has been completely parsed.
12576   if (!CurContext->isRecord() &&
12577       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12578                              AbstractParamType))
12579     New->setInvalidDecl();
12580 
12581   // Parameter declarators cannot be interface types. All ObjC objects are
12582   // passed by reference.
12583   if (T->isObjCObjectType()) {
12584     SourceLocation TypeEndLoc =
12585         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12586     Diag(NameLoc,
12587          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12588       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12589     T = Context.getObjCObjectPointerType(T);
12590     New->setType(T);
12591   }
12592 
12593   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12594   // duration shall not be qualified by an address-space qualifier."
12595   // Since all parameters have automatic store duration, they can not have
12596   // an address space.
12597   if (T.getAddressSpace() != LangAS::Default &&
12598       // OpenCL allows function arguments declared to be an array of a type
12599       // to be qualified with an address space.
12600       !(getLangOpts().OpenCL &&
12601         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12602     Diag(NameLoc, diag::err_arg_with_address_space);
12603     New->setInvalidDecl();
12604   }
12605 
12606   return New;
12607 }
12608 
12609 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12610                                            SourceLocation LocAfterDecls) {
12611   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12612 
12613   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12614   // for a K&R function.
12615   if (!FTI.hasPrototype) {
12616     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12617       --i;
12618       if (FTI.Params[i].Param == nullptr) {
12619         SmallString<256> Code;
12620         llvm::raw_svector_ostream(Code)
12621             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12622         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12623             << FTI.Params[i].Ident
12624             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12625 
12626         // Implicitly declare the argument as type 'int' for lack of a better
12627         // type.
12628         AttributeFactory attrs;
12629         DeclSpec DS(attrs);
12630         const char* PrevSpec; // unused
12631         unsigned DiagID; // unused
12632         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12633                            DiagID, Context.getPrintingPolicy());
12634         // Use the identifier location for the type source range.
12635         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12636         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12637         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12638         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12639         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12640       }
12641     }
12642   }
12643 }
12644 
12645 Decl *
12646 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12647                               MultiTemplateParamsArg TemplateParameterLists,
12648                               SkipBodyInfo *SkipBody) {
12649   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12650   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12651   Scope *ParentScope = FnBodyScope->getParent();
12652 
12653   D.setFunctionDefinitionKind(FDK_Definition);
12654   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12655   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12656 }
12657 
12658 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12659   Consumer.HandleInlineFunctionDefinition(D);
12660 }
12661 
12662 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12663                              const FunctionDecl*& PossibleZeroParamPrototype) {
12664   // Don't warn about invalid declarations.
12665   if (FD->isInvalidDecl())
12666     return false;
12667 
12668   // Or declarations that aren't global.
12669   if (!FD->isGlobal())
12670     return false;
12671 
12672   // Don't warn about C++ member functions.
12673   if (isa<CXXMethodDecl>(FD))
12674     return false;
12675 
12676   // Don't warn about 'main'.
12677   if (FD->isMain())
12678     return false;
12679 
12680   // Don't warn about inline functions.
12681   if (FD->isInlined())
12682     return false;
12683 
12684   // Don't warn about function templates.
12685   if (FD->getDescribedFunctionTemplate())
12686     return false;
12687 
12688   // Don't warn about function template specializations.
12689   if (FD->isFunctionTemplateSpecialization())
12690     return false;
12691 
12692   // Don't warn for OpenCL kernels.
12693   if (FD->hasAttr<OpenCLKernelAttr>())
12694     return false;
12695 
12696   // Don't warn on explicitly deleted functions.
12697   if (FD->isDeleted())
12698     return false;
12699 
12700   bool MissingPrototype = true;
12701   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12702        Prev; Prev = Prev->getPreviousDecl()) {
12703     // Ignore any declarations that occur in function or method
12704     // scope, because they aren't visible from the header.
12705     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12706       continue;
12707 
12708     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12709     if (FD->getNumParams() == 0)
12710       PossibleZeroParamPrototype = Prev;
12711     break;
12712   }
12713 
12714   return MissingPrototype;
12715 }
12716 
12717 void
12718 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12719                                    const FunctionDecl *EffectiveDefinition,
12720                                    SkipBodyInfo *SkipBody) {
12721   const FunctionDecl *Definition = EffectiveDefinition;
12722   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12723     // If this is a friend function defined in a class template, it does not
12724     // have a body until it is used, nevertheless it is a definition, see
12725     // [temp.inst]p2:
12726     //
12727     // ... for the purpose of determining whether an instantiated redeclaration
12728     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12729     // corresponds to a definition in the template is considered to be a
12730     // definition.
12731     //
12732     // The following code must produce redefinition error:
12733     //
12734     //     template<typename T> struct C20 { friend void func_20() {} };
12735     //     C20<int> c20i;
12736     //     void func_20() {}
12737     //
12738     for (auto I : FD->redecls()) {
12739       if (I != FD && !I->isInvalidDecl() &&
12740           I->getFriendObjectKind() != Decl::FOK_None) {
12741         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12742           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12743             // A merged copy of the same function, instantiated as a member of
12744             // the same class, is OK.
12745             if (declaresSameEntity(OrigFD, Original) &&
12746                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12747                                    cast<Decl>(FD->getLexicalDeclContext())))
12748               continue;
12749           }
12750 
12751           if (Original->isThisDeclarationADefinition()) {
12752             Definition = I;
12753             break;
12754           }
12755         }
12756       }
12757     }
12758   }
12759 
12760   if (!Definition)
12761     // Similar to friend functions a friend function template may be a
12762     // definition and do not have a body if it is instantiated in a class
12763     // template.
12764     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12765       for (auto I : FTD->redecls()) {
12766         auto D = cast<FunctionTemplateDecl>(I);
12767         if (D != FTD) {
12768           assert(!D->isThisDeclarationADefinition() &&
12769                  "More than one definition in redeclaration chain");
12770           if (D->getFriendObjectKind() != Decl::FOK_None)
12771             if (FunctionTemplateDecl *FT =
12772                                        D->getInstantiatedFromMemberTemplate()) {
12773               if (FT->isThisDeclarationADefinition()) {
12774                 Definition = D->getTemplatedDecl();
12775                 break;
12776               }
12777             }
12778         }
12779       }
12780     }
12781 
12782   if (!Definition)
12783     return;
12784 
12785   if (canRedefineFunction(Definition, getLangOpts()))
12786     return;
12787 
12788   // Don't emit an error when this is redefinition of a typo-corrected
12789   // definition.
12790   if (TypoCorrectedFunctionDefinitions.count(Definition))
12791     return;
12792 
12793   // If we don't have a visible definition of the function, and it's inline or
12794   // a template, skip the new definition.
12795   if (SkipBody && !hasVisibleDefinition(Definition) &&
12796       (Definition->getFormalLinkage() == InternalLinkage ||
12797        Definition->isInlined() ||
12798        Definition->getDescribedFunctionTemplate() ||
12799        Definition->getNumTemplateParameterLists())) {
12800     SkipBody->ShouldSkip = true;
12801     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12802     if (auto *TD = Definition->getDescribedFunctionTemplate())
12803       makeMergedDefinitionVisible(TD);
12804     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12805     return;
12806   }
12807 
12808   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12809       Definition->getStorageClass() == SC_Extern)
12810     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12811         << FD->getDeclName() << getLangOpts().CPlusPlus;
12812   else
12813     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12814 
12815   Diag(Definition->getLocation(), diag::note_previous_definition);
12816   FD->setInvalidDecl();
12817 }
12818 
12819 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12820                                    Sema &S) {
12821   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12822 
12823   LambdaScopeInfo *LSI = S.PushLambdaScope();
12824   LSI->CallOperator = CallOperator;
12825   LSI->Lambda = LambdaClass;
12826   LSI->ReturnType = CallOperator->getReturnType();
12827   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12828 
12829   if (LCD == LCD_None)
12830     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12831   else if (LCD == LCD_ByCopy)
12832     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12833   else if (LCD == LCD_ByRef)
12834     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12835   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12836 
12837   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12838   LSI->Mutable = !CallOperator->isConst();
12839 
12840   // Add the captures to the LSI so they can be noted as already
12841   // captured within tryCaptureVar.
12842   auto I = LambdaClass->field_begin();
12843   for (const auto &C : LambdaClass->captures()) {
12844     if (C.capturesVariable()) {
12845       VarDecl *VD = C.getCapturedVar();
12846       if (VD->isInitCapture())
12847         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12848       QualType CaptureType = VD->getType();
12849       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12850       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12851           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12852           /*EllipsisLoc*/C.isPackExpansion()
12853                          ? C.getEllipsisLoc() : SourceLocation(),
12854           CaptureType, /*Expr*/ nullptr);
12855 
12856     } else if (C.capturesThis()) {
12857       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12858                               /*Expr*/ nullptr,
12859                               C.getCaptureKind() == LCK_StarThis);
12860     } else {
12861       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12862     }
12863     ++I;
12864   }
12865 }
12866 
12867 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12868                                     SkipBodyInfo *SkipBody) {
12869   if (!D) {
12870     // Parsing the function declaration failed in some way. Push on a fake scope
12871     // anyway so we can try to parse the function body.
12872     PushFunctionScope();
12873     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12874     return D;
12875   }
12876 
12877   FunctionDecl *FD = nullptr;
12878 
12879   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12880     FD = FunTmpl->getTemplatedDecl();
12881   else
12882     FD = cast<FunctionDecl>(D);
12883 
12884   // Do not push if it is a lambda because one is already pushed when building
12885   // the lambda in ActOnStartOfLambdaDefinition().
12886   if (!isLambdaCallOperator(FD))
12887     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12888 
12889   // Check for defining attributes before the check for redefinition.
12890   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12891     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12892     FD->dropAttr<AliasAttr>();
12893     FD->setInvalidDecl();
12894   }
12895   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12896     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12897     FD->dropAttr<IFuncAttr>();
12898     FD->setInvalidDecl();
12899   }
12900 
12901   // See if this is a redefinition. If 'will have body' is already set, then
12902   // these checks were already performed when it was set.
12903   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12904     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12905 
12906     // If we're skipping the body, we're done. Don't enter the scope.
12907     if (SkipBody && SkipBody->ShouldSkip)
12908       return D;
12909   }
12910 
12911   // Mark this function as "will have a body eventually".  This lets users to
12912   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12913   // this function.
12914   FD->setWillHaveBody();
12915 
12916   // If we are instantiating a generic lambda call operator, push
12917   // a LambdaScopeInfo onto the function stack.  But use the information
12918   // that's already been calculated (ActOnLambdaExpr) to prime the current
12919   // LambdaScopeInfo.
12920   // When the template operator is being specialized, the LambdaScopeInfo,
12921   // has to be properly restored so that tryCaptureVariable doesn't try
12922   // and capture any new variables. In addition when calculating potential
12923   // captures during transformation of nested lambdas, it is necessary to
12924   // have the LSI properly restored.
12925   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12926     assert(inTemplateInstantiation() &&
12927            "There should be an active template instantiation on the stack "
12928            "when instantiating a generic lambda!");
12929     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12930   } else {
12931     // Enter a new function scope
12932     PushFunctionScope();
12933   }
12934 
12935   // Builtin functions cannot be defined.
12936   if (unsigned BuiltinID = FD->getBuiltinID()) {
12937     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12938         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12939       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12940       FD->setInvalidDecl();
12941     }
12942   }
12943 
12944   // The return type of a function definition must be complete
12945   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12946   QualType ResultType = FD->getReturnType();
12947   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12948       !FD->isInvalidDecl() &&
12949       RequireCompleteType(FD->getLocation(), ResultType,
12950                           diag::err_func_def_incomplete_result))
12951     FD->setInvalidDecl();
12952 
12953   if (FnBodyScope)
12954     PushDeclContext(FnBodyScope, FD);
12955 
12956   // Check the validity of our function parameters
12957   CheckParmsForFunctionDef(FD->parameters(),
12958                            /*CheckParameterNames=*/true);
12959 
12960   // Add non-parameter declarations already in the function to the current
12961   // scope.
12962   if (FnBodyScope) {
12963     for (Decl *NPD : FD->decls()) {
12964       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12965       if (!NonParmDecl)
12966         continue;
12967       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12968              "parameters should not be in newly created FD yet");
12969 
12970       // If the decl has a name, make it accessible in the current scope.
12971       if (NonParmDecl->getDeclName())
12972         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12973 
12974       // Similarly, dive into enums and fish their constants out, making them
12975       // accessible in this scope.
12976       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12977         for (auto *EI : ED->enumerators())
12978           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12979       }
12980     }
12981   }
12982 
12983   // Introduce our parameters into the function scope
12984   for (auto Param : FD->parameters()) {
12985     Param->setOwningFunction(FD);
12986 
12987     // If this has an identifier, add it to the scope stack.
12988     if (Param->getIdentifier() && FnBodyScope) {
12989       CheckShadow(FnBodyScope, Param);
12990 
12991       PushOnScopeChains(Param, FnBodyScope);
12992     }
12993   }
12994 
12995   // Ensure that the function's exception specification is instantiated.
12996   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12997     ResolveExceptionSpec(D->getLocation(), FPT);
12998 
12999   // dllimport cannot be applied to non-inline function definitions.
13000   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13001       !FD->isTemplateInstantiation()) {
13002     assert(!FD->hasAttr<DLLExportAttr>());
13003     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13004     FD->setInvalidDecl();
13005     return D;
13006   }
13007   // We want to attach documentation to original Decl (which might be
13008   // a function template).
13009   ActOnDocumentableDecl(D);
13010   if (getCurLexicalContext()->isObjCContainer() &&
13011       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13012       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13013     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13014 
13015   return D;
13016 }
13017 
13018 /// Given the set of return statements within a function body,
13019 /// compute the variables that are subject to the named return value
13020 /// optimization.
13021 ///
13022 /// Each of the variables that is subject to the named return value
13023 /// optimization will be marked as NRVO variables in the AST, and any
13024 /// return statement that has a marked NRVO variable as its NRVO candidate can
13025 /// use the named return value optimization.
13026 ///
13027 /// This function applies a very simplistic algorithm for NRVO: if every return
13028 /// statement in the scope of a variable has the same NRVO candidate, that
13029 /// candidate is an NRVO variable.
13030 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13031   ReturnStmt **Returns = Scope->Returns.data();
13032 
13033   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13034     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13035       if (!NRVOCandidate->isNRVOVariable())
13036         Returns[I]->setNRVOCandidate(nullptr);
13037     }
13038   }
13039 }
13040 
13041 bool Sema::canDelayFunctionBody(const Declarator &D) {
13042   // We can't delay parsing the body of a constexpr function template (yet).
13043   if (D.getDeclSpec().isConstexprSpecified())
13044     return false;
13045 
13046   // We can't delay parsing the body of a function template with a deduced
13047   // return type (yet).
13048   if (D.getDeclSpec().hasAutoTypeSpec()) {
13049     // If the placeholder introduces a non-deduced trailing return type,
13050     // we can still delay parsing it.
13051     if (D.getNumTypeObjects()) {
13052       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13053       if (Outer.Kind == DeclaratorChunk::Function &&
13054           Outer.Fun.hasTrailingReturnType()) {
13055         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13056         return Ty.isNull() || !Ty->isUndeducedType();
13057       }
13058     }
13059     return false;
13060   }
13061 
13062   return true;
13063 }
13064 
13065 bool Sema::canSkipFunctionBody(Decl *D) {
13066   // We cannot skip the body of a function (or function template) which is
13067   // constexpr, since we may need to evaluate its body in order to parse the
13068   // rest of the file.
13069   // We cannot skip the body of a function with an undeduced return type,
13070   // because any callers of that function need to know the type.
13071   if (const FunctionDecl *FD = D->getAsFunction()) {
13072     if (FD->isConstexpr())
13073       return false;
13074     // We can't simply call Type::isUndeducedType here, because inside template
13075     // auto can be deduced to a dependent type, which is not considered
13076     // "undeduced".
13077     if (FD->getReturnType()->getContainedDeducedType())
13078       return false;
13079   }
13080   return Consumer.shouldSkipFunctionBody(D);
13081 }
13082 
13083 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13084   if (!Decl)
13085     return nullptr;
13086   if (FunctionDecl *FD = Decl->getAsFunction())
13087     FD->setHasSkippedBody();
13088   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13089     MD->setHasSkippedBody();
13090   return Decl;
13091 }
13092 
13093 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13094   return ActOnFinishFunctionBody(D, BodyArg, false);
13095 }
13096 
13097 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13098 /// body.
13099 class ExitFunctionBodyRAII {
13100 public:
13101   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13102   ~ExitFunctionBodyRAII() {
13103     if (!IsLambda)
13104       S.PopExpressionEvaluationContext();
13105   }
13106 
13107 private:
13108   Sema &S;
13109   bool IsLambda = false;
13110 };
13111 
13112 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13113                                     bool IsInstantiation) {
13114   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13115 
13116   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13117   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13118 
13119   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
13120     CheckCompletedCoroutineBody(FD, Body);
13121 
13122   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13123   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13124   // meant to pop the context added in ActOnStartOfFunctionDef().
13125   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13126 
13127   if (FD) {
13128     FD->setBody(Body);
13129     FD->setWillHaveBody(false);
13130 
13131     if (getLangOpts().CPlusPlus14) {
13132       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13133           FD->getReturnType()->isUndeducedType()) {
13134         // If the function has a deduced result type but contains no 'return'
13135         // statements, the result type as written must be exactly 'auto', and
13136         // the deduced result type is 'void'.
13137         if (!FD->getReturnType()->getAs<AutoType>()) {
13138           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13139               << FD->getReturnType();
13140           FD->setInvalidDecl();
13141         } else {
13142           // Substitute 'void' for the 'auto' in the type.
13143           TypeLoc ResultType = getReturnTypeLoc(FD);
13144           Context.adjustDeducedFunctionResultType(
13145               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13146         }
13147       }
13148     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13149       // In C++11, we don't use 'auto' deduction rules for lambda call
13150       // operators because we don't support return type deduction.
13151       auto *LSI = getCurLambda();
13152       if (LSI->HasImplicitReturnType) {
13153         deduceClosureReturnType(*LSI);
13154 
13155         // C++11 [expr.prim.lambda]p4:
13156         //   [...] if there are no return statements in the compound-statement
13157         //   [the deduced type is] the type void
13158         QualType RetType =
13159             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13160 
13161         // Update the return type to the deduced type.
13162         const FunctionProtoType *Proto =
13163             FD->getType()->getAs<FunctionProtoType>();
13164         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13165                                             Proto->getExtProtoInfo()));
13166       }
13167     }
13168 
13169     // If the function implicitly returns zero (like 'main') or is naked,
13170     // don't complain about missing return statements.
13171     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13172       WP.disableCheckFallThrough();
13173 
13174     // MSVC permits the use of pure specifier (=0) on function definition,
13175     // defined at class scope, warn about this non-standard construct.
13176     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13177       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13178 
13179     if (!FD->isInvalidDecl()) {
13180       // Don't diagnose unused parameters of defaulted or deleted functions.
13181       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13182         DiagnoseUnusedParameters(FD->parameters());
13183       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13184                                              FD->getReturnType(), FD);
13185 
13186       // If this is a structor, we need a vtable.
13187       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13188         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13189       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13190         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13191 
13192       // Try to apply the named return value optimization. We have to check
13193       // if we can do this here because lambdas keep return statements around
13194       // to deduce an implicit return type.
13195       if (FD->getReturnType()->isRecordType() &&
13196           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13197         computeNRVO(Body, getCurFunction());
13198     }
13199 
13200     // GNU warning -Wmissing-prototypes:
13201     //   Warn if a global function is defined without a previous
13202     //   prototype declaration. This warning is issued even if the
13203     //   definition itself provides a prototype. The aim is to detect
13204     //   global functions that fail to be declared in header files.
13205     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13206     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13207       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13208 
13209       if (PossibleZeroParamPrototype) {
13210         // We found a declaration that is not a prototype,
13211         // but that could be a zero-parameter prototype
13212         if (TypeSourceInfo *TI =
13213                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13214           TypeLoc TL = TI->getTypeLoc();
13215           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13216             Diag(PossibleZeroParamPrototype->getLocation(),
13217                  diag::note_declaration_not_a_prototype)
13218                 << PossibleZeroParamPrototype
13219                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13220         }
13221       }
13222 
13223       // GNU warning -Wstrict-prototypes
13224       //   Warn if K&R function is defined without a previous declaration.
13225       //   This warning is issued only if the definition itself does not provide
13226       //   a prototype. Only K&R definitions do not provide a prototype.
13227       //   An empty list in a function declarator that is part of a definition
13228       //   of that function specifies that the function has no parameters
13229       //   (C99 6.7.5.3p14)
13230       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13231           !LangOpts.CPlusPlus) {
13232         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13233         TypeLoc TL = TI->getTypeLoc();
13234         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13235         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13236       }
13237     }
13238 
13239     // Warn on CPUDispatch with an actual body.
13240     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13241       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13242         if (!CmpndBody->body_empty())
13243           Diag(CmpndBody->body_front()->getBeginLoc(),
13244                diag::warn_dispatch_body_ignored);
13245 
13246     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13247       const CXXMethodDecl *KeyFunction;
13248       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13249           MD->isVirtual() &&
13250           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13251           MD == KeyFunction->getCanonicalDecl()) {
13252         // Update the key-function state if necessary for this ABI.
13253         if (FD->isInlined() &&
13254             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13255           Context.setNonKeyFunction(MD);
13256 
13257           // If the newly-chosen key function is already defined, then we
13258           // need to mark the vtable as used retroactively.
13259           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13260           const FunctionDecl *Definition;
13261           if (KeyFunction && KeyFunction->isDefined(Definition))
13262             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13263         } else {
13264           // We just defined they key function; mark the vtable as used.
13265           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13266         }
13267       }
13268     }
13269 
13270     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13271            "Function parsing confused");
13272   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13273     assert(MD == getCurMethodDecl() && "Method parsing confused");
13274     MD->setBody(Body);
13275     if (!MD->isInvalidDecl()) {
13276       if (!MD->hasSkippedBody())
13277         DiagnoseUnusedParameters(MD->parameters());
13278       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13279                                              MD->getReturnType(), MD);
13280 
13281       if (Body)
13282         computeNRVO(Body, getCurFunction());
13283     }
13284     if (getCurFunction()->ObjCShouldCallSuper) {
13285       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13286           << MD->getSelector().getAsString();
13287       getCurFunction()->ObjCShouldCallSuper = false;
13288     }
13289     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13290       const ObjCMethodDecl *InitMethod = nullptr;
13291       bool isDesignated =
13292           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13293       assert(isDesignated && InitMethod);
13294       (void)isDesignated;
13295 
13296       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13297         auto IFace = MD->getClassInterface();
13298         if (!IFace)
13299           return false;
13300         auto SuperD = IFace->getSuperClass();
13301         if (!SuperD)
13302           return false;
13303         return SuperD->getIdentifier() ==
13304             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13305       };
13306       // Don't issue this warning for unavailable inits or direct subclasses
13307       // of NSObject.
13308       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13309         Diag(MD->getLocation(),
13310              diag::warn_objc_designated_init_missing_super_call);
13311         Diag(InitMethod->getLocation(),
13312              diag::note_objc_designated_init_marked_here);
13313       }
13314       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13315     }
13316     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13317       // Don't issue this warning for unavaialable inits.
13318       if (!MD->isUnavailable())
13319         Diag(MD->getLocation(),
13320              diag::warn_objc_secondary_init_missing_init_call);
13321       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13322     }
13323   } else {
13324     // Parsing the function declaration failed in some way. Pop the fake scope
13325     // we pushed on.
13326     PopFunctionScopeInfo(ActivePolicy, dcl);
13327     return nullptr;
13328   }
13329 
13330   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13331     DiagnoseUnguardedAvailabilityViolations(dcl);
13332 
13333   assert(!getCurFunction()->ObjCShouldCallSuper &&
13334          "This should only be set for ObjC methods, which should have been "
13335          "handled in the block above.");
13336 
13337   // Verify and clean out per-function state.
13338   if (Body && (!FD || !FD->isDefaulted())) {
13339     // C++ constructors that have function-try-blocks can't have return
13340     // statements in the handlers of that block. (C++ [except.handle]p14)
13341     // Verify this.
13342     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13343       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13344 
13345     // Verify that gotos and switch cases don't jump into scopes illegally.
13346     if (getCurFunction()->NeedsScopeChecking() &&
13347         !PP.isCodeCompletionEnabled())
13348       DiagnoseInvalidJumps(Body);
13349 
13350     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13351       if (!Destructor->getParent()->isDependentType())
13352         CheckDestructor(Destructor);
13353 
13354       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13355                                              Destructor->getParent());
13356     }
13357 
13358     // If any errors have occurred, clear out any temporaries that may have
13359     // been leftover. This ensures that these temporaries won't be picked up for
13360     // deletion in some later function.
13361     if (getDiagnostics().hasErrorOccurred() ||
13362         getDiagnostics().getSuppressAllDiagnostics()) {
13363       DiscardCleanupsInEvaluationContext();
13364     }
13365     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13366         !isa<FunctionTemplateDecl>(dcl)) {
13367       // Since the body is valid, issue any analysis-based warnings that are
13368       // enabled.
13369       ActivePolicy = &WP;
13370     }
13371 
13372     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13373         (!CheckConstexprFunctionDecl(FD) ||
13374          !CheckConstexprFunctionBody(FD, Body)))
13375       FD->setInvalidDecl();
13376 
13377     if (FD && FD->hasAttr<NakedAttr>()) {
13378       for (const Stmt *S : Body->children()) {
13379         // Allow local register variables without initializer as they don't
13380         // require prologue.
13381         bool RegisterVariables = false;
13382         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13383           for (const auto *Decl : DS->decls()) {
13384             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13385               RegisterVariables =
13386                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13387               if (!RegisterVariables)
13388                 break;
13389             }
13390           }
13391         }
13392         if (RegisterVariables)
13393           continue;
13394         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13395           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13396           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13397           FD->setInvalidDecl();
13398           break;
13399         }
13400       }
13401     }
13402 
13403     assert(ExprCleanupObjects.size() ==
13404                ExprEvalContexts.back().NumCleanupObjects &&
13405            "Leftover temporaries in function");
13406     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13407     assert(MaybeODRUseExprs.empty() &&
13408            "Leftover expressions for odr-use checking");
13409   }
13410 
13411   if (!IsInstantiation)
13412     PopDeclContext();
13413 
13414   PopFunctionScopeInfo(ActivePolicy, dcl);
13415   // If any errors have occurred, clear out any temporaries that may have
13416   // been leftover. This ensures that these temporaries won't be picked up for
13417   // deletion in some later function.
13418   if (getDiagnostics().hasErrorOccurred()) {
13419     DiscardCleanupsInEvaluationContext();
13420   }
13421 
13422   return dcl;
13423 }
13424 
13425 /// When we finish delayed parsing of an attribute, we must attach it to the
13426 /// relevant Decl.
13427 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13428                                        ParsedAttributes &Attrs) {
13429   // Always attach attributes to the underlying decl.
13430   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13431     D = TD->getTemplatedDecl();
13432   ProcessDeclAttributeList(S, D, Attrs);
13433 
13434   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13435     if (Method->isStatic())
13436       checkThisInStaticMemberFunctionAttributes(Method);
13437 }
13438 
13439 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13440 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13441 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13442                                           IdentifierInfo &II, Scope *S) {
13443   // Find the scope in which the identifier is injected and the corresponding
13444   // DeclContext.
13445   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13446   // In that case, we inject the declaration into the translation unit scope
13447   // instead.
13448   Scope *BlockScope = S;
13449   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13450     BlockScope = BlockScope->getParent();
13451 
13452   Scope *ContextScope = BlockScope;
13453   while (!ContextScope->getEntity())
13454     ContextScope = ContextScope->getParent();
13455   ContextRAII SavedContext(*this, ContextScope->getEntity());
13456 
13457   // Before we produce a declaration for an implicitly defined
13458   // function, see whether there was a locally-scoped declaration of
13459   // this name as a function or variable. If so, use that
13460   // (non-visible) declaration, and complain about it.
13461   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13462   if (ExternCPrev) {
13463     // We still need to inject the function into the enclosing block scope so
13464     // that later (non-call) uses can see it.
13465     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13466 
13467     // C89 footnote 38:
13468     //   If in fact it is not defined as having type "function returning int",
13469     //   the behavior is undefined.
13470     if (!isa<FunctionDecl>(ExternCPrev) ||
13471         !Context.typesAreCompatible(
13472             cast<FunctionDecl>(ExternCPrev)->getType(),
13473             Context.getFunctionNoProtoType(Context.IntTy))) {
13474       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13475           << ExternCPrev << !getLangOpts().C99;
13476       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13477       return ExternCPrev;
13478     }
13479   }
13480 
13481   // Extension in C99.  Legal in C90, but warn about it.
13482   unsigned diag_id;
13483   if (II.getName().startswith("__builtin_"))
13484     diag_id = diag::warn_builtin_unknown;
13485   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13486   else if (getLangOpts().OpenCL)
13487     diag_id = diag::err_opencl_implicit_function_decl;
13488   else if (getLangOpts().C99)
13489     diag_id = diag::ext_implicit_function_decl;
13490   else
13491     diag_id = diag::warn_implicit_function_decl;
13492   Diag(Loc, diag_id) << &II;
13493 
13494   // If we found a prior declaration of this function, don't bother building
13495   // another one. We've already pushed that one into scope, so there's nothing
13496   // more to do.
13497   if (ExternCPrev)
13498     return ExternCPrev;
13499 
13500   // Because typo correction is expensive, only do it if the implicit
13501   // function declaration is going to be treated as an error.
13502   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13503     TypoCorrection Corrected;
13504     if (S &&
13505         (Corrected = CorrectTypo(
13506              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13507              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13508       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13509                    /*ErrorRecovery*/false);
13510   }
13511 
13512   // Set a Declarator for the implicit definition: int foo();
13513   const char *Dummy;
13514   AttributeFactory attrFactory;
13515   DeclSpec DS(attrFactory);
13516   unsigned DiagID;
13517   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13518                                   Context.getPrintingPolicy());
13519   (void)Error; // Silence warning.
13520   assert(!Error && "Error setting up implicit decl!");
13521   SourceLocation NoLoc;
13522   Declarator D(DS, DeclaratorContext::BlockContext);
13523   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13524                                              /*IsAmbiguous=*/false,
13525                                              /*LParenLoc=*/NoLoc,
13526                                              /*Params=*/nullptr,
13527                                              /*NumParams=*/0,
13528                                              /*EllipsisLoc=*/NoLoc,
13529                                              /*RParenLoc=*/NoLoc,
13530                                              /*RefQualifierIsLvalueRef=*/true,
13531                                              /*RefQualifierLoc=*/NoLoc,
13532                                              /*MutableLoc=*/NoLoc, EST_None,
13533                                              /*ESpecRange=*/SourceRange(),
13534                                              /*Exceptions=*/nullptr,
13535                                              /*ExceptionRanges=*/nullptr,
13536                                              /*NumExceptions=*/0,
13537                                              /*NoexceptExpr=*/nullptr,
13538                                              /*ExceptionSpecTokens=*/nullptr,
13539                                              /*DeclsInPrototype=*/None, Loc,
13540                                              Loc, D),
13541                 std::move(DS.getAttributes()), SourceLocation());
13542   D.SetIdentifier(&II, Loc);
13543 
13544   // Insert this function into the enclosing block scope.
13545   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13546   FD->setImplicit();
13547 
13548   AddKnownFunctionAttributes(FD);
13549 
13550   return FD;
13551 }
13552 
13553 /// Adds any function attributes that we know a priori based on
13554 /// the declaration of this function.
13555 ///
13556 /// These attributes can apply both to implicitly-declared builtins
13557 /// (like __builtin___printf_chk) or to library-declared functions
13558 /// like NSLog or printf.
13559 ///
13560 /// We need to check for duplicate attributes both here and where user-written
13561 /// attributes are applied to declarations.
13562 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13563   if (FD->isInvalidDecl())
13564     return;
13565 
13566   // If this is a built-in function, map its builtin attributes to
13567   // actual attributes.
13568   if (unsigned BuiltinID = FD->getBuiltinID()) {
13569     // Handle printf-formatting attributes.
13570     unsigned FormatIdx;
13571     bool HasVAListArg;
13572     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13573       if (!FD->hasAttr<FormatAttr>()) {
13574         const char *fmt = "printf";
13575         unsigned int NumParams = FD->getNumParams();
13576         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13577             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13578           fmt = "NSString";
13579         FD->addAttr(FormatAttr::CreateImplicit(Context,
13580                                                &Context.Idents.get(fmt),
13581                                                FormatIdx+1,
13582                                                HasVAListArg ? 0 : FormatIdx+2,
13583                                                FD->getLocation()));
13584       }
13585     }
13586     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13587                                              HasVAListArg)) {
13588      if (!FD->hasAttr<FormatAttr>())
13589        FD->addAttr(FormatAttr::CreateImplicit(Context,
13590                                               &Context.Idents.get("scanf"),
13591                                               FormatIdx+1,
13592                                               HasVAListArg ? 0 : FormatIdx+2,
13593                                               FD->getLocation()));
13594     }
13595 
13596     // Handle automatically recognized callbacks.
13597     SmallVector<int, 4> Encoding;
13598     if (!FD->hasAttr<CallbackAttr>() &&
13599         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13600       FD->addAttr(CallbackAttr::CreateImplicit(
13601           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13602 
13603     // Mark const if we don't care about errno and that is the only thing
13604     // preventing the function from being const. This allows IRgen to use LLVM
13605     // intrinsics for such functions.
13606     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13607         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13608       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13609 
13610     // We make "fma" on some platforms const because we know it does not set
13611     // errno in those environments even though it could set errno based on the
13612     // C standard.
13613     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13614     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13615         !FD->hasAttr<ConstAttr>()) {
13616       switch (BuiltinID) {
13617       case Builtin::BI__builtin_fma:
13618       case Builtin::BI__builtin_fmaf:
13619       case Builtin::BI__builtin_fmal:
13620       case Builtin::BIfma:
13621       case Builtin::BIfmaf:
13622       case Builtin::BIfmal:
13623         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13624         break;
13625       default:
13626         break;
13627       }
13628     }
13629 
13630     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13631         !FD->hasAttr<ReturnsTwiceAttr>())
13632       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13633                                          FD->getLocation()));
13634     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13635       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13636     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13637       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13638     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13639       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13640     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13641         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13642       // Add the appropriate attribute, depending on the CUDA compilation mode
13643       // and which target the builtin belongs to. For example, during host
13644       // compilation, aux builtins are __device__, while the rest are __host__.
13645       if (getLangOpts().CUDAIsDevice !=
13646           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13647         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13648       else
13649         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13650     }
13651   }
13652 
13653   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13654   // throw, add an implicit nothrow attribute to any extern "C" function we come
13655   // across.
13656   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13657       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13658     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13659     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13660       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13661   }
13662 
13663   IdentifierInfo *Name = FD->getIdentifier();
13664   if (!Name)
13665     return;
13666   if ((!getLangOpts().CPlusPlus &&
13667        FD->getDeclContext()->isTranslationUnit()) ||
13668       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13669        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13670        LinkageSpecDecl::lang_c)) {
13671     // Okay: this could be a libc/libm/Objective-C function we know
13672     // about.
13673   } else
13674     return;
13675 
13676   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13677     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13678     // target-specific builtins, perhaps?
13679     if (!FD->hasAttr<FormatAttr>())
13680       FD->addAttr(FormatAttr::CreateImplicit(Context,
13681                                              &Context.Idents.get("printf"), 2,
13682                                              Name->isStr("vasprintf") ? 0 : 3,
13683                                              FD->getLocation()));
13684   }
13685 
13686   if (Name->isStr("__CFStringMakeConstantString")) {
13687     // We already have a __builtin___CFStringMakeConstantString,
13688     // but builds that use -fno-constant-cfstrings don't go through that.
13689     if (!FD->hasAttr<FormatArgAttr>())
13690       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13691                                                 FD->getLocation()));
13692   }
13693 }
13694 
13695 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13696                                     TypeSourceInfo *TInfo) {
13697   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13698   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13699 
13700   if (!TInfo) {
13701     assert(D.isInvalidType() && "no declarator info for valid type");
13702     TInfo = Context.getTrivialTypeSourceInfo(T);
13703   }
13704 
13705   // Scope manipulation handled by caller.
13706   TypedefDecl *NewTD =
13707       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13708                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13709 
13710   // Bail out immediately if we have an invalid declaration.
13711   if (D.isInvalidType()) {
13712     NewTD->setInvalidDecl();
13713     return NewTD;
13714   }
13715 
13716   if (D.getDeclSpec().isModulePrivateSpecified()) {
13717     if (CurContext->isFunctionOrMethod())
13718       Diag(NewTD->getLocation(), diag::err_module_private_local)
13719         << 2 << NewTD->getDeclName()
13720         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13721         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13722     else
13723       NewTD->setModulePrivate();
13724   }
13725 
13726   // C++ [dcl.typedef]p8:
13727   //   If the typedef declaration defines an unnamed class (or
13728   //   enum), the first typedef-name declared by the declaration
13729   //   to be that class type (or enum type) is used to denote the
13730   //   class type (or enum type) for linkage purposes only.
13731   // We need to check whether the type was declared in the declaration.
13732   switch (D.getDeclSpec().getTypeSpecType()) {
13733   case TST_enum:
13734   case TST_struct:
13735   case TST_interface:
13736   case TST_union:
13737   case TST_class: {
13738     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13739     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13740     break;
13741   }
13742 
13743   default:
13744     break;
13745   }
13746 
13747   return NewTD;
13748 }
13749 
13750 /// Check that this is a valid underlying type for an enum declaration.
13751 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13752   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13753   QualType T = TI->getType();
13754 
13755   if (T->isDependentType())
13756     return false;
13757 
13758   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13759     if (BT->isInteger())
13760       return false;
13761 
13762   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13763   return true;
13764 }
13765 
13766 /// Check whether this is a valid redeclaration of a previous enumeration.
13767 /// \return true if the redeclaration was invalid.
13768 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13769                                   QualType EnumUnderlyingTy, bool IsFixed,
13770                                   const EnumDecl *Prev) {
13771   if (IsScoped != Prev->isScoped()) {
13772     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13773       << Prev->isScoped();
13774     Diag(Prev->getLocation(), diag::note_previous_declaration);
13775     return true;
13776   }
13777 
13778   if (IsFixed && Prev->isFixed()) {
13779     if (!EnumUnderlyingTy->isDependentType() &&
13780         !Prev->getIntegerType()->isDependentType() &&
13781         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13782                                         Prev->getIntegerType())) {
13783       // TODO: Highlight the underlying type of the redeclaration.
13784       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13785         << EnumUnderlyingTy << Prev->getIntegerType();
13786       Diag(Prev->getLocation(), diag::note_previous_declaration)
13787           << Prev->getIntegerTypeRange();
13788       return true;
13789     }
13790   } else if (IsFixed != Prev->isFixed()) {
13791     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13792       << Prev->isFixed();
13793     Diag(Prev->getLocation(), diag::note_previous_declaration);
13794     return true;
13795   }
13796 
13797   return false;
13798 }
13799 
13800 /// Get diagnostic %select index for tag kind for
13801 /// redeclaration diagnostic message.
13802 /// WARNING: Indexes apply to particular diagnostics only!
13803 ///
13804 /// \returns diagnostic %select index.
13805 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13806   switch (Tag) {
13807   case TTK_Struct: return 0;
13808   case TTK_Interface: return 1;
13809   case TTK_Class:  return 2;
13810   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13811   }
13812 }
13813 
13814 /// Determine if tag kind is a class-key compatible with
13815 /// class for redeclaration (class, struct, or __interface).
13816 ///
13817 /// \returns true iff the tag kind is compatible.
13818 static bool isClassCompatTagKind(TagTypeKind Tag)
13819 {
13820   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13821 }
13822 
13823 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13824                                              TagTypeKind TTK) {
13825   if (isa<TypedefDecl>(PrevDecl))
13826     return NTK_Typedef;
13827   else if (isa<TypeAliasDecl>(PrevDecl))
13828     return NTK_TypeAlias;
13829   else if (isa<ClassTemplateDecl>(PrevDecl))
13830     return NTK_Template;
13831   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13832     return NTK_TypeAliasTemplate;
13833   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13834     return NTK_TemplateTemplateArgument;
13835   switch (TTK) {
13836   case TTK_Struct:
13837   case TTK_Interface:
13838   case TTK_Class:
13839     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13840   case TTK_Union:
13841     return NTK_NonUnion;
13842   case TTK_Enum:
13843     return NTK_NonEnum;
13844   }
13845   llvm_unreachable("invalid TTK");
13846 }
13847 
13848 /// Determine whether a tag with a given kind is acceptable
13849 /// as a redeclaration of the given tag declaration.
13850 ///
13851 /// \returns true if the new tag kind is acceptable, false otherwise.
13852 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13853                                         TagTypeKind NewTag, bool isDefinition,
13854                                         SourceLocation NewTagLoc,
13855                                         const IdentifierInfo *Name) {
13856   // C++ [dcl.type.elab]p3:
13857   //   The class-key or enum keyword present in the
13858   //   elaborated-type-specifier shall agree in kind with the
13859   //   declaration to which the name in the elaborated-type-specifier
13860   //   refers. This rule also applies to the form of
13861   //   elaborated-type-specifier that declares a class-name or
13862   //   friend class since it can be construed as referring to the
13863   //   definition of the class. Thus, in any
13864   //   elaborated-type-specifier, the enum keyword shall be used to
13865   //   refer to an enumeration (7.2), the union class-key shall be
13866   //   used to refer to a union (clause 9), and either the class or
13867   //   struct class-key shall be used to refer to a class (clause 9)
13868   //   declared using the class or struct class-key.
13869   TagTypeKind OldTag = Previous->getTagKind();
13870   if (OldTag != NewTag &&
13871       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
13872     return false;
13873 
13874   // Tags are compatible, but we might still want to warn on mismatched tags.
13875   // Non-class tags can't be mismatched at this point.
13876   if (!isClassCompatTagKind(NewTag))
13877     return true;
13878 
13879   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
13880   // by our warning analysis. We don't want to warn about mismatches with (eg)
13881   // declarations in system headers that are designed to be specialized, but if
13882   // a user asks us to warn, we should warn if their code contains mismatched
13883   // declarations.
13884   auto IsIgnoredLoc = [&](SourceLocation Loc) {
13885     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
13886                                       Loc);
13887   };
13888   if (IsIgnoredLoc(NewTagLoc))
13889     return true;
13890 
13891   auto IsIgnored = [&](const TagDecl *Tag) {
13892     return IsIgnoredLoc(Tag->getLocation());
13893   };
13894   while (IsIgnored(Previous)) {
13895     Previous = Previous->getPreviousDecl();
13896     if (!Previous)
13897       return true;
13898     OldTag = Previous->getTagKind();
13899   }
13900 
13901   bool isTemplate = false;
13902   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13903     isTemplate = Record->getDescribedClassTemplate();
13904 
13905   if (inTemplateInstantiation()) {
13906     if (OldTag != NewTag) {
13907       // In a template instantiation, do not offer fix-its for tag mismatches
13908       // since they usually mess up the template instead of fixing the problem.
13909       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13910         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13911         << getRedeclDiagFromTagKind(OldTag);
13912       // FIXME: Note previous location?
13913     }
13914     return true;
13915   }
13916 
13917   if (isDefinition) {
13918     // On definitions, check all previous tags and issue a fix-it for each
13919     // one that doesn't match the current tag.
13920     if (Previous->getDefinition()) {
13921       // Don't suggest fix-its for redefinitions.
13922       return true;
13923     }
13924 
13925     bool previousMismatch = false;
13926     for (const TagDecl *I : Previous->redecls()) {
13927       if (I->getTagKind() != NewTag) {
13928         // Ignore previous declarations for which the warning was disabled.
13929         if (IsIgnored(I))
13930           continue;
13931 
13932         if (!previousMismatch) {
13933           previousMismatch = true;
13934           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13935             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13936             << getRedeclDiagFromTagKind(I->getTagKind());
13937         }
13938         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13939           << getRedeclDiagFromTagKind(NewTag)
13940           << FixItHint::CreateReplacement(I->getInnerLocStart(),
13941                TypeWithKeyword::getTagTypeKindName(NewTag));
13942       }
13943     }
13944     return true;
13945   }
13946 
13947   // Identify the prevailing tag kind: this is the kind of the definition (if
13948   // there is a non-ignored definition), or otherwise the kind of the prior
13949   // (non-ignored) declaration.
13950   const TagDecl *PrevDef = Previous->getDefinition();
13951   if (PrevDef && IsIgnored(PrevDef))
13952     PrevDef = nullptr;
13953   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
13954   if (Redecl->getTagKind() != NewTag) {
13955     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13956       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13957       << getRedeclDiagFromTagKind(OldTag);
13958     Diag(Redecl->getLocation(), diag::note_previous_use);
13959 
13960     // If there is a previous definition, suggest a fix-it.
13961     if (PrevDef) {
13962       Diag(NewTagLoc, diag::note_struct_class_suggestion)
13963         << getRedeclDiagFromTagKind(Redecl->getTagKind())
13964         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13965              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13966     }
13967   }
13968 
13969   return true;
13970 }
13971 
13972 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13973 /// from an outer enclosing namespace or file scope inside a friend declaration.
13974 /// This should provide the commented out code in the following snippet:
13975 ///   namespace N {
13976 ///     struct X;
13977 ///     namespace M {
13978 ///       struct Y { friend struct /*N::*/ X; };
13979 ///     }
13980 ///   }
13981 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13982                                          SourceLocation NameLoc) {
13983   // While the decl is in a namespace, do repeated lookup of that name and see
13984   // if we get the same namespace back.  If we do not, continue until
13985   // translation unit scope, at which point we have a fully qualified NNS.
13986   SmallVector<IdentifierInfo *, 4> Namespaces;
13987   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13988   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13989     // This tag should be declared in a namespace, which can only be enclosed by
13990     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13991     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13992     if (!Namespace || Namespace->isAnonymousNamespace())
13993       return FixItHint();
13994     IdentifierInfo *II = Namespace->getIdentifier();
13995     Namespaces.push_back(II);
13996     NamedDecl *Lookup = SemaRef.LookupSingleName(
13997         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13998     if (Lookup == Namespace)
13999       break;
14000   }
14001 
14002   // Once we have all the namespaces, reverse them to go outermost first, and
14003   // build an NNS.
14004   SmallString<64> Insertion;
14005   llvm::raw_svector_ostream OS(Insertion);
14006   if (DC->isTranslationUnit())
14007     OS << "::";
14008   std::reverse(Namespaces.begin(), Namespaces.end());
14009   for (auto *II : Namespaces)
14010     OS << II->getName() << "::";
14011   return FixItHint::CreateInsertion(NameLoc, Insertion);
14012 }
14013 
14014 /// Determine whether a tag originally declared in context \p OldDC can
14015 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14016 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14017 /// using-declaration).
14018 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14019                                          DeclContext *NewDC) {
14020   OldDC = OldDC->getRedeclContext();
14021   NewDC = NewDC->getRedeclContext();
14022 
14023   if (OldDC->Equals(NewDC))
14024     return true;
14025 
14026   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14027   // encloses the other).
14028   if (S.getLangOpts().MSVCCompat &&
14029       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14030     return true;
14031 
14032   return false;
14033 }
14034 
14035 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14036 /// former case, Name will be non-null.  In the later case, Name will be null.
14037 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14038 /// reference/declaration/definition of a tag.
14039 ///
14040 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14041 /// trailing-type-specifier) other than one in an alias-declaration.
14042 ///
14043 /// \param SkipBody If non-null, will be set to indicate if the caller should
14044 /// skip the definition of this tag and treat it as if it were a declaration.
14045 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14046                      SourceLocation KWLoc, CXXScopeSpec &SS,
14047                      IdentifierInfo *Name, SourceLocation NameLoc,
14048                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14049                      SourceLocation ModulePrivateLoc,
14050                      MultiTemplateParamsArg TemplateParameterLists,
14051                      bool &OwnedDecl, bool &IsDependent,
14052                      SourceLocation ScopedEnumKWLoc,
14053                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14054                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14055                      SkipBodyInfo *SkipBody) {
14056   // If this is not a definition, it must have a name.
14057   IdentifierInfo *OrigName = Name;
14058   assert((Name != nullptr || TUK == TUK_Definition) &&
14059          "Nameless record must be a definition!");
14060   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14061 
14062   OwnedDecl = false;
14063   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14064   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14065 
14066   // FIXME: Check member specializations more carefully.
14067   bool isMemberSpecialization = false;
14068   bool Invalid = false;
14069 
14070   // We only need to do this matching if we have template parameters
14071   // or a scope specifier, which also conveniently avoids this work
14072   // for non-C++ cases.
14073   if (TemplateParameterLists.size() > 0 ||
14074       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14075     if (TemplateParameterList *TemplateParams =
14076             MatchTemplateParametersToScopeSpecifier(
14077                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14078                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14079       if (Kind == TTK_Enum) {
14080         Diag(KWLoc, diag::err_enum_template);
14081         return nullptr;
14082       }
14083 
14084       if (TemplateParams->size() > 0) {
14085         // This is a declaration or definition of a class template (which may
14086         // be a member of another template).
14087 
14088         if (Invalid)
14089           return nullptr;
14090 
14091         OwnedDecl = false;
14092         DeclResult Result = CheckClassTemplate(
14093             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14094             AS, ModulePrivateLoc,
14095             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14096             TemplateParameterLists.data(), SkipBody);
14097         return Result.get();
14098       } else {
14099         // The "template<>" header is extraneous.
14100         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14101           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14102         isMemberSpecialization = true;
14103       }
14104     }
14105   }
14106 
14107   // Figure out the underlying type if this a enum declaration. We need to do
14108   // this early, because it's needed to detect if this is an incompatible
14109   // redeclaration.
14110   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14111   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14112 
14113   if (Kind == TTK_Enum) {
14114     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14115       // No underlying type explicitly specified, or we failed to parse the
14116       // type, default to int.
14117       EnumUnderlying = Context.IntTy.getTypePtr();
14118     } else if (UnderlyingType.get()) {
14119       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14120       // integral type; any cv-qualification is ignored.
14121       TypeSourceInfo *TI = nullptr;
14122       GetTypeFromParser(UnderlyingType.get(), &TI);
14123       EnumUnderlying = TI;
14124 
14125       if (CheckEnumUnderlyingType(TI))
14126         // Recover by falling back to int.
14127         EnumUnderlying = Context.IntTy.getTypePtr();
14128 
14129       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14130                                           UPPC_FixedUnderlyingType))
14131         EnumUnderlying = Context.IntTy.getTypePtr();
14132 
14133     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14134       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14135       // of 'int'. However, if this is an unfixed forward declaration, don't set
14136       // the underlying type unless the user enables -fms-compatibility. This
14137       // makes unfixed forward declared enums incomplete and is more conforming.
14138       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14139         EnumUnderlying = Context.IntTy.getTypePtr();
14140     }
14141   }
14142 
14143   DeclContext *SearchDC = CurContext;
14144   DeclContext *DC = CurContext;
14145   bool isStdBadAlloc = false;
14146   bool isStdAlignValT = false;
14147 
14148   RedeclarationKind Redecl = forRedeclarationInCurContext();
14149   if (TUK == TUK_Friend || TUK == TUK_Reference)
14150     Redecl = NotForRedeclaration;
14151 
14152   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14153   /// implemented asks for structural equivalence checking, the returned decl
14154   /// here is passed back to the parser, allowing the tag body to be parsed.
14155   auto createTagFromNewDecl = [&]() -> TagDecl * {
14156     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14157     // If there is an identifier, use the location of the identifier as the
14158     // location of the decl, otherwise use the location of the struct/union
14159     // keyword.
14160     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14161     TagDecl *New = nullptr;
14162 
14163     if (Kind == TTK_Enum) {
14164       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14165                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14166       // If this is an undefined enum, bail.
14167       if (TUK != TUK_Definition && !Invalid)
14168         return nullptr;
14169       if (EnumUnderlying) {
14170         EnumDecl *ED = cast<EnumDecl>(New);
14171         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14172           ED->setIntegerTypeSourceInfo(TI);
14173         else
14174           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14175         ED->setPromotionType(ED->getIntegerType());
14176       }
14177     } else { // struct/union
14178       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14179                                nullptr);
14180     }
14181 
14182     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14183       // Add alignment attributes if necessary; these attributes are checked
14184       // when the ASTContext lays out the structure.
14185       //
14186       // It is important for implementing the correct semantics that this
14187       // happen here (in ActOnTag). The #pragma pack stack is
14188       // maintained as a result of parser callbacks which can occur at
14189       // many points during the parsing of a struct declaration (because
14190       // the #pragma tokens are effectively skipped over during the
14191       // parsing of the struct).
14192       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14193         AddAlignmentAttributesForRecord(RD);
14194         AddMsStructLayoutForRecord(RD);
14195       }
14196     }
14197     New->setLexicalDeclContext(CurContext);
14198     return New;
14199   };
14200 
14201   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14202   if (Name && SS.isNotEmpty()) {
14203     // We have a nested-name tag ('struct foo::bar').
14204 
14205     // Check for invalid 'foo::'.
14206     if (SS.isInvalid()) {
14207       Name = nullptr;
14208       goto CreateNewDecl;
14209     }
14210 
14211     // If this is a friend or a reference to a class in a dependent
14212     // context, don't try to make a decl for it.
14213     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14214       DC = computeDeclContext(SS, false);
14215       if (!DC) {
14216         IsDependent = true;
14217         return nullptr;
14218       }
14219     } else {
14220       DC = computeDeclContext(SS, true);
14221       if (!DC) {
14222         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14223           << SS.getRange();
14224         return nullptr;
14225       }
14226     }
14227 
14228     if (RequireCompleteDeclContext(SS, DC))
14229       return nullptr;
14230 
14231     SearchDC = DC;
14232     // Look-up name inside 'foo::'.
14233     LookupQualifiedName(Previous, DC);
14234 
14235     if (Previous.isAmbiguous())
14236       return nullptr;
14237 
14238     if (Previous.empty()) {
14239       // Name lookup did not find anything. However, if the
14240       // nested-name-specifier refers to the current instantiation,
14241       // and that current instantiation has any dependent base
14242       // classes, we might find something at instantiation time: treat
14243       // this as a dependent elaborated-type-specifier.
14244       // But this only makes any sense for reference-like lookups.
14245       if (Previous.wasNotFoundInCurrentInstantiation() &&
14246           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14247         IsDependent = true;
14248         return nullptr;
14249       }
14250 
14251       // A tag 'foo::bar' must already exist.
14252       Diag(NameLoc, diag::err_not_tag_in_scope)
14253         << Kind << Name << DC << SS.getRange();
14254       Name = nullptr;
14255       Invalid = true;
14256       goto CreateNewDecl;
14257     }
14258   } else if (Name) {
14259     // C++14 [class.mem]p14:
14260     //   If T is the name of a class, then each of the following shall have a
14261     //   name different from T:
14262     //    -- every member of class T that is itself a type
14263     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14264         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14265       return nullptr;
14266 
14267     // If this is a named struct, check to see if there was a previous forward
14268     // declaration or definition.
14269     // FIXME: We're looking into outer scopes here, even when we
14270     // shouldn't be. Doing so can result in ambiguities that we
14271     // shouldn't be diagnosing.
14272     LookupName(Previous, S);
14273 
14274     // When declaring or defining a tag, ignore ambiguities introduced
14275     // by types using'ed into this scope.
14276     if (Previous.isAmbiguous() &&
14277         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14278       LookupResult::Filter F = Previous.makeFilter();
14279       while (F.hasNext()) {
14280         NamedDecl *ND = F.next();
14281         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14282                 SearchDC->getRedeclContext()))
14283           F.erase();
14284       }
14285       F.done();
14286     }
14287 
14288     // C++11 [namespace.memdef]p3:
14289     //   If the name in a friend declaration is neither qualified nor
14290     //   a template-id and the declaration is a function or an
14291     //   elaborated-type-specifier, the lookup to determine whether
14292     //   the entity has been previously declared shall not consider
14293     //   any scopes outside the innermost enclosing namespace.
14294     //
14295     // MSVC doesn't implement the above rule for types, so a friend tag
14296     // declaration may be a redeclaration of a type declared in an enclosing
14297     // scope.  They do implement this rule for friend functions.
14298     //
14299     // Does it matter that this should be by scope instead of by
14300     // semantic context?
14301     if (!Previous.empty() && TUK == TUK_Friend) {
14302       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14303       LookupResult::Filter F = Previous.makeFilter();
14304       bool FriendSawTagOutsideEnclosingNamespace = false;
14305       while (F.hasNext()) {
14306         NamedDecl *ND = F.next();
14307         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14308         if (DC->isFileContext() &&
14309             !EnclosingNS->Encloses(ND->getDeclContext())) {
14310           if (getLangOpts().MSVCCompat)
14311             FriendSawTagOutsideEnclosingNamespace = true;
14312           else
14313             F.erase();
14314         }
14315       }
14316       F.done();
14317 
14318       // Diagnose this MSVC extension in the easy case where lookup would have
14319       // unambiguously found something outside the enclosing namespace.
14320       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14321         NamedDecl *ND = Previous.getFoundDecl();
14322         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14323             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14324       }
14325     }
14326 
14327     // Note:  there used to be some attempt at recovery here.
14328     if (Previous.isAmbiguous())
14329       return nullptr;
14330 
14331     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14332       // FIXME: This makes sure that we ignore the contexts associated
14333       // with C structs, unions, and enums when looking for a matching
14334       // tag declaration or definition. See the similar lookup tweak
14335       // in Sema::LookupName; is there a better way to deal with this?
14336       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14337         SearchDC = SearchDC->getParent();
14338     }
14339   }
14340 
14341   if (Previous.isSingleResult() &&
14342       Previous.getFoundDecl()->isTemplateParameter()) {
14343     // Maybe we will complain about the shadowed template parameter.
14344     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14345     // Just pretend that we didn't see the previous declaration.
14346     Previous.clear();
14347   }
14348 
14349   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14350       DC->Equals(getStdNamespace())) {
14351     if (Name->isStr("bad_alloc")) {
14352       // This is a declaration of or a reference to "std::bad_alloc".
14353       isStdBadAlloc = true;
14354 
14355       // If std::bad_alloc has been implicitly declared (but made invisible to
14356       // name lookup), fill in this implicit declaration as the previous
14357       // declaration, so that the declarations get chained appropriately.
14358       if (Previous.empty() && StdBadAlloc)
14359         Previous.addDecl(getStdBadAlloc());
14360     } else if (Name->isStr("align_val_t")) {
14361       isStdAlignValT = true;
14362       if (Previous.empty() && StdAlignValT)
14363         Previous.addDecl(getStdAlignValT());
14364     }
14365   }
14366 
14367   // If we didn't find a previous declaration, and this is a reference
14368   // (or friend reference), move to the correct scope.  In C++, we
14369   // also need to do a redeclaration lookup there, just in case
14370   // there's a shadow friend decl.
14371   if (Name && Previous.empty() &&
14372       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14373     if (Invalid) goto CreateNewDecl;
14374     assert(SS.isEmpty());
14375 
14376     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14377       // C++ [basic.scope.pdecl]p5:
14378       //   -- for an elaborated-type-specifier of the form
14379       //
14380       //          class-key identifier
14381       //
14382       //      if the elaborated-type-specifier is used in the
14383       //      decl-specifier-seq or parameter-declaration-clause of a
14384       //      function defined in namespace scope, the identifier is
14385       //      declared as a class-name in the namespace that contains
14386       //      the declaration; otherwise, except as a friend
14387       //      declaration, the identifier is declared in the smallest
14388       //      non-class, non-function-prototype scope that contains the
14389       //      declaration.
14390       //
14391       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14392       // C structs and unions.
14393       //
14394       // It is an error in C++ to declare (rather than define) an enum
14395       // type, including via an elaborated type specifier.  We'll
14396       // diagnose that later; for now, declare the enum in the same
14397       // scope as we would have picked for any other tag type.
14398       //
14399       // GNU C also supports this behavior as part of its incomplete
14400       // enum types extension, while GNU C++ does not.
14401       //
14402       // Find the context where we'll be declaring the tag.
14403       // FIXME: We would like to maintain the current DeclContext as the
14404       // lexical context,
14405       SearchDC = getTagInjectionContext(SearchDC);
14406 
14407       // Find the scope where we'll be declaring the tag.
14408       S = getTagInjectionScope(S, getLangOpts());
14409     } else {
14410       assert(TUK == TUK_Friend);
14411       // C++ [namespace.memdef]p3:
14412       //   If a friend declaration in a non-local class first declares a
14413       //   class or function, the friend class or function is a member of
14414       //   the innermost enclosing namespace.
14415       SearchDC = SearchDC->getEnclosingNamespaceContext();
14416     }
14417 
14418     // In C++, we need to do a redeclaration lookup to properly
14419     // diagnose some problems.
14420     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14421     // hidden declaration so that we don't get ambiguity errors when using a
14422     // type declared by an elaborated-type-specifier.  In C that is not correct
14423     // and we should instead merge compatible types found by lookup.
14424     if (getLangOpts().CPlusPlus) {
14425       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14426       LookupQualifiedName(Previous, SearchDC);
14427     } else {
14428       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14429       LookupName(Previous, S);
14430     }
14431   }
14432 
14433   // If we have a known previous declaration to use, then use it.
14434   if (Previous.empty() && SkipBody && SkipBody->Previous)
14435     Previous.addDecl(SkipBody->Previous);
14436 
14437   if (!Previous.empty()) {
14438     NamedDecl *PrevDecl = Previous.getFoundDecl();
14439     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14440 
14441     // It's okay to have a tag decl in the same scope as a typedef
14442     // which hides a tag decl in the same scope.  Finding this
14443     // insanity with a redeclaration lookup can only actually happen
14444     // in C++.
14445     //
14446     // This is also okay for elaborated-type-specifiers, which is
14447     // technically forbidden by the current standard but which is
14448     // okay according to the likely resolution of an open issue;
14449     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14450     if (getLangOpts().CPlusPlus) {
14451       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14452         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14453           TagDecl *Tag = TT->getDecl();
14454           if (Tag->getDeclName() == Name &&
14455               Tag->getDeclContext()->getRedeclContext()
14456                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14457             PrevDecl = Tag;
14458             Previous.clear();
14459             Previous.addDecl(Tag);
14460             Previous.resolveKind();
14461           }
14462         }
14463       }
14464     }
14465 
14466     // If this is a redeclaration of a using shadow declaration, it must
14467     // declare a tag in the same context. In MSVC mode, we allow a
14468     // redefinition if either context is within the other.
14469     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14470       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14471       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14472           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14473           !(OldTag && isAcceptableTagRedeclContext(
14474                           *this, OldTag->getDeclContext(), SearchDC))) {
14475         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14476         Diag(Shadow->getTargetDecl()->getLocation(),
14477              diag::note_using_decl_target);
14478         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14479             << 0;
14480         // Recover by ignoring the old declaration.
14481         Previous.clear();
14482         goto CreateNewDecl;
14483       }
14484     }
14485 
14486     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14487       // If this is a use of a previous tag, or if the tag is already declared
14488       // in the same scope (so that the definition/declaration completes or
14489       // rementions the tag), reuse the decl.
14490       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14491           isDeclInScope(DirectPrevDecl, SearchDC, S,
14492                         SS.isNotEmpty() || isMemberSpecialization)) {
14493         // Make sure that this wasn't declared as an enum and now used as a
14494         // struct or something similar.
14495         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14496                                           TUK == TUK_Definition, KWLoc,
14497                                           Name)) {
14498           bool SafeToContinue
14499             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14500                Kind != TTK_Enum);
14501           if (SafeToContinue)
14502             Diag(KWLoc, diag::err_use_with_wrong_tag)
14503               << Name
14504               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14505                                               PrevTagDecl->getKindName());
14506           else
14507             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14508           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14509 
14510           if (SafeToContinue)
14511             Kind = PrevTagDecl->getTagKind();
14512           else {
14513             // Recover by making this an anonymous redefinition.
14514             Name = nullptr;
14515             Previous.clear();
14516             Invalid = true;
14517           }
14518         }
14519 
14520         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14521           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14522 
14523           // If this is an elaborated-type-specifier for a scoped enumeration,
14524           // the 'class' keyword is not necessary and not permitted.
14525           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14526             if (ScopedEnum)
14527               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14528                 << PrevEnum->isScoped()
14529                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14530             return PrevTagDecl;
14531           }
14532 
14533           QualType EnumUnderlyingTy;
14534           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14535             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14536           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14537             EnumUnderlyingTy = QualType(T, 0);
14538 
14539           // All conflicts with previous declarations are recovered by
14540           // returning the previous declaration, unless this is a definition,
14541           // in which case we want the caller to bail out.
14542           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14543                                      ScopedEnum, EnumUnderlyingTy,
14544                                      IsFixed, PrevEnum))
14545             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14546         }
14547 
14548         // C++11 [class.mem]p1:
14549         //   A member shall not be declared twice in the member-specification,
14550         //   except that a nested class or member class template can be declared
14551         //   and then later defined.
14552         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14553             S->isDeclScope(PrevDecl)) {
14554           Diag(NameLoc, diag::ext_member_redeclared);
14555           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14556         }
14557 
14558         if (!Invalid) {
14559           // If this is a use, just return the declaration we found, unless
14560           // we have attributes.
14561           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14562             if (!Attrs.empty()) {
14563               // FIXME: Diagnose these attributes. For now, we create a new
14564               // declaration to hold them.
14565             } else if (TUK == TUK_Reference &&
14566                        (PrevTagDecl->getFriendObjectKind() ==
14567                             Decl::FOK_Undeclared ||
14568                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14569                        SS.isEmpty()) {
14570               // This declaration is a reference to an existing entity, but
14571               // has different visibility from that entity: it either makes
14572               // a friend visible or it makes a type visible in a new module.
14573               // In either case, create a new declaration. We only do this if
14574               // the declaration would have meant the same thing if no prior
14575               // declaration were found, that is, if it was found in the same
14576               // scope where we would have injected a declaration.
14577               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14578                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14579                 return PrevTagDecl;
14580               // This is in the injected scope, create a new declaration in
14581               // that scope.
14582               S = getTagInjectionScope(S, getLangOpts());
14583             } else {
14584               return PrevTagDecl;
14585             }
14586           }
14587 
14588           // Diagnose attempts to redefine a tag.
14589           if (TUK == TUK_Definition) {
14590             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14591               // If we're defining a specialization and the previous definition
14592               // is from an implicit instantiation, don't emit an error
14593               // here; we'll catch this in the general case below.
14594               bool IsExplicitSpecializationAfterInstantiation = false;
14595               if (isMemberSpecialization) {
14596                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14597                   IsExplicitSpecializationAfterInstantiation =
14598                     RD->getTemplateSpecializationKind() !=
14599                     TSK_ExplicitSpecialization;
14600                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14601                   IsExplicitSpecializationAfterInstantiation =
14602                     ED->getTemplateSpecializationKind() !=
14603                     TSK_ExplicitSpecialization;
14604               }
14605 
14606               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14607               // not keep more that one definition around (merge them). However,
14608               // ensure the decl passes the structural compatibility check in
14609               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14610               NamedDecl *Hidden = nullptr;
14611               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14612                 // There is a definition of this tag, but it is not visible. We
14613                 // explicitly make use of C++'s one definition rule here, and
14614                 // assume that this definition is identical to the hidden one
14615                 // we already have. Make the existing definition visible and
14616                 // use it in place of this one.
14617                 if (!getLangOpts().CPlusPlus) {
14618                   // Postpone making the old definition visible until after we
14619                   // complete parsing the new one and do the structural
14620                   // comparison.
14621                   SkipBody->CheckSameAsPrevious = true;
14622                   SkipBody->New = createTagFromNewDecl();
14623                   SkipBody->Previous = Def;
14624                   return Def;
14625                 } else {
14626                   SkipBody->ShouldSkip = true;
14627                   SkipBody->Previous = Def;
14628                   makeMergedDefinitionVisible(Hidden);
14629                   // Carry on and handle it like a normal definition. We'll
14630                   // skip starting the definitiion later.
14631                 }
14632               } else if (!IsExplicitSpecializationAfterInstantiation) {
14633                 // A redeclaration in function prototype scope in C isn't
14634                 // visible elsewhere, so merely issue a warning.
14635                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14636                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14637                 else
14638                   Diag(NameLoc, diag::err_redefinition) << Name;
14639                 notePreviousDefinition(Def,
14640                                        NameLoc.isValid() ? NameLoc : KWLoc);
14641                 // If this is a redefinition, recover by making this
14642                 // struct be anonymous, which will make any later
14643                 // references get the previous definition.
14644                 Name = nullptr;
14645                 Previous.clear();
14646                 Invalid = true;
14647               }
14648             } else {
14649               // If the type is currently being defined, complain
14650               // about a nested redefinition.
14651               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14652               if (TD->isBeingDefined()) {
14653                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14654                 Diag(PrevTagDecl->getLocation(),
14655                      diag::note_previous_definition);
14656                 Name = nullptr;
14657                 Previous.clear();
14658                 Invalid = true;
14659               }
14660             }
14661 
14662             // Okay, this is definition of a previously declared or referenced
14663             // tag. We're going to create a new Decl for it.
14664           }
14665 
14666           // Okay, we're going to make a redeclaration.  If this is some kind
14667           // of reference, make sure we build the redeclaration in the same DC
14668           // as the original, and ignore the current access specifier.
14669           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14670             SearchDC = PrevTagDecl->getDeclContext();
14671             AS = AS_none;
14672           }
14673         }
14674         // If we get here we have (another) forward declaration or we
14675         // have a definition.  Just create a new decl.
14676 
14677       } else {
14678         // If we get here, this is a definition of a new tag type in a nested
14679         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14680         // new decl/type.  We set PrevDecl to NULL so that the entities
14681         // have distinct types.
14682         Previous.clear();
14683       }
14684       // If we get here, we're going to create a new Decl. If PrevDecl
14685       // is non-NULL, it's a definition of the tag declared by
14686       // PrevDecl. If it's NULL, we have a new definition.
14687 
14688     // Otherwise, PrevDecl is not a tag, but was found with tag
14689     // lookup.  This is only actually possible in C++, where a few
14690     // things like templates still live in the tag namespace.
14691     } else {
14692       // Use a better diagnostic if an elaborated-type-specifier
14693       // found the wrong kind of type on the first
14694       // (non-redeclaration) lookup.
14695       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14696           !Previous.isForRedeclaration()) {
14697         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14698         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14699                                                        << Kind;
14700         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14701         Invalid = true;
14702 
14703       // Otherwise, only diagnose if the declaration is in scope.
14704       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14705                                 SS.isNotEmpty() || isMemberSpecialization)) {
14706         // do nothing
14707 
14708       // Diagnose implicit declarations introduced by elaborated types.
14709       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14710         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14711         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14712         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14713         Invalid = true;
14714 
14715       // Otherwise it's a declaration.  Call out a particularly common
14716       // case here.
14717       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14718         unsigned Kind = 0;
14719         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14720         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14721           << Name << Kind << TND->getUnderlyingType();
14722         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14723         Invalid = true;
14724 
14725       // Otherwise, diagnose.
14726       } else {
14727         // The tag name clashes with something else in the target scope,
14728         // issue an error and recover by making this tag be anonymous.
14729         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14730         notePreviousDefinition(PrevDecl, NameLoc);
14731         Name = nullptr;
14732         Invalid = true;
14733       }
14734 
14735       // The existing declaration isn't relevant to us; we're in a
14736       // new scope, so clear out the previous declaration.
14737       Previous.clear();
14738     }
14739   }
14740 
14741 CreateNewDecl:
14742 
14743   TagDecl *PrevDecl = nullptr;
14744   if (Previous.isSingleResult())
14745     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14746 
14747   // If there is an identifier, use the location of the identifier as the
14748   // location of the decl, otherwise use the location of the struct/union
14749   // keyword.
14750   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14751 
14752   // Otherwise, create a new declaration. If there is a previous
14753   // declaration of the same entity, the two will be linked via
14754   // PrevDecl.
14755   TagDecl *New;
14756 
14757   if (Kind == TTK_Enum) {
14758     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14759     // enum X { A, B, C } D;    D should chain to X.
14760     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14761                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14762                            ScopedEnumUsesClassTag, IsFixed);
14763 
14764     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14765       StdAlignValT = cast<EnumDecl>(New);
14766 
14767     // If this is an undefined enum, warn.
14768     if (TUK != TUK_Definition && !Invalid) {
14769       TagDecl *Def;
14770       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14771         // C++0x: 7.2p2: opaque-enum-declaration.
14772         // Conflicts are diagnosed above. Do nothing.
14773       }
14774       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14775         Diag(Loc, diag::ext_forward_ref_enum_def)
14776           << New;
14777         Diag(Def->getLocation(), diag::note_previous_definition);
14778       } else {
14779         unsigned DiagID = diag::ext_forward_ref_enum;
14780         if (getLangOpts().MSVCCompat)
14781           DiagID = diag::ext_ms_forward_ref_enum;
14782         else if (getLangOpts().CPlusPlus)
14783           DiagID = diag::err_forward_ref_enum;
14784         Diag(Loc, DiagID);
14785       }
14786     }
14787 
14788     if (EnumUnderlying) {
14789       EnumDecl *ED = cast<EnumDecl>(New);
14790       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14791         ED->setIntegerTypeSourceInfo(TI);
14792       else
14793         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14794       ED->setPromotionType(ED->getIntegerType());
14795       assert(ED->isComplete() && "enum with type should be complete");
14796     }
14797   } else {
14798     // struct/union/class
14799 
14800     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14801     // struct X { int A; } D;    D should chain to X.
14802     if (getLangOpts().CPlusPlus) {
14803       // FIXME: Look for a way to use RecordDecl for simple structs.
14804       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14805                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14806 
14807       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14808         StdBadAlloc = cast<CXXRecordDecl>(New);
14809     } else
14810       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14811                                cast_or_null<RecordDecl>(PrevDecl));
14812   }
14813 
14814   // C++11 [dcl.type]p3:
14815   //   A type-specifier-seq shall not define a class or enumeration [...].
14816   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14817       TUK == TUK_Definition) {
14818     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14819       << Context.getTagDeclType(New);
14820     Invalid = true;
14821   }
14822 
14823   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14824       DC->getDeclKind() == Decl::Enum) {
14825     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14826       << Context.getTagDeclType(New);
14827     Invalid = true;
14828   }
14829 
14830   // Maybe add qualifier info.
14831   if (SS.isNotEmpty()) {
14832     if (SS.isSet()) {
14833       // If this is either a declaration or a definition, check the
14834       // nested-name-specifier against the current context.
14835       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14836           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14837                                        isMemberSpecialization))
14838         Invalid = true;
14839 
14840       New->setQualifierInfo(SS.getWithLocInContext(Context));
14841       if (TemplateParameterLists.size() > 0) {
14842         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14843       }
14844     }
14845     else
14846       Invalid = true;
14847   }
14848 
14849   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14850     // Add alignment attributes if necessary; these attributes are checked when
14851     // the ASTContext lays out the structure.
14852     //
14853     // It is important for implementing the correct semantics that this
14854     // happen here (in ActOnTag). The #pragma pack stack is
14855     // maintained as a result of parser callbacks which can occur at
14856     // many points during the parsing of a struct declaration (because
14857     // the #pragma tokens are effectively skipped over during the
14858     // parsing of the struct).
14859     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14860       AddAlignmentAttributesForRecord(RD);
14861       AddMsStructLayoutForRecord(RD);
14862     }
14863   }
14864 
14865   if (ModulePrivateLoc.isValid()) {
14866     if (isMemberSpecialization)
14867       Diag(New->getLocation(), diag::err_module_private_specialization)
14868         << 2
14869         << FixItHint::CreateRemoval(ModulePrivateLoc);
14870     // __module_private__ does not apply to local classes. However, we only
14871     // diagnose this as an error when the declaration specifiers are
14872     // freestanding. Here, we just ignore the __module_private__.
14873     else if (!SearchDC->isFunctionOrMethod())
14874       New->setModulePrivate();
14875   }
14876 
14877   // If this is a specialization of a member class (of a class template),
14878   // check the specialization.
14879   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14880     Invalid = true;
14881 
14882   // If we're declaring or defining a tag in function prototype scope in C,
14883   // note that this type can only be used within the function and add it to
14884   // the list of decls to inject into the function definition scope.
14885   if ((Name || Kind == TTK_Enum) &&
14886       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14887     if (getLangOpts().CPlusPlus) {
14888       // C++ [dcl.fct]p6:
14889       //   Types shall not be defined in return or parameter types.
14890       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14891         Diag(Loc, diag::err_type_defined_in_param_type)
14892             << Name;
14893         Invalid = true;
14894       }
14895     } else if (!PrevDecl) {
14896       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14897     }
14898   }
14899 
14900   if (Invalid)
14901     New->setInvalidDecl();
14902 
14903   // Set the lexical context. If the tag has a C++ scope specifier, the
14904   // lexical context will be different from the semantic context.
14905   New->setLexicalDeclContext(CurContext);
14906 
14907   // Mark this as a friend decl if applicable.
14908   // In Microsoft mode, a friend declaration also acts as a forward
14909   // declaration so we always pass true to setObjectOfFriendDecl to make
14910   // the tag name visible.
14911   if (TUK == TUK_Friend)
14912     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14913 
14914   // Set the access specifier.
14915   if (!Invalid && SearchDC->isRecord())
14916     SetMemberAccessSpecifier(New, PrevDecl, AS);
14917 
14918   if (PrevDecl)
14919     CheckRedeclarationModuleOwnership(New, PrevDecl);
14920 
14921   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14922     New->startDefinition();
14923 
14924   ProcessDeclAttributeList(S, New, Attrs);
14925   AddPragmaAttributes(S, New);
14926 
14927   // If this has an identifier, add it to the scope stack.
14928   if (TUK == TUK_Friend) {
14929     // We might be replacing an existing declaration in the lookup tables;
14930     // if so, borrow its access specifier.
14931     if (PrevDecl)
14932       New->setAccess(PrevDecl->getAccess());
14933 
14934     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14935     DC->makeDeclVisibleInContext(New);
14936     if (Name) // can be null along some error paths
14937       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14938         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14939   } else if (Name) {
14940     S = getNonFieldDeclScope(S);
14941     PushOnScopeChains(New, S, true);
14942   } else {
14943     CurContext->addDecl(New);
14944   }
14945 
14946   // If this is the C FILE type, notify the AST context.
14947   if (IdentifierInfo *II = New->getIdentifier())
14948     if (!New->isInvalidDecl() &&
14949         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14950         II->isStr("FILE"))
14951       Context.setFILEDecl(New);
14952 
14953   if (PrevDecl)
14954     mergeDeclAttributes(New, PrevDecl);
14955 
14956   // If there's a #pragma GCC visibility in scope, set the visibility of this
14957   // record.
14958   AddPushedVisibilityAttribute(New);
14959 
14960   if (isMemberSpecialization && !New->isInvalidDecl())
14961     CompleteMemberSpecialization(New, Previous);
14962 
14963   OwnedDecl = true;
14964   // In C++, don't return an invalid declaration. We can't recover well from
14965   // the cases where we make the type anonymous.
14966   if (Invalid && getLangOpts().CPlusPlus) {
14967     if (New->isBeingDefined())
14968       if (auto RD = dyn_cast<RecordDecl>(New))
14969         RD->completeDefinition();
14970     return nullptr;
14971   } else if (SkipBody && SkipBody->ShouldSkip) {
14972     return SkipBody->Previous;
14973   } else {
14974     return New;
14975   }
14976 }
14977 
14978 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14979   AdjustDeclIfTemplate(TagD);
14980   TagDecl *Tag = cast<TagDecl>(TagD);
14981 
14982   // Enter the tag context.
14983   PushDeclContext(S, Tag);
14984 
14985   ActOnDocumentableDecl(TagD);
14986 
14987   // If there's a #pragma GCC visibility in scope, set the visibility of this
14988   // record.
14989   AddPushedVisibilityAttribute(Tag);
14990 }
14991 
14992 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14993                                     SkipBodyInfo &SkipBody) {
14994   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14995     return false;
14996 
14997   // Make the previous decl visible.
14998   makeMergedDefinitionVisible(SkipBody.Previous);
14999   return true;
15000 }
15001 
15002 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15003   assert(isa<ObjCContainerDecl>(IDecl) &&
15004          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15005   DeclContext *OCD = cast<DeclContext>(IDecl);
15006   assert(getContainingDC(OCD) == CurContext &&
15007       "The next DeclContext should be lexically contained in the current one.");
15008   CurContext = OCD;
15009   return IDecl;
15010 }
15011 
15012 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15013                                            SourceLocation FinalLoc,
15014                                            bool IsFinalSpelledSealed,
15015                                            SourceLocation LBraceLoc) {
15016   AdjustDeclIfTemplate(TagD);
15017   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15018 
15019   FieldCollector->StartClass();
15020 
15021   if (!Record->getIdentifier())
15022     return;
15023 
15024   if (FinalLoc.isValid())
15025     Record->addAttr(new (Context)
15026                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15027 
15028   // C++ [class]p2:
15029   //   [...] The class-name is also inserted into the scope of the
15030   //   class itself; this is known as the injected-class-name. For
15031   //   purposes of access checking, the injected-class-name is treated
15032   //   as if it were a public member name.
15033   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15034       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15035       Record->getLocation(), Record->getIdentifier(),
15036       /*PrevDecl=*/nullptr,
15037       /*DelayTypeCreation=*/true);
15038   Context.getTypeDeclType(InjectedClassName, Record);
15039   InjectedClassName->setImplicit();
15040   InjectedClassName->setAccess(AS_public);
15041   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15042       InjectedClassName->setDescribedClassTemplate(Template);
15043   PushOnScopeChains(InjectedClassName, S);
15044   assert(InjectedClassName->isInjectedClassName() &&
15045          "Broken injected-class-name");
15046 }
15047 
15048 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15049                                     SourceRange BraceRange) {
15050   AdjustDeclIfTemplate(TagD);
15051   TagDecl *Tag = cast<TagDecl>(TagD);
15052   Tag->setBraceRange(BraceRange);
15053 
15054   // Make sure we "complete" the definition even it is invalid.
15055   if (Tag->isBeingDefined()) {
15056     assert(Tag->isInvalidDecl() && "We should already have completed it");
15057     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15058       RD->completeDefinition();
15059   }
15060 
15061   if (isa<CXXRecordDecl>(Tag)) {
15062     FieldCollector->FinishClass();
15063   }
15064 
15065   // Exit this scope of this tag's definition.
15066   PopDeclContext();
15067 
15068   if (getCurLexicalContext()->isObjCContainer() &&
15069       Tag->getDeclContext()->isFileContext())
15070     Tag->setTopLevelDeclInObjCContainer();
15071 
15072   // Notify the consumer that we've defined a tag.
15073   if (!Tag->isInvalidDecl())
15074     Consumer.HandleTagDeclDefinition(Tag);
15075 }
15076 
15077 void Sema::ActOnObjCContainerFinishDefinition() {
15078   // Exit this scope of this interface definition.
15079   PopDeclContext();
15080 }
15081 
15082 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15083   assert(DC == CurContext && "Mismatch of container contexts");
15084   OriginalLexicalContext = DC;
15085   ActOnObjCContainerFinishDefinition();
15086 }
15087 
15088 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15089   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15090   OriginalLexicalContext = nullptr;
15091 }
15092 
15093 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15094   AdjustDeclIfTemplate(TagD);
15095   TagDecl *Tag = cast<TagDecl>(TagD);
15096   Tag->setInvalidDecl();
15097 
15098   // Make sure we "complete" the definition even it is invalid.
15099   if (Tag->isBeingDefined()) {
15100     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15101       RD->completeDefinition();
15102   }
15103 
15104   // We're undoing ActOnTagStartDefinition here, not
15105   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15106   // the FieldCollector.
15107 
15108   PopDeclContext();
15109 }
15110 
15111 // Note that FieldName may be null for anonymous bitfields.
15112 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15113                                 IdentifierInfo *FieldName,
15114                                 QualType FieldTy, bool IsMsStruct,
15115                                 Expr *BitWidth, bool *ZeroWidth) {
15116   // Default to true; that shouldn't confuse checks for emptiness
15117   if (ZeroWidth)
15118     *ZeroWidth = true;
15119 
15120   // C99 6.7.2.1p4 - verify the field type.
15121   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15122   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15123     // Handle incomplete types with specific error.
15124     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15125       return ExprError();
15126     if (FieldName)
15127       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15128         << FieldName << FieldTy << BitWidth->getSourceRange();
15129     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15130       << FieldTy << BitWidth->getSourceRange();
15131   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15132                                              UPPC_BitFieldWidth))
15133     return ExprError();
15134 
15135   // If the bit-width is type- or value-dependent, don't try to check
15136   // it now.
15137   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15138     return BitWidth;
15139 
15140   llvm::APSInt Value;
15141   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15142   if (ICE.isInvalid())
15143     return ICE;
15144   BitWidth = ICE.get();
15145 
15146   if (Value != 0 && ZeroWidth)
15147     *ZeroWidth = false;
15148 
15149   // Zero-width bitfield is ok for anonymous field.
15150   if (Value == 0 && FieldName)
15151     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15152 
15153   if (Value.isSigned() && Value.isNegative()) {
15154     if (FieldName)
15155       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15156                << FieldName << Value.toString(10);
15157     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15158       << Value.toString(10);
15159   }
15160 
15161   if (!FieldTy->isDependentType()) {
15162     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15163     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15164     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15165 
15166     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15167     // ABI.
15168     bool CStdConstraintViolation =
15169         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15170     bool MSBitfieldViolation =
15171         Value.ugt(TypeStorageSize) &&
15172         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15173     if (CStdConstraintViolation || MSBitfieldViolation) {
15174       unsigned DiagWidth =
15175           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15176       if (FieldName)
15177         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15178                << FieldName << (unsigned)Value.getZExtValue()
15179                << !CStdConstraintViolation << DiagWidth;
15180 
15181       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15182              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15183              << DiagWidth;
15184     }
15185 
15186     // Warn on types where the user might conceivably expect to get all
15187     // specified bits as value bits: that's all integral types other than
15188     // 'bool'.
15189     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15190       if (FieldName)
15191         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15192             << FieldName << (unsigned)Value.getZExtValue()
15193             << (unsigned)TypeWidth;
15194       else
15195         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15196             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15197     }
15198   }
15199 
15200   return BitWidth;
15201 }
15202 
15203 /// ActOnField - Each field of a C struct/union is passed into this in order
15204 /// to create a FieldDecl object for it.
15205 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15206                        Declarator &D, Expr *BitfieldWidth) {
15207   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15208                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15209                                /*InitStyle=*/ICIS_NoInit, AS_public);
15210   return Res;
15211 }
15212 
15213 /// HandleField - Analyze a field of a C struct or a C++ data member.
15214 ///
15215 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15216                              SourceLocation DeclStart,
15217                              Declarator &D, Expr *BitWidth,
15218                              InClassInitStyle InitStyle,
15219                              AccessSpecifier AS) {
15220   if (D.isDecompositionDeclarator()) {
15221     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15222     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15223       << Decomp.getSourceRange();
15224     return nullptr;
15225   }
15226 
15227   IdentifierInfo *II = D.getIdentifier();
15228   SourceLocation Loc = DeclStart;
15229   if (II) Loc = D.getIdentifierLoc();
15230 
15231   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15232   QualType T = TInfo->getType();
15233   if (getLangOpts().CPlusPlus) {
15234     CheckExtraCXXDefaultArguments(D);
15235 
15236     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15237                                         UPPC_DataMemberType)) {
15238       D.setInvalidType();
15239       T = Context.IntTy;
15240       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15241     }
15242   }
15243 
15244   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15245 
15246   if (D.getDeclSpec().isInlineSpecified())
15247     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15248         << getLangOpts().CPlusPlus17;
15249   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15250     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15251          diag::err_invalid_thread)
15252       << DeclSpec::getSpecifierName(TSCS);
15253 
15254   // Check to see if this name was declared as a member previously
15255   NamedDecl *PrevDecl = nullptr;
15256   LookupResult Previous(*this, II, Loc, LookupMemberName,
15257                         ForVisibleRedeclaration);
15258   LookupName(Previous, S);
15259   switch (Previous.getResultKind()) {
15260     case LookupResult::Found:
15261     case LookupResult::FoundUnresolvedValue:
15262       PrevDecl = Previous.getAsSingle<NamedDecl>();
15263       break;
15264 
15265     case LookupResult::FoundOverloaded:
15266       PrevDecl = Previous.getRepresentativeDecl();
15267       break;
15268 
15269     case LookupResult::NotFound:
15270     case LookupResult::NotFoundInCurrentInstantiation:
15271     case LookupResult::Ambiguous:
15272       break;
15273   }
15274   Previous.suppressDiagnostics();
15275 
15276   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15277     // Maybe we will complain about the shadowed template parameter.
15278     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15279     // Just pretend that we didn't see the previous declaration.
15280     PrevDecl = nullptr;
15281   }
15282 
15283   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15284     PrevDecl = nullptr;
15285 
15286   bool Mutable
15287     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15288   SourceLocation TSSL = D.getBeginLoc();
15289   FieldDecl *NewFD
15290     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15291                      TSSL, AS, PrevDecl, &D);
15292 
15293   if (NewFD->isInvalidDecl())
15294     Record->setInvalidDecl();
15295 
15296   if (D.getDeclSpec().isModulePrivateSpecified())
15297     NewFD->setModulePrivate();
15298 
15299   if (NewFD->isInvalidDecl() && PrevDecl) {
15300     // Don't introduce NewFD into scope; there's already something
15301     // with the same name in the same scope.
15302   } else if (II) {
15303     PushOnScopeChains(NewFD, S);
15304   } else
15305     Record->addDecl(NewFD);
15306 
15307   return NewFD;
15308 }
15309 
15310 /// Build a new FieldDecl and check its well-formedness.
15311 ///
15312 /// This routine builds a new FieldDecl given the fields name, type,
15313 /// record, etc. \p PrevDecl should refer to any previous declaration
15314 /// with the same name and in the same scope as the field to be
15315 /// created.
15316 ///
15317 /// \returns a new FieldDecl.
15318 ///
15319 /// \todo The Declarator argument is a hack. It will be removed once
15320 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15321                                 TypeSourceInfo *TInfo,
15322                                 RecordDecl *Record, SourceLocation Loc,
15323                                 bool Mutable, Expr *BitWidth,
15324                                 InClassInitStyle InitStyle,
15325                                 SourceLocation TSSL,
15326                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15327                                 Declarator *D) {
15328   IdentifierInfo *II = Name.getAsIdentifierInfo();
15329   bool InvalidDecl = false;
15330   if (D) InvalidDecl = D->isInvalidType();
15331 
15332   // If we receive a broken type, recover by assuming 'int' and
15333   // marking this declaration as invalid.
15334   if (T.isNull()) {
15335     InvalidDecl = true;
15336     T = Context.IntTy;
15337   }
15338 
15339   QualType EltTy = Context.getBaseElementType(T);
15340   if (!EltTy->isDependentType()) {
15341     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15342       // Fields of incomplete type force their record to be invalid.
15343       Record->setInvalidDecl();
15344       InvalidDecl = true;
15345     } else {
15346       NamedDecl *Def;
15347       EltTy->isIncompleteType(&Def);
15348       if (Def && Def->isInvalidDecl()) {
15349         Record->setInvalidDecl();
15350         InvalidDecl = true;
15351       }
15352     }
15353   }
15354 
15355   // TR 18037 does not allow fields to be declared with address space
15356   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15357       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15358     Diag(Loc, diag::err_field_with_address_space);
15359     Record->setInvalidDecl();
15360     InvalidDecl = true;
15361   }
15362 
15363   if (LangOpts.OpenCL) {
15364     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15365     // used as structure or union field: image, sampler, event or block types.
15366     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15367         T->isBlockPointerType()) {
15368       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15369       Record->setInvalidDecl();
15370       InvalidDecl = true;
15371     }
15372     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15373     if (BitWidth) {
15374       Diag(Loc, diag::err_opencl_bitfields);
15375       InvalidDecl = true;
15376     }
15377   }
15378 
15379   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15380   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15381       T.hasQualifiers()) {
15382     InvalidDecl = true;
15383     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15384   }
15385 
15386   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15387   // than a variably modified type.
15388   if (!InvalidDecl && T->isVariablyModifiedType()) {
15389     bool SizeIsNegative;
15390     llvm::APSInt Oversized;
15391 
15392     TypeSourceInfo *FixedTInfo =
15393       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15394                                                     SizeIsNegative,
15395                                                     Oversized);
15396     if (FixedTInfo) {
15397       Diag(Loc, diag::warn_illegal_constant_array_size);
15398       TInfo = FixedTInfo;
15399       T = FixedTInfo->getType();
15400     } else {
15401       if (SizeIsNegative)
15402         Diag(Loc, diag::err_typecheck_negative_array_size);
15403       else if (Oversized.getBoolValue())
15404         Diag(Loc, diag::err_array_too_large)
15405           << Oversized.toString(10);
15406       else
15407         Diag(Loc, diag::err_typecheck_field_variable_size);
15408       InvalidDecl = true;
15409     }
15410   }
15411 
15412   // Fields can not have abstract class types
15413   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15414                                              diag::err_abstract_type_in_decl,
15415                                              AbstractFieldType))
15416     InvalidDecl = true;
15417 
15418   bool ZeroWidth = false;
15419   if (InvalidDecl)
15420     BitWidth = nullptr;
15421   // If this is declared as a bit-field, check the bit-field.
15422   if (BitWidth) {
15423     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15424                               &ZeroWidth).get();
15425     if (!BitWidth) {
15426       InvalidDecl = true;
15427       BitWidth = nullptr;
15428       ZeroWidth = false;
15429     }
15430   }
15431 
15432   // Check that 'mutable' is consistent with the type of the declaration.
15433   if (!InvalidDecl && Mutable) {
15434     unsigned DiagID = 0;
15435     if (T->isReferenceType())
15436       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15437                                         : diag::err_mutable_reference;
15438     else if (T.isConstQualified())
15439       DiagID = diag::err_mutable_const;
15440 
15441     if (DiagID) {
15442       SourceLocation ErrLoc = Loc;
15443       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15444         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15445       Diag(ErrLoc, DiagID);
15446       if (DiagID != diag::ext_mutable_reference) {
15447         Mutable = false;
15448         InvalidDecl = true;
15449       }
15450     }
15451   }
15452 
15453   // C++11 [class.union]p8 (DR1460):
15454   //   At most one variant member of a union may have a
15455   //   brace-or-equal-initializer.
15456   if (InitStyle != ICIS_NoInit)
15457     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15458 
15459   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15460                                        BitWidth, Mutable, InitStyle);
15461   if (InvalidDecl)
15462     NewFD->setInvalidDecl();
15463 
15464   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15465     Diag(Loc, diag::err_duplicate_member) << II;
15466     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15467     NewFD->setInvalidDecl();
15468   }
15469 
15470   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15471     if (Record->isUnion()) {
15472       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15473         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15474         if (RDecl->getDefinition()) {
15475           // C++ [class.union]p1: An object of a class with a non-trivial
15476           // constructor, a non-trivial copy constructor, a non-trivial
15477           // destructor, or a non-trivial copy assignment operator
15478           // cannot be a member of a union, nor can an array of such
15479           // objects.
15480           if (CheckNontrivialField(NewFD))
15481             NewFD->setInvalidDecl();
15482         }
15483       }
15484 
15485       // C++ [class.union]p1: If a union contains a member of reference type,
15486       // the program is ill-formed, except when compiling with MSVC extensions
15487       // enabled.
15488       if (EltTy->isReferenceType()) {
15489         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15490                                     diag::ext_union_member_of_reference_type :
15491                                     diag::err_union_member_of_reference_type)
15492           << NewFD->getDeclName() << EltTy;
15493         if (!getLangOpts().MicrosoftExt)
15494           NewFD->setInvalidDecl();
15495       }
15496     }
15497   }
15498 
15499   // FIXME: We need to pass in the attributes given an AST
15500   // representation, not a parser representation.
15501   if (D) {
15502     // FIXME: The current scope is almost... but not entirely... correct here.
15503     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15504 
15505     if (NewFD->hasAttrs())
15506       CheckAlignasUnderalignment(NewFD);
15507   }
15508 
15509   // In auto-retain/release, infer strong retension for fields of
15510   // retainable type.
15511   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15512     NewFD->setInvalidDecl();
15513 
15514   if (T.isObjCGCWeak())
15515     Diag(Loc, diag::warn_attribute_weak_on_field);
15516 
15517   NewFD->setAccess(AS);
15518   return NewFD;
15519 }
15520 
15521 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15522   assert(FD);
15523   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15524 
15525   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15526     return false;
15527 
15528   QualType EltTy = Context.getBaseElementType(FD->getType());
15529   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15530     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15531     if (RDecl->getDefinition()) {
15532       // We check for copy constructors before constructors
15533       // because otherwise we'll never get complaints about
15534       // copy constructors.
15535 
15536       CXXSpecialMember member = CXXInvalid;
15537       // We're required to check for any non-trivial constructors. Since the
15538       // implicit default constructor is suppressed if there are any
15539       // user-declared constructors, we just need to check that there is a
15540       // trivial default constructor and a trivial copy constructor. (We don't
15541       // worry about move constructors here, since this is a C++98 check.)
15542       if (RDecl->hasNonTrivialCopyConstructor())
15543         member = CXXCopyConstructor;
15544       else if (!RDecl->hasTrivialDefaultConstructor())
15545         member = CXXDefaultConstructor;
15546       else if (RDecl->hasNonTrivialCopyAssignment())
15547         member = CXXCopyAssignment;
15548       else if (RDecl->hasNonTrivialDestructor())
15549         member = CXXDestructor;
15550 
15551       if (member != CXXInvalid) {
15552         if (!getLangOpts().CPlusPlus11 &&
15553             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15554           // Objective-C++ ARC: it is an error to have a non-trivial field of
15555           // a union. However, system headers in Objective-C programs
15556           // occasionally have Objective-C lifetime objects within unions,
15557           // and rather than cause the program to fail, we make those
15558           // members unavailable.
15559           SourceLocation Loc = FD->getLocation();
15560           if (getSourceManager().isInSystemHeader(Loc)) {
15561             if (!FD->hasAttr<UnavailableAttr>())
15562               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15563                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15564             return false;
15565           }
15566         }
15567 
15568         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15569                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15570                diag::err_illegal_union_or_anon_struct_member)
15571           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15572         DiagnoseNontrivial(RDecl, member);
15573         return !getLangOpts().CPlusPlus11;
15574       }
15575     }
15576   }
15577 
15578   return false;
15579 }
15580 
15581 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15582 ///  AST enum value.
15583 static ObjCIvarDecl::AccessControl
15584 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15585   switch (ivarVisibility) {
15586   default: llvm_unreachable("Unknown visitibility kind");
15587   case tok::objc_private: return ObjCIvarDecl::Private;
15588   case tok::objc_public: return ObjCIvarDecl::Public;
15589   case tok::objc_protected: return ObjCIvarDecl::Protected;
15590   case tok::objc_package: return ObjCIvarDecl::Package;
15591   }
15592 }
15593 
15594 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15595 /// in order to create an IvarDecl object for it.
15596 Decl *Sema::ActOnIvar(Scope *S,
15597                                 SourceLocation DeclStart,
15598                                 Declarator &D, Expr *BitfieldWidth,
15599                                 tok::ObjCKeywordKind Visibility) {
15600 
15601   IdentifierInfo *II = D.getIdentifier();
15602   Expr *BitWidth = (Expr*)BitfieldWidth;
15603   SourceLocation Loc = DeclStart;
15604   if (II) Loc = D.getIdentifierLoc();
15605 
15606   // FIXME: Unnamed fields can be handled in various different ways, for
15607   // example, unnamed unions inject all members into the struct namespace!
15608 
15609   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15610   QualType T = TInfo->getType();
15611 
15612   if (BitWidth) {
15613     // 6.7.2.1p3, 6.7.2.1p4
15614     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15615     if (!BitWidth)
15616       D.setInvalidType();
15617   } else {
15618     // Not a bitfield.
15619 
15620     // validate II.
15621 
15622   }
15623   if (T->isReferenceType()) {
15624     Diag(Loc, diag::err_ivar_reference_type);
15625     D.setInvalidType();
15626   }
15627   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15628   // than a variably modified type.
15629   else if (T->isVariablyModifiedType()) {
15630     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15631     D.setInvalidType();
15632   }
15633 
15634   // Get the visibility (access control) for this ivar.
15635   ObjCIvarDecl::AccessControl ac =
15636     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15637                                         : ObjCIvarDecl::None;
15638   // Must set ivar's DeclContext to its enclosing interface.
15639   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15640   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15641     return nullptr;
15642   ObjCContainerDecl *EnclosingContext;
15643   if (ObjCImplementationDecl *IMPDecl =
15644       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15645     if (LangOpts.ObjCRuntime.isFragile()) {
15646     // Case of ivar declared in an implementation. Context is that of its class.
15647       EnclosingContext = IMPDecl->getClassInterface();
15648       assert(EnclosingContext && "Implementation has no class interface!");
15649     }
15650     else
15651       EnclosingContext = EnclosingDecl;
15652   } else {
15653     if (ObjCCategoryDecl *CDecl =
15654         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15655       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15656         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15657         return nullptr;
15658       }
15659     }
15660     EnclosingContext = EnclosingDecl;
15661   }
15662 
15663   // Construct the decl.
15664   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15665                                              DeclStart, Loc, II, T,
15666                                              TInfo, ac, (Expr *)BitfieldWidth);
15667 
15668   if (II) {
15669     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15670                                            ForVisibleRedeclaration);
15671     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15672         && !isa<TagDecl>(PrevDecl)) {
15673       Diag(Loc, diag::err_duplicate_member) << II;
15674       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15675       NewID->setInvalidDecl();
15676     }
15677   }
15678 
15679   // Process attributes attached to the ivar.
15680   ProcessDeclAttributes(S, NewID, D);
15681 
15682   if (D.isInvalidType())
15683     NewID->setInvalidDecl();
15684 
15685   // In ARC, infer 'retaining' for ivars of retainable type.
15686   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15687     NewID->setInvalidDecl();
15688 
15689   if (D.getDeclSpec().isModulePrivateSpecified())
15690     NewID->setModulePrivate();
15691 
15692   if (II) {
15693     // FIXME: When interfaces are DeclContexts, we'll need to add
15694     // these to the interface.
15695     S->AddDecl(NewID);
15696     IdResolver.AddDecl(NewID);
15697   }
15698 
15699   if (LangOpts.ObjCRuntime.isNonFragile() &&
15700       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15701     Diag(Loc, diag::warn_ivars_in_interface);
15702 
15703   return NewID;
15704 }
15705 
15706 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15707 /// class and class extensions. For every class \@interface and class
15708 /// extension \@interface, if the last ivar is a bitfield of any type,
15709 /// then add an implicit `char :0` ivar to the end of that interface.
15710 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15711                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15712   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15713     return;
15714 
15715   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15716   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15717 
15718   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15719     return;
15720   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15721   if (!ID) {
15722     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15723       if (!CD->IsClassExtension())
15724         return;
15725     }
15726     // No need to add this to end of @implementation.
15727     else
15728       return;
15729   }
15730   // All conditions are met. Add a new bitfield to the tail end of ivars.
15731   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15732   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15733 
15734   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15735                               DeclLoc, DeclLoc, nullptr,
15736                               Context.CharTy,
15737                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15738                                                                DeclLoc),
15739                               ObjCIvarDecl::Private, BW,
15740                               true);
15741   AllIvarDecls.push_back(Ivar);
15742 }
15743 
15744 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15745                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15746                        SourceLocation RBrac,
15747                        const ParsedAttributesView &Attrs) {
15748   assert(EnclosingDecl && "missing record or interface decl");
15749 
15750   // If this is an Objective-C @implementation or category and we have
15751   // new fields here we should reset the layout of the interface since
15752   // it will now change.
15753   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15754     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15755     switch (DC->getKind()) {
15756     default: break;
15757     case Decl::ObjCCategory:
15758       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15759       break;
15760     case Decl::ObjCImplementation:
15761       Context.
15762         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15763       break;
15764     }
15765   }
15766 
15767   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15768   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15769 
15770   // Start counting up the number of named members; make sure to include
15771   // members of anonymous structs and unions in the total.
15772   unsigned NumNamedMembers = 0;
15773   if (Record) {
15774     for (const auto *I : Record->decls()) {
15775       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15776         if (IFD->getDeclName())
15777           ++NumNamedMembers;
15778     }
15779   }
15780 
15781   // Verify that all the fields are okay.
15782   SmallVector<FieldDecl*, 32> RecFields;
15783 
15784   bool ObjCFieldLifetimeErrReported = false;
15785   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15786        i != end; ++i) {
15787     FieldDecl *FD = cast<FieldDecl>(*i);
15788 
15789     // Get the type for the field.
15790     const Type *FDTy = FD->getType().getTypePtr();
15791 
15792     if (!FD->isAnonymousStructOrUnion()) {
15793       // Remember all fields written by the user.
15794       RecFields.push_back(FD);
15795     }
15796 
15797     // If the field is already invalid for some reason, don't emit more
15798     // diagnostics about it.
15799     if (FD->isInvalidDecl()) {
15800       EnclosingDecl->setInvalidDecl();
15801       continue;
15802     }
15803 
15804     // C99 6.7.2.1p2:
15805     //   A structure or union shall not contain a member with
15806     //   incomplete or function type (hence, a structure shall not
15807     //   contain an instance of itself, but may contain a pointer to
15808     //   an instance of itself), except that the last member of a
15809     //   structure with more than one named member may have incomplete
15810     //   array type; such a structure (and any union containing,
15811     //   possibly recursively, a member that is such a structure)
15812     //   shall not be a member of a structure or an element of an
15813     //   array.
15814     bool IsLastField = (i + 1 == Fields.end());
15815     if (FDTy->isFunctionType()) {
15816       // Field declared as a function.
15817       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15818         << FD->getDeclName();
15819       FD->setInvalidDecl();
15820       EnclosingDecl->setInvalidDecl();
15821       continue;
15822     } else if (FDTy->isIncompleteArrayType() &&
15823                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15824       if (Record) {
15825         // Flexible array member.
15826         // Microsoft and g++ is more permissive regarding flexible array.
15827         // It will accept flexible array in union and also
15828         // as the sole element of a struct/class.
15829         unsigned DiagID = 0;
15830         if (!Record->isUnion() && !IsLastField) {
15831           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15832             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15833           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15834           FD->setInvalidDecl();
15835           EnclosingDecl->setInvalidDecl();
15836           continue;
15837         } else if (Record->isUnion())
15838           DiagID = getLangOpts().MicrosoftExt
15839                        ? diag::ext_flexible_array_union_ms
15840                        : getLangOpts().CPlusPlus
15841                              ? diag::ext_flexible_array_union_gnu
15842                              : diag::err_flexible_array_union;
15843         else if (NumNamedMembers < 1)
15844           DiagID = getLangOpts().MicrosoftExt
15845                        ? diag::ext_flexible_array_empty_aggregate_ms
15846                        : getLangOpts().CPlusPlus
15847                              ? diag::ext_flexible_array_empty_aggregate_gnu
15848                              : diag::err_flexible_array_empty_aggregate;
15849 
15850         if (DiagID)
15851           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15852                                           << Record->getTagKind();
15853         // While the layout of types that contain virtual bases is not specified
15854         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15855         // virtual bases after the derived members.  This would make a flexible
15856         // array member declared at the end of an object not adjacent to the end
15857         // of the type.
15858         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15859           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15860               << FD->getDeclName() << Record->getTagKind();
15861         if (!getLangOpts().C99)
15862           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15863             << FD->getDeclName() << Record->getTagKind();
15864 
15865         // If the element type has a non-trivial destructor, we would not
15866         // implicitly destroy the elements, so disallow it for now.
15867         //
15868         // FIXME: GCC allows this. We should probably either implicitly delete
15869         // the destructor of the containing class, or just allow this.
15870         QualType BaseElem = Context.getBaseElementType(FD->getType());
15871         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15872           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15873             << FD->getDeclName() << FD->getType();
15874           FD->setInvalidDecl();
15875           EnclosingDecl->setInvalidDecl();
15876           continue;
15877         }
15878         // Okay, we have a legal flexible array member at the end of the struct.
15879         Record->setHasFlexibleArrayMember(true);
15880       } else {
15881         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15882         // unless they are followed by another ivar. That check is done
15883         // elsewhere, after synthesized ivars are known.
15884       }
15885     } else if (!FDTy->isDependentType() &&
15886                RequireCompleteType(FD->getLocation(), FD->getType(),
15887                                    diag::err_field_incomplete)) {
15888       // Incomplete type
15889       FD->setInvalidDecl();
15890       EnclosingDecl->setInvalidDecl();
15891       continue;
15892     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15893       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15894         // A type which contains a flexible array member is considered to be a
15895         // flexible array member.
15896         Record->setHasFlexibleArrayMember(true);
15897         if (!Record->isUnion()) {
15898           // If this is a struct/class and this is not the last element, reject
15899           // it.  Note that GCC supports variable sized arrays in the middle of
15900           // structures.
15901           if (!IsLastField)
15902             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15903               << FD->getDeclName() << FD->getType();
15904           else {
15905             // We support flexible arrays at the end of structs in
15906             // other structs as an extension.
15907             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15908               << FD->getDeclName();
15909           }
15910         }
15911       }
15912       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15913           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15914                                  diag::err_abstract_type_in_decl,
15915                                  AbstractIvarType)) {
15916         // Ivars can not have abstract class types
15917         FD->setInvalidDecl();
15918       }
15919       if (Record && FDTTy->getDecl()->hasObjectMember())
15920         Record->setHasObjectMember(true);
15921       if (Record && FDTTy->getDecl()->hasVolatileMember())
15922         Record->setHasVolatileMember(true);
15923       if (Record && Record->isUnion() &&
15924           FD->getType().isNonTrivialPrimitiveCType(Context))
15925         Diag(FD->getLocation(),
15926              diag::err_nontrivial_primitive_type_in_union);
15927     } else if (FDTy->isObjCObjectType()) {
15928       /// A field cannot be an Objective-c object
15929       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15930         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15931       QualType T = Context.getObjCObjectPointerType(FD->getType());
15932       FD->setType(T);
15933     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15934                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
15935                !getLangOpts().CPlusPlus) {
15936       // It's an error in ARC or Weak if a field has lifetime.
15937       // We don't want to report this in a system header, though,
15938       // so we just make the field unavailable.
15939       // FIXME: that's really not sufficient; we need to make the type
15940       // itself invalid to, say, initialize or copy.
15941       QualType T = FD->getType();
15942       if (T.hasNonTrivialObjCLifetime()) {
15943         SourceLocation loc = FD->getLocation();
15944         if (getSourceManager().isInSystemHeader(loc)) {
15945           if (!FD->hasAttr<UnavailableAttr>()) {
15946             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15947                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15948           }
15949         } else {
15950           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15951             << T->isBlockPointerType() << Record->getTagKind();
15952         }
15953         ObjCFieldLifetimeErrReported = true;
15954       }
15955     } else if (getLangOpts().ObjC &&
15956                getLangOpts().getGC() != LangOptions::NonGC &&
15957                Record && !Record->hasObjectMember()) {
15958       if (FD->getType()->isObjCObjectPointerType() ||
15959           FD->getType().isObjCGCStrong())
15960         Record->setHasObjectMember(true);
15961       else if (Context.getAsArrayType(FD->getType())) {
15962         QualType BaseType = Context.getBaseElementType(FD->getType());
15963         if (BaseType->isRecordType() &&
15964             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15965           Record->setHasObjectMember(true);
15966         else if (BaseType->isObjCObjectPointerType() ||
15967                  BaseType.isObjCGCStrong())
15968                Record->setHasObjectMember(true);
15969       }
15970     }
15971 
15972     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15973       QualType FT = FD->getType();
15974       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15975         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15976       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15977       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15978         Record->setNonTrivialToPrimitiveCopy(true);
15979       if (FT.isDestructedType()) {
15980         Record->setNonTrivialToPrimitiveDestroy(true);
15981         Record->setParamDestroyedInCallee(true);
15982       }
15983 
15984       if (const auto *RT = FT->getAs<RecordType>()) {
15985         if (RT->getDecl()->getArgPassingRestrictions() ==
15986             RecordDecl::APK_CanNeverPassInRegs)
15987           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15988       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15989         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15990     }
15991 
15992     if (Record && FD->getType().isVolatileQualified())
15993       Record->setHasVolatileMember(true);
15994     // Keep track of the number of named members.
15995     if (FD->getIdentifier())
15996       ++NumNamedMembers;
15997   }
15998 
15999   // Okay, we successfully defined 'Record'.
16000   if (Record) {
16001     bool Completed = false;
16002     if (CXXRecord) {
16003       if (!CXXRecord->isInvalidDecl()) {
16004         // Set access bits correctly on the directly-declared conversions.
16005         for (CXXRecordDecl::conversion_iterator
16006                I = CXXRecord->conversion_begin(),
16007                E = CXXRecord->conversion_end(); I != E; ++I)
16008           I.setAccess((*I)->getAccess());
16009       }
16010 
16011       if (!CXXRecord->isDependentType()) {
16012         // Add any implicitly-declared members to this class.
16013         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16014 
16015         if (!CXXRecord->isInvalidDecl()) {
16016           // If we have virtual base classes, we may end up finding multiple
16017           // final overriders for a given virtual function. Check for this
16018           // problem now.
16019           if (CXXRecord->getNumVBases()) {
16020             CXXFinalOverriderMap FinalOverriders;
16021             CXXRecord->getFinalOverriders(FinalOverriders);
16022 
16023             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16024                                              MEnd = FinalOverriders.end();
16025                  M != MEnd; ++M) {
16026               for (OverridingMethods::iterator SO = M->second.begin(),
16027                                             SOEnd = M->second.end();
16028                    SO != SOEnd; ++SO) {
16029                 assert(SO->second.size() > 0 &&
16030                        "Virtual function without overriding functions?");
16031                 if (SO->second.size() == 1)
16032                   continue;
16033 
16034                 // C++ [class.virtual]p2:
16035                 //   In a derived class, if a virtual member function of a base
16036                 //   class subobject has more than one final overrider the
16037                 //   program is ill-formed.
16038                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16039                   << (const NamedDecl *)M->first << Record;
16040                 Diag(M->first->getLocation(),
16041                      diag::note_overridden_virtual_function);
16042                 for (OverridingMethods::overriding_iterator
16043                           OM = SO->second.begin(),
16044                        OMEnd = SO->second.end();
16045                      OM != OMEnd; ++OM)
16046                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16047                     << (const NamedDecl *)M->first << OM->Method->getParent();
16048 
16049                 Record->setInvalidDecl();
16050               }
16051             }
16052             CXXRecord->completeDefinition(&FinalOverriders);
16053             Completed = true;
16054           }
16055         }
16056       }
16057     }
16058 
16059     if (!Completed)
16060       Record->completeDefinition();
16061 
16062     // Handle attributes before checking the layout.
16063     ProcessDeclAttributeList(S, Record, Attrs);
16064 
16065     // We may have deferred checking for a deleted destructor. Check now.
16066     if (CXXRecord) {
16067       auto *Dtor = CXXRecord->getDestructor();
16068       if (Dtor && Dtor->isImplicit() &&
16069           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16070         CXXRecord->setImplicitDestructorIsDeleted();
16071         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16072       }
16073     }
16074 
16075     if (Record->hasAttrs()) {
16076       CheckAlignasUnderalignment(Record);
16077 
16078       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16079         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16080                                            IA->getRange(), IA->getBestCase(),
16081                                            IA->getSemanticSpelling());
16082     }
16083 
16084     // Check if the structure/union declaration is a type that can have zero
16085     // size in C. For C this is a language extension, for C++ it may cause
16086     // compatibility problems.
16087     bool CheckForZeroSize;
16088     if (!getLangOpts().CPlusPlus) {
16089       CheckForZeroSize = true;
16090     } else {
16091       // For C++ filter out types that cannot be referenced in C code.
16092       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16093       CheckForZeroSize =
16094           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16095           !CXXRecord->isDependentType() &&
16096           CXXRecord->isCLike();
16097     }
16098     if (CheckForZeroSize) {
16099       bool ZeroSize = true;
16100       bool IsEmpty = true;
16101       unsigned NonBitFields = 0;
16102       for (RecordDecl::field_iterator I = Record->field_begin(),
16103                                       E = Record->field_end();
16104            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16105         IsEmpty = false;
16106         if (I->isUnnamedBitfield()) {
16107           if (!I->isZeroLengthBitField(Context))
16108             ZeroSize = false;
16109         } else {
16110           ++NonBitFields;
16111           QualType FieldType = I->getType();
16112           if (FieldType->isIncompleteType() ||
16113               !Context.getTypeSizeInChars(FieldType).isZero())
16114             ZeroSize = false;
16115         }
16116       }
16117 
16118       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16119       // allowed in C++, but warn if its declaration is inside
16120       // extern "C" block.
16121       if (ZeroSize) {
16122         Diag(RecLoc, getLangOpts().CPlusPlus ?
16123                          diag::warn_zero_size_struct_union_in_extern_c :
16124                          diag::warn_zero_size_struct_union_compat)
16125           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16126       }
16127 
16128       // Structs without named members are extension in C (C99 6.7.2.1p7),
16129       // but are accepted by GCC.
16130       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16131         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16132                                diag::ext_no_named_members_in_struct_union)
16133           << Record->isUnion();
16134       }
16135     }
16136   } else {
16137     ObjCIvarDecl **ClsFields =
16138       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16139     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16140       ID->setEndOfDefinitionLoc(RBrac);
16141       // Add ivar's to class's DeclContext.
16142       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16143         ClsFields[i]->setLexicalDeclContext(ID);
16144         ID->addDecl(ClsFields[i]);
16145       }
16146       // Must enforce the rule that ivars in the base classes may not be
16147       // duplicates.
16148       if (ID->getSuperClass())
16149         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16150     } else if (ObjCImplementationDecl *IMPDecl =
16151                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16152       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16153       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16154         // Ivar declared in @implementation never belongs to the implementation.
16155         // Only it is in implementation's lexical context.
16156         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16157       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16158       IMPDecl->setIvarLBraceLoc(LBrac);
16159       IMPDecl->setIvarRBraceLoc(RBrac);
16160     } else if (ObjCCategoryDecl *CDecl =
16161                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16162       // case of ivars in class extension; all other cases have been
16163       // reported as errors elsewhere.
16164       // FIXME. Class extension does not have a LocEnd field.
16165       // CDecl->setLocEnd(RBrac);
16166       // Add ivar's to class extension's DeclContext.
16167       // Diagnose redeclaration of private ivars.
16168       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16169       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16170         if (IDecl) {
16171           if (const ObjCIvarDecl *ClsIvar =
16172               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16173             Diag(ClsFields[i]->getLocation(),
16174                  diag::err_duplicate_ivar_declaration);
16175             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16176             continue;
16177           }
16178           for (const auto *Ext : IDecl->known_extensions()) {
16179             if (const ObjCIvarDecl *ClsExtIvar
16180                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16181               Diag(ClsFields[i]->getLocation(),
16182                    diag::err_duplicate_ivar_declaration);
16183               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16184               continue;
16185             }
16186           }
16187         }
16188         ClsFields[i]->setLexicalDeclContext(CDecl);
16189         CDecl->addDecl(ClsFields[i]);
16190       }
16191       CDecl->setIvarLBraceLoc(LBrac);
16192       CDecl->setIvarRBraceLoc(RBrac);
16193     }
16194   }
16195 }
16196 
16197 /// Determine whether the given integral value is representable within
16198 /// the given type T.
16199 static bool isRepresentableIntegerValue(ASTContext &Context,
16200                                         llvm::APSInt &Value,
16201                                         QualType T) {
16202   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16203          "Integral type required!");
16204   unsigned BitWidth = Context.getIntWidth(T);
16205 
16206   if (Value.isUnsigned() || Value.isNonNegative()) {
16207     if (T->isSignedIntegerOrEnumerationType())
16208       --BitWidth;
16209     return Value.getActiveBits() <= BitWidth;
16210   }
16211   return Value.getMinSignedBits() <= BitWidth;
16212 }
16213 
16214 // Given an integral type, return the next larger integral type
16215 // (or a NULL type of no such type exists).
16216 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16217   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16218   // enum checking below.
16219   assert((T->isIntegralType(Context) ||
16220          T->isEnumeralType()) && "Integral type required!");
16221   const unsigned NumTypes = 4;
16222   QualType SignedIntegralTypes[NumTypes] = {
16223     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16224   };
16225   QualType UnsignedIntegralTypes[NumTypes] = {
16226     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16227     Context.UnsignedLongLongTy
16228   };
16229 
16230   unsigned BitWidth = Context.getTypeSize(T);
16231   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16232                                                         : UnsignedIntegralTypes;
16233   for (unsigned I = 0; I != NumTypes; ++I)
16234     if (Context.getTypeSize(Types[I]) > BitWidth)
16235       return Types[I];
16236 
16237   return QualType();
16238 }
16239 
16240 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16241                                           EnumConstantDecl *LastEnumConst,
16242                                           SourceLocation IdLoc,
16243                                           IdentifierInfo *Id,
16244                                           Expr *Val) {
16245   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16246   llvm::APSInt EnumVal(IntWidth);
16247   QualType EltTy;
16248 
16249   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16250     Val = nullptr;
16251 
16252   if (Val)
16253     Val = DefaultLvalueConversion(Val).get();
16254 
16255   if (Val) {
16256     if (Enum->isDependentType() || Val->isTypeDependent())
16257       EltTy = Context.DependentTy;
16258     else {
16259       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16260           !getLangOpts().MSVCCompat) {
16261         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16262         // constant-expression in the enumerator-definition shall be a converted
16263         // constant expression of the underlying type.
16264         EltTy = Enum->getIntegerType();
16265         ExprResult Converted =
16266           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16267                                            CCEK_Enumerator);
16268         if (Converted.isInvalid())
16269           Val = nullptr;
16270         else
16271           Val = Converted.get();
16272       } else if (!Val->isValueDependent() &&
16273                  !(Val = VerifyIntegerConstantExpression(Val,
16274                                                          &EnumVal).get())) {
16275         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16276       } else {
16277         if (Enum->isComplete()) {
16278           EltTy = Enum->getIntegerType();
16279 
16280           // In Obj-C and Microsoft mode, require the enumeration value to be
16281           // representable in the underlying type of the enumeration. In C++11,
16282           // we perform a non-narrowing conversion as part of converted constant
16283           // expression checking.
16284           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16285             if (getLangOpts().MSVCCompat) {
16286               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16287               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16288             } else
16289               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16290           } else
16291             Val = ImpCastExprToType(Val, EltTy,
16292                                     EltTy->isBooleanType() ?
16293                                     CK_IntegralToBoolean : CK_IntegralCast)
16294                     .get();
16295         } else if (getLangOpts().CPlusPlus) {
16296           // C++11 [dcl.enum]p5:
16297           //   If the underlying type is not fixed, the type of each enumerator
16298           //   is the type of its initializing value:
16299           //     - If an initializer is specified for an enumerator, the
16300           //       initializing value has the same type as the expression.
16301           EltTy = Val->getType();
16302         } else {
16303           // C99 6.7.2.2p2:
16304           //   The expression that defines the value of an enumeration constant
16305           //   shall be an integer constant expression that has a value
16306           //   representable as an int.
16307 
16308           // Complain if the value is not representable in an int.
16309           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16310             Diag(IdLoc, diag::ext_enum_value_not_int)
16311               << EnumVal.toString(10) << Val->getSourceRange()
16312               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16313           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16314             // Force the type of the expression to 'int'.
16315             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16316           }
16317           EltTy = Val->getType();
16318         }
16319       }
16320     }
16321   }
16322 
16323   if (!Val) {
16324     if (Enum->isDependentType())
16325       EltTy = Context.DependentTy;
16326     else if (!LastEnumConst) {
16327       // C++0x [dcl.enum]p5:
16328       //   If the underlying type is not fixed, the type of each enumerator
16329       //   is the type of its initializing value:
16330       //     - If no initializer is specified for the first enumerator, the
16331       //       initializing value has an unspecified integral type.
16332       //
16333       // GCC uses 'int' for its unspecified integral type, as does
16334       // C99 6.7.2.2p3.
16335       if (Enum->isFixed()) {
16336         EltTy = Enum->getIntegerType();
16337       }
16338       else {
16339         EltTy = Context.IntTy;
16340       }
16341     } else {
16342       // Assign the last value + 1.
16343       EnumVal = LastEnumConst->getInitVal();
16344       ++EnumVal;
16345       EltTy = LastEnumConst->getType();
16346 
16347       // Check for overflow on increment.
16348       if (EnumVal < LastEnumConst->getInitVal()) {
16349         // C++0x [dcl.enum]p5:
16350         //   If the underlying type is not fixed, the type of each enumerator
16351         //   is the type of its initializing value:
16352         //
16353         //     - Otherwise the type of the initializing value is the same as
16354         //       the type of the initializing value of the preceding enumerator
16355         //       unless the incremented value is not representable in that type,
16356         //       in which case the type is an unspecified integral type
16357         //       sufficient to contain the incremented value. If no such type
16358         //       exists, the program is ill-formed.
16359         QualType T = getNextLargerIntegralType(Context, EltTy);
16360         if (T.isNull() || Enum->isFixed()) {
16361           // There is no integral type larger enough to represent this
16362           // value. Complain, then allow the value to wrap around.
16363           EnumVal = LastEnumConst->getInitVal();
16364           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16365           ++EnumVal;
16366           if (Enum->isFixed())
16367             // When the underlying type is fixed, this is ill-formed.
16368             Diag(IdLoc, diag::err_enumerator_wrapped)
16369               << EnumVal.toString(10)
16370               << EltTy;
16371           else
16372             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16373               << EnumVal.toString(10);
16374         } else {
16375           EltTy = T;
16376         }
16377 
16378         // Retrieve the last enumerator's value, extent that type to the
16379         // type that is supposed to be large enough to represent the incremented
16380         // value, then increment.
16381         EnumVal = LastEnumConst->getInitVal();
16382         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16383         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16384         ++EnumVal;
16385 
16386         // If we're not in C++, diagnose the overflow of enumerator values,
16387         // which in C99 means that the enumerator value is not representable in
16388         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16389         // permits enumerator values that are representable in some larger
16390         // integral type.
16391         if (!getLangOpts().CPlusPlus && !T.isNull())
16392           Diag(IdLoc, diag::warn_enum_value_overflow);
16393       } else if (!getLangOpts().CPlusPlus &&
16394                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16395         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16396         Diag(IdLoc, diag::ext_enum_value_not_int)
16397           << EnumVal.toString(10) << 1;
16398       }
16399     }
16400   }
16401 
16402   if (!EltTy->isDependentType()) {
16403     // Make the enumerator value match the signedness and size of the
16404     // enumerator's type.
16405     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16406     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16407   }
16408 
16409   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16410                                   Val, EnumVal);
16411 }
16412 
16413 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16414                                                 SourceLocation IILoc) {
16415   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16416       !getLangOpts().CPlusPlus)
16417     return SkipBodyInfo();
16418 
16419   // We have an anonymous enum definition. Look up the first enumerator to
16420   // determine if we should merge the definition with an existing one and
16421   // skip the body.
16422   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16423                                          forRedeclarationInCurContext());
16424   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16425   if (!PrevECD)
16426     return SkipBodyInfo();
16427 
16428   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16429   NamedDecl *Hidden;
16430   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16431     SkipBodyInfo Skip;
16432     Skip.Previous = Hidden;
16433     return Skip;
16434   }
16435 
16436   return SkipBodyInfo();
16437 }
16438 
16439 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16440                               SourceLocation IdLoc, IdentifierInfo *Id,
16441                               const ParsedAttributesView &Attrs,
16442                               SourceLocation EqualLoc, Expr *Val) {
16443   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16444   EnumConstantDecl *LastEnumConst =
16445     cast_or_null<EnumConstantDecl>(lastEnumConst);
16446 
16447   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16448   // we find one that is.
16449   S = getNonFieldDeclScope(S);
16450 
16451   // Verify that there isn't already something declared with this name in this
16452   // scope.
16453   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16454   LookupName(R, S);
16455   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16456 
16457   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16458     // Maybe we will complain about the shadowed template parameter.
16459     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16460     // Just pretend that we didn't see the previous declaration.
16461     PrevDecl = nullptr;
16462   }
16463 
16464   // C++ [class.mem]p15:
16465   // If T is the name of a class, then each of the following shall have a name
16466   // different from T:
16467   // - every enumerator of every member of class T that is an unscoped
16468   // enumerated type
16469   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16470     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16471                             DeclarationNameInfo(Id, IdLoc));
16472 
16473   EnumConstantDecl *New =
16474     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16475   if (!New)
16476     return nullptr;
16477 
16478   if (PrevDecl) {
16479     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16480       // Check for other kinds of shadowing not already handled.
16481       CheckShadow(New, PrevDecl, R);
16482     }
16483 
16484     // When in C++, we may get a TagDecl with the same name; in this case the
16485     // enum constant will 'hide' the tag.
16486     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16487            "Received TagDecl when not in C++!");
16488     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16489       if (isa<EnumConstantDecl>(PrevDecl))
16490         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16491       else
16492         Diag(IdLoc, diag::err_redefinition) << Id;
16493       notePreviousDefinition(PrevDecl, IdLoc);
16494       return nullptr;
16495     }
16496   }
16497 
16498   // Process attributes.
16499   ProcessDeclAttributeList(S, New, Attrs);
16500   AddPragmaAttributes(S, New);
16501 
16502   // Register this decl in the current scope stack.
16503   New->setAccess(TheEnumDecl->getAccess());
16504   PushOnScopeChains(New, S);
16505 
16506   ActOnDocumentableDecl(New);
16507 
16508   return New;
16509 }
16510 
16511 // Returns true when the enum initial expression does not trigger the
16512 // duplicate enum warning.  A few common cases are exempted as follows:
16513 // Element2 = Element1
16514 // Element2 = Element1 + 1
16515 // Element2 = Element1 - 1
16516 // Where Element2 and Element1 are from the same enum.
16517 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16518   Expr *InitExpr = ECD->getInitExpr();
16519   if (!InitExpr)
16520     return true;
16521   InitExpr = InitExpr->IgnoreImpCasts();
16522 
16523   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16524     if (!BO->isAdditiveOp())
16525       return true;
16526     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16527     if (!IL)
16528       return true;
16529     if (IL->getValue() != 1)
16530       return true;
16531 
16532     InitExpr = BO->getLHS();
16533   }
16534 
16535   // This checks if the elements are from the same enum.
16536   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16537   if (!DRE)
16538     return true;
16539 
16540   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16541   if (!EnumConstant)
16542     return true;
16543 
16544   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16545       Enum)
16546     return true;
16547 
16548   return false;
16549 }
16550 
16551 // Emits a warning when an element is implicitly set a value that
16552 // a previous element has already been set to.
16553 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16554                                         EnumDecl *Enum, QualType EnumType) {
16555   // Avoid anonymous enums
16556   if (!Enum->getIdentifier())
16557     return;
16558 
16559   // Only check for small enums.
16560   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16561     return;
16562 
16563   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16564     return;
16565 
16566   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16567   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16568 
16569   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16570   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16571 
16572   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16573   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16574     llvm::APSInt Val = D->getInitVal();
16575     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16576   };
16577 
16578   DuplicatesVector DupVector;
16579   ValueToVectorMap EnumMap;
16580 
16581   // Populate the EnumMap with all values represented by enum constants without
16582   // an initializer.
16583   for (auto *Element : Elements) {
16584     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16585 
16586     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16587     // this constant.  Skip this enum since it may be ill-formed.
16588     if (!ECD) {
16589       return;
16590     }
16591 
16592     // Constants with initalizers are handled in the next loop.
16593     if (ECD->getInitExpr())
16594       continue;
16595 
16596     // Duplicate values are handled in the next loop.
16597     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16598   }
16599 
16600   if (EnumMap.size() == 0)
16601     return;
16602 
16603   // Create vectors for any values that has duplicates.
16604   for (auto *Element : Elements) {
16605     // The last loop returned if any constant was null.
16606     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16607     if (!ValidDuplicateEnum(ECD, Enum))
16608       continue;
16609 
16610     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16611     if (Iter == EnumMap.end())
16612       continue;
16613 
16614     DeclOrVector& Entry = Iter->second;
16615     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16616       // Ensure constants are different.
16617       if (D == ECD)
16618         continue;
16619 
16620       // Create new vector and push values onto it.
16621       auto Vec = llvm::make_unique<ECDVector>();
16622       Vec->push_back(D);
16623       Vec->push_back(ECD);
16624 
16625       // Update entry to point to the duplicates vector.
16626       Entry = Vec.get();
16627 
16628       // Store the vector somewhere we can consult later for quick emission of
16629       // diagnostics.
16630       DupVector.emplace_back(std::move(Vec));
16631       continue;
16632     }
16633 
16634     ECDVector *Vec = Entry.get<ECDVector*>();
16635     // Make sure constants are not added more than once.
16636     if (*Vec->begin() == ECD)
16637       continue;
16638 
16639     Vec->push_back(ECD);
16640   }
16641 
16642   // Emit diagnostics.
16643   for (const auto &Vec : DupVector) {
16644     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16645 
16646     // Emit warning for one enum constant.
16647     auto *FirstECD = Vec->front();
16648     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16649       << FirstECD << FirstECD->getInitVal().toString(10)
16650       << FirstECD->getSourceRange();
16651 
16652     // Emit one note for each of the remaining enum constants with
16653     // the same value.
16654     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16655       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16656         << ECD << ECD->getInitVal().toString(10)
16657         << ECD->getSourceRange();
16658   }
16659 }
16660 
16661 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16662                              bool AllowMask) const {
16663   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16664   assert(ED->isCompleteDefinition() && "expected enum definition");
16665 
16666   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16667   llvm::APInt &FlagBits = R.first->second;
16668 
16669   if (R.second) {
16670     for (auto *E : ED->enumerators()) {
16671       const auto &EVal = E->getInitVal();
16672       // Only single-bit enumerators introduce new flag values.
16673       if (EVal.isPowerOf2())
16674         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16675     }
16676   }
16677 
16678   // A value is in a flag enum if either its bits are a subset of the enum's
16679   // flag bits (the first condition) or we are allowing masks and the same is
16680   // true of its complement (the second condition). When masks are allowed, we
16681   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16682   //
16683   // While it's true that any value could be used as a mask, the assumption is
16684   // that a mask will have all of the insignificant bits set. Anything else is
16685   // likely a logic error.
16686   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16687   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16688 }
16689 
16690 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16691                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16692                          const ParsedAttributesView &Attrs) {
16693   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16694   QualType EnumType = Context.getTypeDeclType(Enum);
16695 
16696   ProcessDeclAttributeList(S, Enum, Attrs);
16697 
16698   if (Enum->isDependentType()) {
16699     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16700       EnumConstantDecl *ECD =
16701         cast_or_null<EnumConstantDecl>(Elements[i]);
16702       if (!ECD) continue;
16703 
16704       ECD->setType(EnumType);
16705     }
16706 
16707     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16708     return;
16709   }
16710 
16711   // TODO: If the result value doesn't fit in an int, it must be a long or long
16712   // long value.  ISO C does not support this, but GCC does as an extension,
16713   // emit a warning.
16714   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16715   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16716   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16717 
16718   // Verify that all the values are okay, compute the size of the values, and
16719   // reverse the list.
16720   unsigned NumNegativeBits = 0;
16721   unsigned NumPositiveBits = 0;
16722 
16723   // Keep track of whether all elements have type int.
16724   bool AllElementsInt = true;
16725 
16726   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16727     EnumConstantDecl *ECD =
16728       cast_or_null<EnumConstantDecl>(Elements[i]);
16729     if (!ECD) continue;  // Already issued a diagnostic.
16730 
16731     const llvm::APSInt &InitVal = ECD->getInitVal();
16732 
16733     // Keep track of the size of positive and negative values.
16734     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16735       NumPositiveBits = std::max(NumPositiveBits,
16736                                  (unsigned)InitVal.getActiveBits());
16737     else
16738       NumNegativeBits = std::max(NumNegativeBits,
16739                                  (unsigned)InitVal.getMinSignedBits());
16740 
16741     // Keep track of whether every enum element has type int (very common).
16742     if (AllElementsInt)
16743       AllElementsInt = ECD->getType() == Context.IntTy;
16744   }
16745 
16746   // Figure out the type that should be used for this enum.
16747   QualType BestType;
16748   unsigned BestWidth;
16749 
16750   // C++0x N3000 [conv.prom]p3:
16751   //   An rvalue of an unscoped enumeration type whose underlying
16752   //   type is not fixed can be converted to an rvalue of the first
16753   //   of the following types that can represent all the values of
16754   //   the enumeration: int, unsigned int, long int, unsigned long
16755   //   int, long long int, or unsigned long long int.
16756   // C99 6.4.4.3p2:
16757   //   An identifier declared as an enumeration constant has type int.
16758   // The C99 rule is modified by a gcc extension
16759   QualType BestPromotionType;
16760 
16761   bool Packed = Enum->hasAttr<PackedAttr>();
16762   // -fshort-enums is the equivalent to specifying the packed attribute on all
16763   // enum definitions.
16764   if (LangOpts.ShortEnums)
16765     Packed = true;
16766 
16767   // If the enum already has a type because it is fixed or dictated by the
16768   // target, promote that type instead of analyzing the enumerators.
16769   if (Enum->isComplete()) {
16770     BestType = Enum->getIntegerType();
16771     if (BestType->isPromotableIntegerType())
16772       BestPromotionType = Context.getPromotedIntegerType(BestType);
16773     else
16774       BestPromotionType = BestType;
16775 
16776     BestWidth = Context.getIntWidth(BestType);
16777   }
16778   else if (NumNegativeBits) {
16779     // If there is a negative value, figure out the smallest integer type (of
16780     // int/long/longlong) that fits.
16781     // If it's packed, check also if it fits a char or a short.
16782     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16783       BestType = Context.SignedCharTy;
16784       BestWidth = CharWidth;
16785     } else if (Packed && NumNegativeBits <= ShortWidth &&
16786                NumPositiveBits < ShortWidth) {
16787       BestType = Context.ShortTy;
16788       BestWidth = ShortWidth;
16789     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16790       BestType = Context.IntTy;
16791       BestWidth = IntWidth;
16792     } else {
16793       BestWidth = Context.getTargetInfo().getLongWidth();
16794 
16795       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16796         BestType = Context.LongTy;
16797       } else {
16798         BestWidth = Context.getTargetInfo().getLongLongWidth();
16799 
16800         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16801           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16802         BestType = Context.LongLongTy;
16803       }
16804     }
16805     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16806   } else {
16807     // If there is no negative value, figure out the smallest type that fits
16808     // all of the enumerator values.
16809     // If it's packed, check also if it fits a char or a short.
16810     if (Packed && NumPositiveBits <= CharWidth) {
16811       BestType = Context.UnsignedCharTy;
16812       BestPromotionType = Context.IntTy;
16813       BestWidth = CharWidth;
16814     } else if (Packed && NumPositiveBits <= ShortWidth) {
16815       BestType = Context.UnsignedShortTy;
16816       BestPromotionType = Context.IntTy;
16817       BestWidth = ShortWidth;
16818     } else if (NumPositiveBits <= IntWidth) {
16819       BestType = Context.UnsignedIntTy;
16820       BestWidth = IntWidth;
16821       BestPromotionType
16822         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16823                            ? Context.UnsignedIntTy : Context.IntTy;
16824     } else if (NumPositiveBits <=
16825                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16826       BestType = Context.UnsignedLongTy;
16827       BestPromotionType
16828         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16829                            ? Context.UnsignedLongTy : Context.LongTy;
16830     } else {
16831       BestWidth = Context.getTargetInfo().getLongLongWidth();
16832       assert(NumPositiveBits <= BestWidth &&
16833              "How could an initializer get larger than ULL?");
16834       BestType = Context.UnsignedLongLongTy;
16835       BestPromotionType
16836         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16837                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16838     }
16839   }
16840 
16841   // Loop over all of the enumerator constants, changing their types to match
16842   // the type of the enum if needed.
16843   for (auto *D : Elements) {
16844     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16845     if (!ECD) continue;  // Already issued a diagnostic.
16846 
16847     // Standard C says the enumerators have int type, but we allow, as an
16848     // extension, the enumerators to be larger than int size.  If each
16849     // enumerator value fits in an int, type it as an int, otherwise type it the
16850     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16851     // that X has type 'int', not 'unsigned'.
16852 
16853     // Determine whether the value fits into an int.
16854     llvm::APSInt InitVal = ECD->getInitVal();
16855 
16856     // If it fits into an integer type, force it.  Otherwise force it to match
16857     // the enum decl type.
16858     QualType NewTy;
16859     unsigned NewWidth;
16860     bool NewSign;
16861     if (!getLangOpts().CPlusPlus &&
16862         !Enum->isFixed() &&
16863         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16864       NewTy = Context.IntTy;
16865       NewWidth = IntWidth;
16866       NewSign = true;
16867     } else if (ECD->getType() == BestType) {
16868       // Already the right type!
16869       if (getLangOpts().CPlusPlus)
16870         // C++ [dcl.enum]p4: Following the closing brace of an
16871         // enum-specifier, each enumerator has the type of its
16872         // enumeration.
16873         ECD->setType(EnumType);
16874       continue;
16875     } else {
16876       NewTy = BestType;
16877       NewWidth = BestWidth;
16878       NewSign = BestType->isSignedIntegerOrEnumerationType();
16879     }
16880 
16881     // Adjust the APSInt value.
16882     InitVal = InitVal.extOrTrunc(NewWidth);
16883     InitVal.setIsSigned(NewSign);
16884     ECD->setInitVal(InitVal);
16885 
16886     // Adjust the Expr initializer and type.
16887     if (ECD->getInitExpr() &&
16888         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16889       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16890                                                 CK_IntegralCast,
16891                                                 ECD->getInitExpr(),
16892                                                 /*base paths*/ nullptr,
16893                                                 VK_RValue));
16894     if (getLangOpts().CPlusPlus)
16895       // C++ [dcl.enum]p4: Following the closing brace of an
16896       // enum-specifier, each enumerator has the type of its
16897       // enumeration.
16898       ECD->setType(EnumType);
16899     else
16900       ECD->setType(NewTy);
16901   }
16902 
16903   Enum->completeDefinition(BestType, BestPromotionType,
16904                            NumPositiveBits, NumNegativeBits);
16905 
16906   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16907 
16908   if (Enum->isClosedFlag()) {
16909     for (Decl *D : Elements) {
16910       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16911       if (!ECD) continue;  // Already issued a diagnostic.
16912 
16913       llvm::APSInt InitVal = ECD->getInitVal();
16914       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16915           !IsValueInFlagEnum(Enum, InitVal, true))
16916         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16917           << ECD << Enum;
16918     }
16919   }
16920 
16921   // Now that the enum type is defined, ensure it's not been underaligned.
16922   if (Enum->hasAttrs())
16923     CheckAlignasUnderalignment(Enum);
16924 }
16925 
16926 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16927                                   SourceLocation StartLoc,
16928                                   SourceLocation EndLoc) {
16929   StringLiteral *AsmString = cast<StringLiteral>(expr);
16930 
16931   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16932                                                    AsmString, StartLoc,
16933                                                    EndLoc);
16934   CurContext->addDecl(New);
16935   return New;
16936 }
16937 
16938 static void checkModuleImportContext(Sema &S, Module *M,
16939                                      SourceLocation ImportLoc, DeclContext *DC,
16940                                      bool FromInclude = false) {
16941   SourceLocation ExternCLoc;
16942 
16943   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16944     switch (LSD->getLanguage()) {
16945     case LinkageSpecDecl::lang_c:
16946       if (ExternCLoc.isInvalid())
16947         ExternCLoc = LSD->getBeginLoc();
16948       break;
16949     case LinkageSpecDecl::lang_cxx:
16950       break;
16951     }
16952     DC = LSD->getParent();
16953   }
16954 
16955   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16956     DC = DC->getParent();
16957 
16958   if (!isa<TranslationUnitDecl>(DC)) {
16959     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16960                           ? diag::ext_module_import_not_at_top_level_noop
16961                           : diag::err_module_import_not_at_top_level_fatal)
16962         << M->getFullModuleName() << DC;
16963     S.Diag(cast<Decl>(DC)->getBeginLoc(),
16964            diag::note_module_import_not_at_top_level)
16965         << DC;
16966   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16967     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16968       << M->getFullModuleName();
16969     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16970   }
16971 }
16972 
16973 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16974                                            SourceLocation ModuleLoc,
16975                                            ModuleDeclKind MDK,
16976                                            ModuleIdPath Path) {
16977   assert(getLangOpts().ModulesTS &&
16978          "should only have module decl in modules TS");
16979 
16980   // A module implementation unit requires that we are not compiling a module
16981   // of any kind. A module interface unit requires that we are not compiling a
16982   // module map.
16983   switch (getLangOpts().getCompilingModule()) {
16984   case LangOptions::CMK_None:
16985     // It's OK to compile a module interface as a normal translation unit.
16986     break;
16987 
16988   case LangOptions::CMK_ModuleInterface:
16989     if (MDK != ModuleDeclKind::Implementation)
16990       break;
16991 
16992     // We were asked to compile a module interface unit but this is a module
16993     // implementation unit. That indicates the 'export' is missing.
16994     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16995       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16996     MDK = ModuleDeclKind::Interface;
16997     break;
16998 
16999   case LangOptions::CMK_ModuleMap:
17000     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
17001     return nullptr;
17002 
17003   case LangOptions::CMK_HeaderModule:
17004     Diag(ModuleLoc, diag::err_module_decl_in_header_module);
17005     return nullptr;
17006   }
17007 
17008   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
17009 
17010   // FIXME: Most of this work should be done by the preprocessor rather than
17011   // here, in order to support macro import.
17012 
17013   // Only one module-declaration is permitted per source file.
17014   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
17015     Diag(ModuleLoc, diag::err_module_redeclaration);
17016     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
17017          diag::note_prev_module_declaration);
17018     return nullptr;
17019   }
17020 
17021   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
17022   // modules, the dots here are just another character that can appear in a
17023   // module name.
17024   std::string ModuleName;
17025   for (auto &Piece : Path) {
17026     if (!ModuleName.empty())
17027       ModuleName += ".";
17028     ModuleName += Piece.first->getName();
17029   }
17030 
17031   // If a module name was explicitly specified on the command line, it must be
17032   // correct.
17033   if (!getLangOpts().CurrentModule.empty() &&
17034       getLangOpts().CurrentModule != ModuleName) {
17035     Diag(Path.front().second, diag::err_current_module_name_mismatch)
17036         << SourceRange(Path.front().second, Path.back().second)
17037         << getLangOpts().CurrentModule;
17038     return nullptr;
17039   }
17040   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
17041 
17042   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
17043   Module *Mod;
17044 
17045   switch (MDK) {
17046   case ModuleDeclKind::Interface: {
17047     // We can't have parsed or imported a definition of this module or parsed a
17048     // module map defining it already.
17049     if (auto *M = Map.findModule(ModuleName)) {
17050       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
17051       if (M->DefinitionLoc.isValid())
17052         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
17053       else if (const auto *FE = M->getASTFile())
17054         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
17055             << FE->getName();
17056       Mod = M;
17057       break;
17058     }
17059 
17060     // Create a Module for the module that we're defining.
17061     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17062                                            ModuleScopes.front().Module);
17063     assert(Mod && "module creation should not fail");
17064     break;
17065   }
17066 
17067   case ModuleDeclKind::Partition:
17068     // FIXME: Check we are in a submodule of the named module.
17069     return nullptr;
17070 
17071   case ModuleDeclKind::Implementation:
17072     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
17073         PP.getIdentifierInfo(ModuleName), Path[0].second);
17074     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
17075                                        Module::AllVisible,
17076                                        /*IsIncludeDirective=*/false);
17077     if (!Mod) {
17078       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
17079       // Create an empty module interface unit for error recovery.
17080       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17081                                              ModuleScopes.front().Module);
17082     }
17083     break;
17084   }
17085 
17086   // Switch from the global module to the named module.
17087   ModuleScopes.back().Module = Mod;
17088   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
17089   VisibleModules.setVisible(Mod, ModuleLoc);
17090 
17091   // From now on, we have an owning module for all declarations we see.
17092   // However, those declarations are module-private unless explicitly
17093   // exported.
17094   auto *TU = Context.getTranslationUnitDecl();
17095   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
17096   TU->setLocalOwningModule(Mod);
17097 
17098   // FIXME: Create a ModuleDecl.
17099   return nullptr;
17100 }
17101 
17102 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
17103                                    SourceLocation ImportLoc,
17104                                    ModuleIdPath Path) {
17105   // Flatten the module path for a Modules TS module name.
17106   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
17107   if (getLangOpts().ModulesTS) {
17108     std::string ModuleName;
17109     for (auto &Piece : Path) {
17110       if (!ModuleName.empty())
17111         ModuleName += ".";
17112       ModuleName += Piece.first->getName();
17113     }
17114     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
17115     Path = ModuleIdPath(ModuleNameLoc);
17116   }
17117 
17118   Module *Mod =
17119       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
17120                                    /*IsIncludeDirective=*/false);
17121   if (!Mod)
17122     return true;
17123 
17124   VisibleModules.setVisible(Mod, ImportLoc);
17125 
17126   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
17127 
17128   // FIXME: we should support importing a submodule within a different submodule
17129   // of the same top-level module. Until we do, make it an error rather than
17130   // silently ignoring the import.
17131   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
17132   // warn on a redundant import of the current module?
17133   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
17134       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
17135     Diag(ImportLoc, getLangOpts().isCompilingModule()
17136                         ? diag::err_module_self_import
17137                         : diag::err_module_import_in_implementation)
17138         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
17139 
17140   SmallVector<SourceLocation, 2> IdentifierLocs;
17141   Module *ModCheck = Mod;
17142   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
17143     // If we've run out of module parents, just drop the remaining identifiers.
17144     // We need the length to be consistent.
17145     if (!ModCheck)
17146       break;
17147     ModCheck = ModCheck->Parent;
17148 
17149     IdentifierLocs.push_back(Path[I].second);
17150   }
17151 
17152   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17153                                           Mod, IdentifierLocs);
17154   if (!ModuleScopes.empty())
17155     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17156   CurContext->addDecl(Import);
17157 
17158   // Re-export the module if needed.
17159   if (Import->isExported() &&
17160       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17161     getCurrentModule()->Exports.emplace_back(Mod, false);
17162 
17163   return Import;
17164 }
17165 
17166 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17167   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17168   BuildModuleInclude(DirectiveLoc, Mod);
17169 }
17170 
17171 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
17172   // Determine whether we're in the #include buffer for a module. The #includes
17173   // in that buffer do not qualify as module imports; they're just an
17174   // implementation detail of us building the module.
17175   //
17176   // FIXME: Should we even get ActOnModuleInclude calls for those?
17177   bool IsInModuleIncludes =
17178       TUKind == TU_Module &&
17179       getSourceManager().isWrittenInMainFile(DirectiveLoc);
17180 
17181   bool ShouldAddImport = !IsInModuleIncludes;
17182 
17183   // If this module import was due to an inclusion directive, create an
17184   // implicit import declaration to capture it in the AST.
17185   if (ShouldAddImport) {
17186     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17187     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17188                                                      DirectiveLoc, Mod,
17189                                                      DirectiveLoc);
17190     if (!ModuleScopes.empty())
17191       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17192     TU->addDecl(ImportD);
17193     Consumer.HandleImplicitImportDecl(ImportD);
17194   }
17195 
17196   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
17197   VisibleModules.setVisible(Mod, DirectiveLoc);
17198 }
17199 
17200 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
17201   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
17202 
17203   ModuleScopes.push_back({});
17204   ModuleScopes.back().Module = Mod;
17205   if (getLangOpts().ModulesLocalVisibility)
17206     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17207 
17208   VisibleModules.setVisible(Mod, DirectiveLoc);
17209 
17210   // The enclosing context is now part of this module.
17211   // FIXME: Consider creating a child DeclContext to hold the entities
17212   // lexically within the module.
17213   if (getLangOpts().trackLocalOwningModule()) {
17214     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17215       cast<Decl>(DC)->setModuleOwnershipKind(
17216           getLangOpts().ModulesLocalVisibility
17217               ? Decl::ModuleOwnershipKind::VisibleWhenImported
17218               : Decl::ModuleOwnershipKind::Visible);
17219       cast<Decl>(DC)->setLocalOwningModule(Mod);
17220     }
17221   }
17222 }
17223 
17224 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
17225   if (getLangOpts().ModulesLocalVisibility) {
17226     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17227     // Leaving a module hides namespace names, so our visible namespace cache
17228     // is now out of date.
17229     VisibleNamespaceCache.clear();
17230   }
17231 
17232   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17233          "left the wrong module scope");
17234   ModuleScopes.pop_back();
17235 
17236   // We got to the end of processing a local module. Create an
17237   // ImportDecl as we would for an imported module.
17238   FileID File = getSourceManager().getFileID(EomLoc);
17239   SourceLocation DirectiveLoc;
17240   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17241     // We reached the end of a #included module header. Use the #include loc.
17242     assert(File != getSourceManager().getMainFileID() &&
17243            "end of submodule in main source file");
17244     DirectiveLoc = getSourceManager().getIncludeLoc(File);
17245   } else {
17246     // We reached an EOM pragma. Use the pragma location.
17247     DirectiveLoc = EomLoc;
17248   }
17249   BuildModuleInclude(DirectiveLoc, Mod);
17250 
17251   // Any further declarations are in whatever module we returned to.
17252   if (getLangOpts().trackLocalOwningModule()) {
17253     // The parser guarantees that this is the same context that we entered
17254     // the module within.
17255     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
17256       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17257       if (!getCurrentModule())
17258         cast<Decl>(DC)->setModuleOwnershipKind(
17259             Decl::ModuleOwnershipKind::Unowned);
17260     }
17261   }
17262 }
17263 
17264 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17265                                                       Module *Mod) {
17266   // Bail if we're not allowed to implicitly import a module here.
17267   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17268       VisibleModules.isVisible(Mod))
17269     return;
17270 
17271   // Create the implicit import declaration.
17272   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17273   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17274                                                    Loc, Mod, Loc);
17275   TU->addDecl(ImportD);
17276   Consumer.HandleImplicitImportDecl(ImportD);
17277 
17278   // Make the module visible.
17279   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
17280   VisibleModules.setVisible(Mod, Loc);
17281 }
17282 
17283 /// We have parsed the start of an export declaration, including the '{'
17284 /// (if present).
17285 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
17286                                  SourceLocation LBraceLoc) {
17287   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
17288 
17289   // C++ Modules TS draft:
17290   //   An export-declaration shall appear in the purview of a module other than
17291   //   the global module.
17292   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17293     Diag(ExportLoc, diag::err_export_not_in_module_interface);
17294 
17295   //   An export-declaration [...] shall not contain more than one
17296   //   export keyword.
17297   //
17298   // The intent here is that an export-declaration cannot appear within another
17299   // export-declaration.
17300   if (D->isExported())
17301     Diag(ExportLoc, diag::err_export_within_export);
17302 
17303   CurContext->addDecl(D);
17304   PushDeclContext(S, D);
17305   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17306   return D;
17307 }
17308 
17309 /// Complete the definition of an export declaration.
17310 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
17311   auto *ED = cast<ExportDecl>(D);
17312   if (RBraceLoc.isValid())
17313     ED->setRBraceLoc(RBraceLoc);
17314 
17315   // FIXME: Diagnose export of internal-linkage declaration (including
17316   // anonymous namespace).
17317 
17318   PopDeclContext();
17319   return D;
17320 }
17321 
17322 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17323                                       IdentifierInfo* AliasName,
17324                                       SourceLocation PragmaLoc,
17325                                       SourceLocation NameLoc,
17326                                       SourceLocation AliasNameLoc) {
17327   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17328                                          LookupOrdinaryName);
17329   AsmLabelAttr *Attr =
17330       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17331 
17332   // If a declaration that:
17333   // 1) declares a function or a variable
17334   // 2) has external linkage
17335   // already exists, add a label attribute to it.
17336   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17337     if (isDeclExternC(PrevDecl))
17338       PrevDecl->addAttr(Attr);
17339     else
17340       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17341           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17342   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17343   } else
17344     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17345 }
17346 
17347 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17348                              SourceLocation PragmaLoc,
17349                              SourceLocation NameLoc) {
17350   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17351 
17352   if (PrevDecl) {
17353     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17354   } else {
17355     (void)WeakUndeclaredIdentifiers.insert(
17356       std::pair<IdentifierInfo*,WeakInfo>
17357         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17358   }
17359 }
17360 
17361 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17362                                 IdentifierInfo* AliasName,
17363                                 SourceLocation PragmaLoc,
17364                                 SourceLocation NameLoc,
17365                                 SourceLocation AliasNameLoc) {
17366   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17367                                     LookupOrdinaryName);
17368   WeakInfo W = WeakInfo(Name, NameLoc);
17369 
17370   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17371     if (!PrevDecl->hasAttr<AliasAttr>())
17372       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17373         DeclApplyPragmaWeak(TUScope, ND, W);
17374   } else {
17375     (void)WeakUndeclaredIdentifiers.insert(
17376       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17377   }
17378 }
17379 
17380 Decl *Sema::getObjCDeclContext() const {
17381   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17382 }
17383