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 final : 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   std::unique_ptr<CorrectionCandidateCallback> clone() override {
109     return llvm::make_unique<TypeNameValidatorCCC>(*this);
110   }
111 
112  private:
113   bool AllowInvalidDecl;
114   bool WantClassName;
115   bool AllowTemplates;
116   bool AllowNonTemplates;
117 };
118 
119 } // end anonymous namespace
120 
121 /// Determine whether the token kind starts a simple-type-specifier.
122 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
123   switch (Kind) {
124   // FIXME: Take into account the current language when deciding whether a
125   // token kind is a valid type specifier
126   case tok::kw_short:
127   case tok::kw_long:
128   case tok::kw___int64:
129   case tok::kw___int128:
130   case tok::kw_signed:
131   case tok::kw_unsigned:
132   case tok::kw_void:
133   case tok::kw_char:
134   case tok::kw_int:
135   case tok::kw_half:
136   case tok::kw_float:
137   case tok::kw_double:
138   case tok::kw__Float16:
139   case tok::kw___float128:
140   case tok::kw_wchar_t:
141   case tok::kw_bool:
142   case tok::kw___underlying_type:
143   case tok::kw___auto_type:
144     return true;
145 
146   case tok::annot_typename:
147   case tok::kw_char16_t:
148   case tok::kw_char32_t:
149   case tok::kw_typeof:
150   case tok::annot_decltype:
151   case tok::kw_decltype:
152     return getLangOpts().CPlusPlus;
153 
154   case tok::kw_char8_t:
155     return getLangOpts().Char8;
156 
157   default:
158     break;
159   }
160 
161   return false;
162 }
163 
164 namespace {
165 enum class UnqualifiedTypeNameLookupResult {
166   NotFound,
167   FoundNonType,
168   FoundType
169 };
170 } // end anonymous namespace
171 
172 /// Tries to perform unqualified lookup of the type decls in bases for
173 /// dependent class.
174 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
175 /// type decl, \a FoundType if only type decls are found.
176 static UnqualifiedTypeNameLookupResult
177 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
178                                 SourceLocation NameLoc,
179                                 const CXXRecordDecl *RD) {
180   if (!RD->hasDefinition())
181     return UnqualifiedTypeNameLookupResult::NotFound;
182   // Look for type decls in base classes.
183   UnqualifiedTypeNameLookupResult FoundTypeDecl =
184       UnqualifiedTypeNameLookupResult::NotFound;
185   for (const auto &Base : RD->bases()) {
186     const CXXRecordDecl *BaseRD = nullptr;
187     if (auto *BaseTT = Base.getType()->getAs<TagType>())
188       BaseRD = BaseTT->getAsCXXRecordDecl();
189     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
190       // Look for type decls in dependent base classes that have known primary
191       // templates.
192       if (!TST || !TST->isDependentType())
193         continue;
194       auto *TD = TST->getTemplateName().getAsTemplateDecl();
195       if (!TD)
196         continue;
197       if (auto *BasePrimaryTemplate =
198           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
199         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
200           BaseRD = BasePrimaryTemplate;
201         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
202           if (const ClassTemplatePartialSpecializationDecl *PS =
203                   CTD->findPartialSpecialization(Base.getType()))
204             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
205               BaseRD = PS;
206         }
207       }
208     }
209     if (BaseRD) {
210       for (NamedDecl *ND : BaseRD->lookup(&II)) {
211         if (!isa<TypeDecl>(ND))
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214       }
215       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
216         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
217         case UnqualifiedTypeNameLookupResult::FoundNonType:
218           return UnqualifiedTypeNameLookupResult::FoundNonType;
219         case UnqualifiedTypeNameLookupResult::FoundType:
220           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
221           break;
222         case UnqualifiedTypeNameLookupResult::NotFound:
223           break;
224         }
225       }
226     }
227   }
228 
229   return FoundTypeDecl;
230 }
231 
232 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
233                                                       const IdentifierInfo &II,
234                                                       SourceLocation NameLoc) {
235   // Lookup in the parent class template context, if any.
236   const CXXRecordDecl *RD = nullptr;
237   UnqualifiedTypeNameLookupResult FoundTypeDecl =
238       UnqualifiedTypeNameLookupResult::NotFound;
239   for (DeclContext *DC = S.CurContext;
240        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
241        DC = DC->getParent()) {
242     // Look for type decls in dependent base classes that have known primary
243     // templates.
244     RD = dyn_cast<CXXRecordDecl>(DC);
245     if (RD && RD->getDescribedClassTemplate())
246       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
247   }
248   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
249     return nullptr;
250 
251   // We found some types in dependent base classes.  Recover as if the user
252   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
253   // lookup during template instantiation.
254   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
255 
256   ASTContext &Context = S.Context;
257   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
258                                           cast<Type>(Context.getRecordType(RD)));
259   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
260 
261   CXXScopeSpec SS;
262   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
263 
264   TypeLocBuilder Builder;
265   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
266   DepTL.setNameLoc(NameLoc);
267   DepTL.setElaboratedKeywordLoc(SourceLocation());
268   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
269   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
270 }
271 
272 /// If the identifier refers to a type name within this scope,
273 /// return the declaration of that type.
274 ///
275 /// This routine performs ordinary name lookup of the identifier II
276 /// within the given scope, with optional C++ scope specifier SS, to
277 /// determine whether the name refers to a type. If so, returns an
278 /// opaque pointer (actually a QualType) corresponding to that
279 /// type. Otherwise, returns NULL.
280 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
281                              Scope *S, CXXScopeSpec *SS,
282                              bool isClassName, bool HasTrailingDot,
283                              ParsedType ObjectTypePtr,
284                              bool IsCtorOrDtorName,
285                              bool WantNontrivialTypeSourceInfo,
286                              bool IsClassTemplateDeductionContext,
287                              IdentifierInfo **CorrectedII) {
288   // FIXME: Consider allowing this outside C++1z mode as an extension.
289   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
290                               getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
291                               !isClassName && !HasTrailingDot;
292 
293   // Determine where we will perform name lookup.
294   DeclContext *LookupCtx = nullptr;
295   if (ObjectTypePtr) {
296     QualType ObjectType = ObjectTypePtr.get();
297     if (ObjectType->isRecordType())
298       LookupCtx = computeDeclContext(ObjectType);
299   } else if (SS && SS->isNotEmpty()) {
300     LookupCtx = computeDeclContext(*SS, false);
301 
302     if (!LookupCtx) {
303       if (isDependentScopeSpecifier(*SS)) {
304         // C++ [temp.res]p3:
305         //   A qualified-id that refers to a type and in which the
306         //   nested-name-specifier depends on a template-parameter (14.6.2)
307         //   shall be prefixed by the keyword typename to indicate that the
308         //   qualified-id denotes a type, forming an
309         //   elaborated-type-specifier (7.1.5.3).
310         //
311         // We therefore do not perform any name lookup if the result would
312         // refer to a member of an unknown specialization.
313         if (!isClassName && !IsCtorOrDtorName)
314           return nullptr;
315 
316         // We know from the grammar that this name refers to a type,
317         // so build a dependent node to describe the type.
318         if (WantNontrivialTypeSourceInfo)
319           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
320 
321         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
322         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
323                                        II, NameLoc);
324         return ParsedType::make(T);
325       }
326 
327       return nullptr;
328     }
329 
330     if (!LookupCtx->isDependentContext() &&
331         RequireCompleteDeclContext(*SS, LookupCtx))
332       return nullptr;
333   }
334 
335   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
336   // lookup for class-names.
337   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
338                                       LookupOrdinaryName;
339   LookupResult Result(*this, &II, NameLoc, Kind);
340   if (LookupCtx) {
341     // Perform "qualified" name lookup into the declaration context we
342     // computed, which is either the type of the base of a member access
343     // expression or the declaration context associated with a prior
344     // nested-name-specifier.
345     LookupQualifiedName(Result, LookupCtx);
346 
347     if (ObjectTypePtr && Result.empty()) {
348       // C++ [basic.lookup.classref]p3:
349       //   If the unqualified-id is ~type-name, the type-name is looked up
350       //   in the context of the entire postfix-expression. If the type T of
351       //   the object expression is of a class type C, the type-name is also
352       //   looked up in the scope of class C. At least one of the lookups shall
353       //   find a name that refers to (possibly cv-qualified) T.
354       LookupName(Result, S);
355     }
356   } else {
357     // Perform unqualified name lookup.
358     LookupName(Result, S);
359 
360     // For unqualified lookup in a class template in MSVC mode, look into
361     // dependent base classes where the primary class template is known.
362     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
363       if (ParsedType TypeInBase =
364               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
365         return TypeInBase;
366     }
367   }
368 
369   NamedDecl *IIDecl = nullptr;
370   switch (Result.getResultKind()) {
371   case LookupResult::NotFound:
372   case LookupResult::NotFoundInCurrentInstantiation:
373     if (CorrectedII) {
374       TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
375                                AllowDeducedTemplate);
376       TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
377                                               S, SS, CCC, CTK_ErrorRecovery);
378       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
379       TemplateTy Template;
380       bool MemberOfUnknownSpecialization;
381       UnqualifiedId TemplateName;
382       TemplateName.setIdentifier(NewII, NameLoc);
383       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
384       CXXScopeSpec NewSS, *NewSSPtr = SS;
385       if (SS && NNS) {
386         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
387         NewSSPtr = &NewSS;
388       }
389       if (Correction && (NNS || NewII != &II) &&
390           // Ignore a correction to a template type as the to-be-corrected
391           // identifier is not a template (typo correction for template names
392           // is handled elsewhere).
393           !(getLangOpts().CPlusPlus && NewSSPtr &&
394             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
395                            Template, MemberOfUnknownSpecialization))) {
396         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
397                                     isClassName, HasTrailingDot, ObjectTypePtr,
398                                     IsCtorOrDtorName,
399                                     WantNontrivialTypeSourceInfo,
400                                     IsClassTemplateDeductionContext);
401         if (Ty) {
402           diagnoseTypo(Correction,
403                        PDiag(diag::err_unknown_type_or_class_name_suggest)
404                          << Result.getLookupName() << isClassName);
405           if (SS && NNS)
406             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
407           *CorrectedII = NewII;
408           return Ty;
409         }
410       }
411     }
412     // If typo correction failed or was not performed, fall through
413     LLVM_FALLTHROUGH;
414   case LookupResult::FoundOverloaded:
415   case LookupResult::FoundUnresolvedValue:
416     Result.suppressDiagnostics();
417     return nullptr;
418 
419   case LookupResult::Ambiguous:
420     // Recover from type-hiding ambiguities by hiding the type.  We'll
421     // do the lookup again when looking for an object, and we can
422     // diagnose the error then.  If we don't do this, then the error
423     // about hiding the type will be immediately followed by an error
424     // that only makes sense if the identifier was treated like a type.
425     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
426       Result.suppressDiagnostics();
427       return nullptr;
428     }
429 
430     // Look to see if we have a type anywhere in the list of results.
431     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
432          Res != ResEnd; ++Res) {
433       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
434           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
435         if (!IIDecl ||
436             (*Res)->getLocation().getRawEncoding() <
437               IIDecl->getLocation().getRawEncoding())
438           IIDecl = *Res;
439       }
440     }
441 
442     if (!IIDecl) {
443       // None of the entities we found is a type, so there is no way
444       // to even assume that the result is a type. In this case, don't
445       // complain about the ambiguity. The parser will either try to
446       // perform this lookup again (e.g., as an object name), which
447       // will produce the ambiguity, or will complain that it expected
448       // a type name.
449       Result.suppressDiagnostics();
450       return nullptr;
451     }
452 
453     // We found a type within the ambiguous lookup; diagnose the
454     // ambiguity and then return that type. This might be the right
455     // answer, or it might not be, but it suppresses any attempt to
456     // perform the name lookup again.
457     break;
458 
459   case LookupResult::Found:
460     IIDecl = Result.getFoundDecl();
461     break;
462   }
463 
464   assert(IIDecl && "Didn't find decl");
465 
466   QualType T;
467   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
468     // C++ [class.qual]p2: A lookup that would find the injected-class-name
469     // instead names the constructors of the class, except when naming a class.
470     // This is ill-formed when we're not actually forming a ctor or dtor name.
471     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
472     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
473     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
474         FoundRD->isInjectedClassName() &&
475         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
476       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
477           << &II << /*Type*/1;
478 
479     DiagnoseUseOfDecl(IIDecl, NameLoc);
480 
481     T = Context.getTypeDeclType(TD);
482     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
483   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
484     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
485     if (!HasTrailingDot)
486       T = Context.getObjCInterfaceType(IDecl);
487   } else if (AllowDeducedTemplate) {
488     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
489       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
490                                                        QualType(), false);
491   }
492 
493   if (T.isNull()) {
494     // If it's not plausibly a type, suppress diagnostics.
495     Result.suppressDiagnostics();
496     return nullptr;
497   }
498 
499   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
500   // constructor or destructor name (in such a case, the scope specifier
501   // will be attached to the enclosing Expr or Decl node).
502   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
503       !isa<ObjCInterfaceDecl>(IIDecl)) {
504     if (WantNontrivialTypeSourceInfo) {
505       // Construct a type with type-source information.
506       TypeLocBuilder Builder;
507       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
508 
509       T = getElaboratedType(ETK_None, *SS, T);
510       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
511       ElabTL.setElaboratedKeywordLoc(SourceLocation());
512       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
513       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
514     } else {
515       T = getElaboratedType(ETK_None, *SS, T);
516     }
517   }
518 
519   return ParsedType::make(T);
520 }
521 
522 // Builds a fake NNS for the given decl context.
523 static NestedNameSpecifier *
524 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
525   for (;; DC = DC->getLookupParent()) {
526     DC = DC->getPrimaryContext();
527     auto *ND = dyn_cast<NamespaceDecl>(DC);
528     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
529       return NestedNameSpecifier::Create(Context, nullptr, ND);
530     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
531       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
532                                          RD->getTypeForDecl());
533     else if (isa<TranslationUnitDecl>(DC))
534       return NestedNameSpecifier::GlobalSpecifier(Context);
535   }
536   llvm_unreachable("something isn't in TU scope?");
537 }
538 
539 /// Find the parent class with dependent bases of the innermost enclosing method
540 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
541 /// up allowing unqualified dependent type names at class-level, which MSVC
542 /// correctly rejects.
543 static const CXXRecordDecl *
544 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
545   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
546     DC = DC->getPrimaryContext();
547     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
548       if (MD->getParent()->hasAnyDependentBases())
549         return MD->getParent();
550   }
551   return nullptr;
552 }
553 
554 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
555                                           SourceLocation NameLoc,
556                                           bool IsTemplateTypeArg) {
557   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
558 
559   NestedNameSpecifier *NNS = nullptr;
560   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
561     // If we weren't able to parse a default template argument, delay lookup
562     // until instantiation time by making a non-dependent DependentTypeName. We
563     // pretend we saw a NestedNameSpecifier referring to the current scope, and
564     // lookup is retried.
565     // FIXME: This hurts our diagnostic quality, since we get errors like "no
566     // type named 'Foo' in 'current_namespace'" when the user didn't write any
567     // name specifiers.
568     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
569     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
570   } else if (const CXXRecordDecl *RD =
571                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
572     // Build a DependentNameType that will perform lookup into RD at
573     // instantiation time.
574     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
575                                       RD->getTypeForDecl());
576 
577     // Diagnose that this identifier was undeclared, and retry the lookup during
578     // template instantiation.
579     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
580                                                                       << RD;
581   } else {
582     // This is not a situation that we should recover from.
583     return ParsedType();
584   }
585 
586   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
587 
588   // Build type location information.  We synthesized the qualifier, so we have
589   // to build a fake NestedNameSpecifierLoc.
590   NestedNameSpecifierLocBuilder NNSLocBuilder;
591   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
592   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
593 
594   TypeLocBuilder Builder;
595   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
596   DepTL.setNameLoc(NameLoc);
597   DepTL.setElaboratedKeywordLoc(SourceLocation());
598   DepTL.setQualifierLoc(QualifierLoc);
599   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
600 }
601 
602 /// isTagName() - This method is called *for error recovery purposes only*
603 /// to determine if the specified name is a valid tag name ("struct foo").  If
604 /// so, this returns the TST for the tag corresponding to it (TST_enum,
605 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
606 /// cases in C where the user forgot to specify the tag.
607 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
608   // Do a tag name lookup in this scope.
609   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
610   LookupName(R, S, false);
611   R.suppressDiagnostics();
612   if (R.getResultKind() == LookupResult::Found)
613     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
614       switch (TD->getTagKind()) {
615       case TTK_Struct: return DeclSpec::TST_struct;
616       case TTK_Interface: return DeclSpec::TST_interface;
617       case TTK_Union:  return DeclSpec::TST_union;
618       case TTK_Class:  return DeclSpec::TST_class;
619       case TTK_Enum:   return DeclSpec::TST_enum;
620       }
621     }
622 
623   return DeclSpec::TST_unspecified;
624 }
625 
626 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
627 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
628 /// then downgrade the missing typename error to a warning.
629 /// This is needed for MSVC compatibility; Example:
630 /// @code
631 /// template<class T> class A {
632 /// public:
633 ///   typedef int TYPE;
634 /// };
635 /// template<class T> class B : public A<T> {
636 /// public:
637 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
638 /// };
639 /// @endcode
640 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
641   if (CurContext->isRecord()) {
642     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
643       return true;
644 
645     const Type *Ty = SS->getScopeRep()->getAsType();
646 
647     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
648     for (const auto &Base : RD->bases())
649       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
650         return true;
651     return S->isFunctionPrototypeScope();
652   }
653   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
654 }
655 
656 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
657                                    SourceLocation IILoc,
658                                    Scope *S,
659                                    CXXScopeSpec *SS,
660                                    ParsedType &SuggestedType,
661                                    bool IsTemplateName) {
662   // Don't report typename errors for editor placeholders.
663   if (II->isEditorPlaceholder())
664     return;
665   // We don't have anything to suggest (yet).
666   SuggestedType = nullptr;
667 
668   // There may have been a typo in the name of the type. Look up typo
669   // results, in case we have something that we can suggest.
670   TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
671                            /*AllowTemplates=*/IsTemplateName,
672                            /*AllowNonTemplates=*/!IsTemplateName);
673   if (TypoCorrection Corrected =
674           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
675                       CCC, CTK_ErrorRecovery)) {
676     // FIXME: Support error recovery for the template-name case.
677     bool CanRecover = !IsTemplateName;
678     if (Corrected.isKeyword()) {
679       // We corrected to a keyword.
680       diagnoseTypo(Corrected,
681                    PDiag(IsTemplateName ? diag::err_no_template_suggest
682                                         : diag::err_unknown_typename_suggest)
683                        << II);
684       II = Corrected.getCorrectionAsIdentifierInfo();
685     } else {
686       // We found a similarly-named type or interface; suggest that.
687       if (!SS || !SS->isSet()) {
688         diagnoseTypo(Corrected,
689                      PDiag(IsTemplateName ? diag::err_no_template_suggest
690                                           : diag::err_unknown_typename_suggest)
691                          << II, CanRecover);
692       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
693         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
694         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
695                                 II->getName().equals(CorrectedStr);
696         diagnoseTypo(Corrected,
697                      PDiag(IsTemplateName
698                                ? diag::err_no_member_template_suggest
699                                : diag::err_unknown_nested_typename_suggest)
700                          << II << DC << DroppedSpecifier << SS->getRange(),
701                      CanRecover);
702       } else {
703         llvm_unreachable("could not have corrected a typo here");
704       }
705 
706       if (!CanRecover)
707         return;
708 
709       CXXScopeSpec tmpSS;
710       if (Corrected.getCorrectionSpecifier())
711         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
712                           SourceRange(IILoc));
713       // FIXME: Support class template argument deduction here.
714       SuggestedType =
715           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
716                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
717                       /*IsCtorOrDtorName=*/false,
718                       /*NonTrivialTypeSourceInfo=*/true);
719     }
720     return;
721   }
722 
723   if (getLangOpts().CPlusPlus && !IsTemplateName) {
724     // See if II is a class template that the user forgot to pass arguments to.
725     UnqualifiedId Name;
726     Name.setIdentifier(II, IILoc);
727     CXXScopeSpec EmptySS;
728     TemplateTy TemplateResult;
729     bool MemberOfUnknownSpecialization;
730     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
731                        Name, nullptr, true, TemplateResult,
732                        MemberOfUnknownSpecialization) == TNK_Type_template) {
733       diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
734       return;
735     }
736   }
737 
738   // FIXME: Should we move the logic that tries to recover from a missing tag
739   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741   if (!SS || (!SS->isSet() && !SS->isInvalid()))
742     Diag(IILoc, IsTemplateName ? diag::err_no_template
743                                : diag::err_unknown_typename)
744         << II;
745   else if (DeclContext *DC = computeDeclContext(*SS, false))
746     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747                                : diag::err_typename_nested_not_found)
748         << II << DC << SS->getRange();
749   else if (isDependentScopeSpecifier(*SS)) {
750     unsigned DiagID = diag::err_typename_missing;
751     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752       DiagID = diag::ext_typename_missing;
753 
754     Diag(SS->getRange().getBegin(), DiagID)
755       << SS->getScopeRep() << II->getName()
756       << SourceRange(SS->getRange().getBegin(), IILoc)
757       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758     SuggestedType = ActOnTypenameType(S, SourceLocation(),
759                                       *SS, *II, IILoc).get();
760   } else {
761     assert(SS && SS->isInvalid() &&
762            "Invalid scope specifier has already been diagnosed");
763   }
764 }
765 
766 /// Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770                        NextToken.is(tok::less);
771 
772   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774       return true;
775 
776     if (CheckTemplate && isa<TemplateDecl>(*I))
777       return true;
778   }
779 
780   return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784                                     Scope *S, CXXScopeSpec &SS,
785                                     IdentifierInfo *&Name,
786                                     SourceLocation NameLoc) {
787   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788   SemaRef.LookupParsedName(R, S, &SS);
789   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790     StringRef FixItTagName;
791     switch (Tag->getTagKind()) {
792       case TTK_Class:
793         FixItTagName = "class ";
794         break;
795 
796       case TTK_Enum:
797         FixItTagName = "enum ";
798         break;
799 
800       case TTK_Struct:
801         FixItTagName = "struct ";
802         break;
803 
804       case TTK_Interface:
805         FixItTagName = "__interface ";
806         break;
807 
808       case TTK_Union:
809         FixItTagName = "union ";
810         break;
811     }
812 
813     StringRef TagName = FixItTagName.drop_back();
814     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819          I != IEnd; ++I)
820       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821         << Name << TagName;
822 
823     // Replace lookup results with just the tag decl.
824     Result.clear(Sema::LookupTagName);
825     SemaRef.LookupParsedName(Result, S, &SS);
826     return true;
827   }
828 
829   return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834                                   QualType T, SourceLocation NameLoc) {
835   ASTContext &Context = S.Context;
836 
837   TypeLocBuilder Builder;
838   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840   T = S.getElaboratedType(ETK_None, SS, T);
841   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842   ElabTL.setElaboratedKeywordLoc(SourceLocation());
843   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
847 Sema::NameClassification
848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849                    SourceLocation NameLoc, const Token &NextToken,
850                    bool IsAddressOfOperand, CorrectionCandidateCallback *CCC) {
851   DeclarationNameInfo NameInfo(Name, NameLoc);
852   ObjCMethodDecl *CurMethod = getCurMethodDecl();
853 
854   if (NextToken.is(tok::coloncolon)) {
855     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858              isCurrentClassName(*Name, S, &SS)) {
859     // Per [class.qual]p2, this names the constructors of SS, not the
860     // injected-class-name. We don't have a classification for that.
861     // There's not much point caching this result, since the parser
862     // will reject it later.
863     return NameClassification::Unknown();
864   }
865 
866   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867   LookupParsedName(Result, S, &SS, !CurMethod);
868 
869   // For unqualified lookup in a class template in MSVC mode, look into
870   // dependent base classes where the primary class template is known.
871   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872     if (ParsedType TypeInBase =
873             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874       return TypeInBase;
875   }
876 
877   // Perform lookup for Objective-C instance variables (including automatically
878   // synthesized instance variables), if we're in an Objective-C method.
879   // FIXME: This lookup really, really needs to be folded in to the normal
880   // unqualified lookup mechanism.
881   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883     if (E.get() || E.isInvalid())
884       return E;
885   }
886 
887   bool SecondTry = false;
888   bool IsFilteredTemplateName = false;
889 
890 Corrected:
891   switch (Result.getResultKind()) {
892   case LookupResult::NotFound:
893     // If an unqualified-id is followed by a '(', then we have a function
894     // call.
895     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896       // In C++, this is an ADL-only call.
897       // FIXME: Reference?
898       if (getLangOpts().CPlusPlus)
899         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900 
901       // C90 6.3.2.2:
902       //   If the expression that precedes the parenthesized argument list in a
903       //   function call consists solely of an identifier, and if no
904       //   declaration is visible for this identifier, the identifier is
905       //   implicitly declared exactly as if, in the innermost block containing
906       //   the function call, the declaration
907       //
908       //     extern int identifier ();
909       //
910       //   appeared.
911       //
912       // We also allow this in C99 as an extension.
913       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914         Result.addDecl(D);
915         Result.resolveKind();
916         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917       }
918     }
919 
920     // In C, we first see whether there is a tag type by the same name, in
921     // which case it's likely that the user just forgot to write "enum",
922     // "struct", or "union".
923     if (!getLangOpts().CPlusPlus && !SecondTry &&
924         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
925       break;
926     }
927 
928     // Perform typo correction to determine if there is another name that is
929     // close to this name.
930     if (!SecondTry && CCC) {
931       SecondTry = true;
932       if (TypoCorrection Corrected =
933               CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
934                           &SS, *CCC, CTK_ErrorRecovery)) {
935         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
936         unsigned QualifiedDiag = diag::err_no_member_suggest;
937 
938         NamedDecl *FirstDecl = Corrected.getFoundDecl();
939         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
940         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
941             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
942           UnqualifiedDiag = diag::err_no_template_suggest;
943           QualifiedDiag = diag::err_no_member_template_suggest;
944         } else if (UnderlyingFirstDecl &&
945                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
946                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
947                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
948           UnqualifiedDiag = diag::err_unknown_typename_suggest;
949           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
950         }
951 
952         if (SS.isEmpty()) {
953           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
954         } else {// FIXME: is this even reachable? Test it.
955           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
956           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
957                                   Name->getName().equals(CorrectedStr);
958           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
959                                     << Name << computeDeclContext(SS, false)
960                                     << DroppedSpecifier << SS.getRange());
961         }
962 
963         // Update the name, so that the caller has the new name.
964         Name = Corrected.getCorrectionAsIdentifierInfo();
965 
966         // Typo correction corrected to a keyword.
967         if (Corrected.isKeyword())
968           return Name;
969 
970         // Also update the LookupResult...
971         // FIXME: This should probably go away at some point
972         Result.clear();
973         Result.setLookupName(Corrected.getCorrection());
974         if (FirstDecl)
975           Result.addDecl(FirstDecl);
976 
977         // If we found an Objective-C instance variable, let
978         // LookupInObjCMethod build the appropriate expression to
979         // reference the ivar.
980         // FIXME: This is a gross hack.
981         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
982           Result.clear();
983           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
984           return E;
985         }
986 
987         goto Corrected;
988       }
989     }
990 
991     // We failed to correct; just fall through and let the parser deal with it.
992     Result.suppressDiagnostics();
993     return NameClassification::Unknown();
994 
995   case LookupResult::NotFoundInCurrentInstantiation: {
996     // We performed name lookup into the current instantiation, and there were
997     // dependent bases, so we treat this result the same way as any other
998     // dependent nested-name-specifier.
999 
1000     // C++ [temp.res]p2:
1001     //   A name used in a template declaration or definition and that is
1002     //   dependent on a template-parameter is assumed not to name a type
1003     //   unless the applicable name lookup finds a type name or the name is
1004     //   qualified by the keyword typename.
1005     //
1006     // FIXME: If the next token is '<', we might want to ask the parser to
1007     // perform some heroics to see if we actually have a
1008     // template-argument-list, which would indicate a missing 'template'
1009     // keyword here.
1010     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1011                                       NameInfo, IsAddressOfOperand,
1012                                       /*TemplateArgs=*/nullptr);
1013   }
1014 
1015   case LookupResult::Found:
1016   case LookupResult::FoundOverloaded:
1017   case LookupResult::FoundUnresolvedValue:
1018     break;
1019 
1020   case LookupResult::Ambiguous:
1021     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1022         hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1023                                       /*AllowDependent=*/false)) {
1024       // C++ [temp.local]p3:
1025       //   A lookup that finds an injected-class-name (10.2) can result in an
1026       //   ambiguity in certain cases (for example, if it is found in more than
1027       //   one base class). If all of the injected-class-names that are found
1028       //   refer to specializations of the same class template, and if the name
1029       //   is followed by a template-argument-list, the reference refers to the
1030       //   class template itself and not a specialization thereof, and is not
1031       //   ambiguous.
1032       //
1033       // This filtering can make an ambiguous result into an unambiguous one,
1034       // so try again after filtering out template names.
1035       FilterAcceptableTemplateNames(Result);
1036       if (!Result.isAmbiguous()) {
1037         IsFilteredTemplateName = true;
1038         break;
1039       }
1040     }
1041 
1042     // Diagnose the ambiguity and return an error.
1043     return NameClassification::Error();
1044   }
1045 
1046   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047       (IsFilteredTemplateName ||
1048        hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1049                                      /*AllowDependent=*/false))) {
1050     // C++ [temp.names]p3:
1051     //   After name lookup (3.4) finds that a name is a template-name or that
1052     //   an operator-function-id or a literal- operator-id refers to a set of
1053     //   overloaded functions any member of which is a function template if
1054     //   this is followed by a <, the < is always taken as the delimiter of a
1055     //   template-argument-list and never as the less-than operator.
1056     if (!IsFilteredTemplateName)
1057       FilterAcceptableTemplateNames(Result);
1058 
1059     if (!Result.empty()) {
1060       bool IsFunctionTemplate;
1061       bool IsVarTemplate;
1062       TemplateName Template;
1063       if (Result.end() - Result.begin() > 1) {
1064         IsFunctionTemplate = true;
1065         Template = Context.getOverloadedTemplateName(Result.begin(),
1066                                                      Result.end());
1067       } else {
1068         auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1069             *Result.begin(), /*AllowFunctionTemplates=*/true,
1070             /*AllowDependent=*/false));
1071         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1072         IsVarTemplate = isa<VarTemplateDecl>(TD);
1073 
1074         if (SS.isSet() && !SS.isInvalid())
1075           Template =
1076               Context.getQualifiedTemplateName(SS.getScopeRep(),
1077                                                /*TemplateKeyword=*/false, TD);
1078         else
1079           Template = TemplateName(TD);
1080       }
1081 
1082       if (IsFunctionTemplate) {
1083         // Function templates always go through overload resolution, at which
1084         // point we'll perform the various checks (e.g., accessibility) we need
1085         // to based on which function we selected.
1086         Result.suppressDiagnostics();
1087 
1088         return NameClassification::FunctionTemplate(Template);
1089       }
1090 
1091       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1092                            : NameClassification::TypeTemplate(Template);
1093     }
1094   }
1095 
1096   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1097   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1098     DiagnoseUseOfDecl(Type, NameLoc);
1099     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1100     QualType T = Context.getTypeDeclType(Type);
1101     if (SS.isNotEmpty())
1102       return buildNestedType(*this, SS, T, NameLoc);
1103     return ParsedType::make(T);
1104   }
1105 
1106   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1107   if (!Class) {
1108     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1109     if (ObjCCompatibleAliasDecl *Alias =
1110             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1111       Class = Alias->getClassInterface();
1112   }
1113 
1114   if (Class) {
1115     DiagnoseUseOfDecl(Class, NameLoc);
1116 
1117     if (NextToken.is(tok::period)) {
1118       // Interface. <something> is parsed as a property reference expression.
1119       // Just return "unknown" as a fall-through for now.
1120       Result.suppressDiagnostics();
1121       return NameClassification::Unknown();
1122     }
1123 
1124     QualType T = Context.getObjCInterfaceType(Class);
1125     return ParsedType::make(T);
1126   }
1127 
1128   // We can have a type template here if we're classifying a template argument.
1129   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1130       !isa<VarTemplateDecl>(FirstDecl))
1131     return NameClassification::TypeTemplate(
1132         TemplateName(cast<TemplateDecl>(FirstDecl)));
1133 
1134   // Check for a tag type hidden by a non-type decl in a few cases where it
1135   // seems likely a type is wanted instead of the non-type that was found.
1136   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1137   if ((NextToken.is(tok::identifier) ||
1138        (NextIsOp &&
1139         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1140       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1141     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1142     DiagnoseUseOfDecl(Type, NameLoc);
1143     QualType T = Context.getTypeDeclType(Type);
1144     if (SS.isNotEmpty())
1145       return buildNestedType(*this, SS, T, NameLoc);
1146     return ParsedType::make(T);
1147   }
1148 
1149   if (FirstDecl->isCXXClassMember())
1150     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1151                                            nullptr, S);
1152 
1153   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1154   return BuildDeclarationNameExpr(SS, Result, ADL);
1155 }
1156 
1157 Sema::TemplateNameKindForDiagnostics
1158 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1159   auto *TD = Name.getAsTemplateDecl();
1160   if (!TD)
1161     return TemplateNameKindForDiagnostics::DependentTemplate;
1162   if (isa<ClassTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::ClassTemplate;
1164   if (isa<FunctionTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::FunctionTemplate;
1166   if (isa<VarTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::VarTemplate;
1168   if (isa<TypeAliasTemplateDecl>(TD))
1169     return TemplateNameKindForDiagnostics::AliasTemplate;
1170   if (isa<TemplateTemplateParmDecl>(TD))
1171     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1172   return TemplateNameKindForDiagnostics::DependentTemplate;
1173 }
1174 
1175 // Determines the context to return to after temporarily entering a
1176 // context.  This depends in an unnecessarily complicated way on the
1177 // exact ordering of callbacks from the parser.
1178 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1179 
1180   // Functions defined inline within classes aren't parsed until we've
1181   // finished parsing the top-level class, so the top-level class is
1182   // the context we'll need to return to.
1183   // A Lambda call operator whose parent is a class must not be treated
1184   // as an inline member function.  A Lambda can be used legally
1185   // either as an in-class member initializer or a default argument.  These
1186   // are parsed once the class has been marked complete and so the containing
1187   // context would be the nested class (when the lambda is defined in one);
1188   // If the class is not complete, then the lambda is being used in an
1189   // ill-formed fashion (such as to specify the width of a bit-field, or
1190   // in an array-bound) - in which case we still want to return the
1191   // lexically containing DC (which could be a nested class).
1192   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1193     DC = DC->getLexicalParent();
1194 
1195     // A function not defined within a class will always return to its
1196     // lexical context.
1197     if (!isa<CXXRecordDecl>(DC))
1198       return DC;
1199 
1200     // A C++ inline method/friend is parsed *after* the topmost class
1201     // it was declared in is fully parsed ("complete");  the topmost
1202     // class is the context we need to return to.
1203     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1204       DC = RD;
1205 
1206     // Return the declaration context of the topmost class the inline method is
1207     // declared in.
1208     return DC;
1209   }
1210 
1211   return DC->getLexicalParent();
1212 }
1213 
1214 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1215   assert(getContainingDC(DC) == CurContext &&
1216       "The next DeclContext should be lexically contained in the current one.");
1217   CurContext = DC;
1218   S->setEntity(DC);
1219 }
1220 
1221 void Sema::PopDeclContext() {
1222   assert(CurContext && "DeclContext imbalance!");
1223 
1224   CurContext = getContainingDC(CurContext);
1225   assert(CurContext && "Popped translation unit!");
1226 }
1227 
1228 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1229                                                                     Decl *D) {
1230   // Unlike PushDeclContext, the context to which we return is not necessarily
1231   // the containing DC of TD, because the new context will be some pre-existing
1232   // TagDecl definition instead of a fresh one.
1233   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1234   CurContext = cast<TagDecl>(D)->getDefinition();
1235   assert(CurContext && "skipping definition of undefined tag");
1236   // Start lookups from the parent of the current context; we don't want to look
1237   // into the pre-existing complete definition.
1238   S->setEntity(CurContext->getLookupParent());
1239   return Result;
1240 }
1241 
1242 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1243   CurContext = static_cast<decltype(CurContext)>(Context);
1244 }
1245 
1246 /// EnterDeclaratorContext - Used when we must lookup names in the context
1247 /// of a declarator's nested name specifier.
1248 ///
1249 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1250   // C++0x [basic.lookup.unqual]p13:
1251   //   A name used in the definition of a static data member of class
1252   //   X (after the qualified-id of the static member) is looked up as
1253   //   if the name was used in a member function of X.
1254   // C++0x [basic.lookup.unqual]p14:
1255   //   If a variable member of a namespace is defined outside of the
1256   //   scope of its namespace then any name used in the definition of
1257   //   the variable member (after the declarator-id) is looked up as
1258   //   if the definition of the variable member occurred in its
1259   //   namespace.
1260   // Both of these imply that we should push a scope whose context
1261   // is the semantic context of the declaration.  We can't use
1262   // PushDeclContext here because that context is not necessarily
1263   // lexically contained in the current context.  Fortunately,
1264   // the containing scope should have the appropriate information.
1265 
1266   assert(!S->getEntity() && "scope already has entity");
1267 
1268 #ifndef NDEBUG
1269   Scope *Ancestor = S->getParent();
1270   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1271   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1272 #endif
1273 
1274   CurContext = DC;
1275   S->setEntity(DC);
1276 }
1277 
1278 void Sema::ExitDeclaratorContext(Scope *S) {
1279   assert(S->getEntity() == CurContext && "Context imbalance!");
1280 
1281   // Switch back to the lexical context.  The safety of this is
1282   // enforced by an assert in EnterDeclaratorContext.
1283   Scope *Ancestor = S->getParent();
1284   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1285   CurContext = Ancestor->getEntity();
1286 
1287   // We don't need to do anything with the scope, which is going to
1288   // disappear.
1289 }
1290 
1291 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1292   // We assume that the caller has already called
1293   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1294   FunctionDecl *FD = D->getAsFunction();
1295   if (!FD)
1296     return;
1297 
1298   // Same implementation as PushDeclContext, but enters the context
1299   // from the lexical parent, rather than the top-level class.
1300   assert(CurContext == FD->getLexicalParent() &&
1301     "The next DeclContext should be lexically contained in the current one.");
1302   CurContext = FD;
1303   S->setEntity(CurContext);
1304 
1305   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1306     ParmVarDecl *Param = FD->getParamDecl(P);
1307     // If the parameter has an identifier, then add it to the scope
1308     if (Param->getIdentifier()) {
1309       S->AddDecl(Param);
1310       IdResolver.AddDecl(Param);
1311     }
1312   }
1313 }
1314 
1315 void Sema::ActOnExitFunctionContext() {
1316   // Same implementation as PopDeclContext, but returns to the lexical parent,
1317   // rather than the top-level class.
1318   assert(CurContext && "DeclContext imbalance!");
1319   CurContext = CurContext->getLexicalParent();
1320   assert(CurContext && "Popped translation unit!");
1321 }
1322 
1323 /// Determine whether we allow overloading of the function
1324 /// PrevDecl with another declaration.
1325 ///
1326 /// This routine determines whether overloading is possible, not
1327 /// whether some new function is actually an overload. It will return
1328 /// true in C++ (where we can always provide overloads) or, as an
1329 /// extension, in C when the previous function is already an
1330 /// overloaded function declaration or has the "overloadable"
1331 /// attribute.
1332 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1333                                        ASTContext &Context,
1334                                        const FunctionDecl *New) {
1335   if (Context.getLangOpts().CPlusPlus)
1336     return true;
1337 
1338   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1339     return true;
1340 
1341   return Previous.getResultKind() == LookupResult::Found &&
1342          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1343           New->hasAttr<OverloadableAttr>());
1344 }
1345 
1346 /// Add this decl to the scope shadowed decl chains.
1347 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1348   // Move up the scope chain until we find the nearest enclosing
1349   // non-transparent context. The declaration will be introduced into this
1350   // scope.
1351   while (S->getEntity() && S->getEntity()->isTransparentContext())
1352     S = S->getParent();
1353 
1354   // Add scoped declarations into their context, so that they can be
1355   // found later. Declarations without a context won't be inserted
1356   // into any context.
1357   if (AddToContext)
1358     CurContext->addDecl(D);
1359 
1360   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1361   // are function-local declarations.
1362   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1363       !D->getDeclContext()->getRedeclContext()->Equals(
1364         D->getLexicalDeclContext()->getRedeclContext()) &&
1365       !D->getLexicalDeclContext()->isFunctionOrMethod())
1366     return;
1367 
1368   // Template instantiations should also not be pushed into scope.
1369   if (isa<FunctionDecl>(D) &&
1370       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1371     return;
1372 
1373   // If this replaces anything in the current scope,
1374   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1375                                IEnd = IdResolver.end();
1376   for (; I != IEnd; ++I) {
1377     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1378       S->RemoveDecl(*I);
1379       IdResolver.RemoveDecl(*I);
1380 
1381       // Should only need to replace one decl.
1382       break;
1383     }
1384   }
1385 
1386   S->AddDecl(D);
1387 
1388   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1389     // Implicitly-generated labels may end up getting generated in an order that
1390     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1391     // the label at the appropriate place in the identifier chain.
1392     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1393       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1394       if (IDC == CurContext) {
1395         if (!S->isDeclScope(*I))
1396           continue;
1397       } else if (IDC->Encloses(CurContext))
1398         break;
1399     }
1400 
1401     IdResolver.InsertDeclAfter(I, D);
1402   } else {
1403     IdResolver.AddDecl(D);
1404   }
1405 }
1406 
1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408                          bool AllowInlineNamespace) {
1409   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410 }
1411 
1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413   DeclContext *TargetDC = DC->getPrimaryContext();
1414   do {
1415     if (DeclContext *ScopeDC = S->getEntity())
1416       if (ScopeDC->getPrimaryContext() == TargetDC)
1417         return S;
1418   } while ((S = S->getParent()));
1419 
1420   return nullptr;
1421 }
1422 
1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424                                             DeclContext*,
1425                                             ASTContext&);
1426 
1427 /// Filters out lookup results that don't fall within the given scope
1428 /// as determined by isDeclInScope.
1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430                                 bool ConsiderLinkage,
1431                                 bool AllowInlineNamespace) {
1432   LookupResult::Filter F = R.makeFilter();
1433   while (F.hasNext()) {
1434     NamedDecl *D = F.next();
1435 
1436     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437       continue;
1438 
1439     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440       continue;
1441 
1442     F.erase();
1443   }
1444 
1445   F.done();
1446 }
1447 
1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1449 /// have compatible owning modules.
1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1451   // FIXME: The Modules TS is not clear about how friend declarations are
1452   // to be treated. It's not meaningful to have different owning modules for
1453   // linkage in redeclarations of the same entity, so for now allow the
1454   // redeclaration and change the owning modules to match.
1455   if (New->getFriendObjectKind() &&
1456       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1457     New->setLocalOwningModule(Old->getOwningModule());
1458     makeMergedDefinitionVisible(New);
1459     return false;
1460   }
1461 
1462   Module *NewM = New->getOwningModule();
1463   Module *OldM = Old->getOwningModule();
1464 
1465   if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1466     NewM = NewM->Parent;
1467   if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1468     OldM = OldM->Parent;
1469 
1470   if (NewM == OldM)
1471     return false;
1472 
1473   bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1474   bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1475   if (NewIsModuleInterface || OldIsModuleInterface) {
1476     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1477     //   if a declaration of D [...] appears in the purview of a module, all
1478     //   other such declarations shall appear in the purview of the same module
1479     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1480       << New
1481       << NewIsModuleInterface
1482       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1483       << OldIsModuleInterface
1484       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1485     Diag(Old->getLocation(), diag::note_previous_declaration);
1486     New->setInvalidDecl();
1487     return true;
1488   }
1489 
1490   return false;
1491 }
1492 
1493 static bool isUsingDecl(NamedDecl *D) {
1494   return isa<UsingShadowDecl>(D) ||
1495          isa<UnresolvedUsingTypenameDecl>(D) ||
1496          isa<UnresolvedUsingValueDecl>(D);
1497 }
1498 
1499 /// Removes using shadow declarations from the lookup results.
1500 static void RemoveUsingDecls(LookupResult &R) {
1501   LookupResult::Filter F = R.makeFilter();
1502   while (F.hasNext())
1503     if (isUsingDecl(F.next()))
1504       F.erase();
1505 
1506   F.done();
1507 }
1508 
1509 /// Check for this common pattern:
1510 /// @code
1511 /// class S {
1512 ///   S(const S&); // DO NOT IMPLEMENT
1513 ///   void operator=(const S&); // DO NOT IMPLEMENT
1514 /// };
1515 /// @endcode
1516 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1517   // FIXME: Should check for private access too but access is set after we get
1518   // the decl here.
1519   if (D->doesThisDeclarationHaveABody())
1520     return false;
1521 
1522   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1523     return CD->isCopyConstructor();
1524   return D->isCopyAssignmentOperator();
1525 }
1526 
1527 // We need this to handle
1528 //
1529 // typedef struct {
1530 //   void *foo() { return 0; }
1531 // } A;
1532 //
1533 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1534 // for example. If 'A', foo will have external linkage. If we have '*A',
1535 // foo will have no linkage. Since we can't know until we get to the end
1536 // of the typedef, this function finds out if D might have non-external linkage.
1537 // Callers should verify at the end of the TU if it D has external linkage or
1538 // not.
1539 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1540   const DeclContext *DC = D->getDeclContext();
1541   while (!DC->isTranslationUnit()) {
1542     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1543       if (!RD->hasNameForLinkage())
1544         return true;
1545     }
1546     DC = DC->getParent();
1547   }
1548 
1549   return !D->isExternallyVisible();
1550 }
1551 
1552 // FIXME: This needs to be refactored; some other isInMainFile users want
1553 // these semantics.
1554 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1555   if (S.TUKind != TU_Complete)
1556     return false;
1557   return S.SourceMgr.isInMainFile(Loc);
1558 }
1559 
1560 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1561   assert(D);
1562 
1563   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1564     return false;
1565 
1566   // Ignore all entities declared within templates, and out-of-line definitions
1567   // of members of class templates.
1568   if (D->getDeclContext()->isDependentContext() ||
1569       D->getLexicalDeclContext()->isDependentContext())
1570     return false;
1571 
1572   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1573     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1574       return false;
1575     // A non-out-of-line declaration of a member specialization was implicitly
1576     // instantiated; it's the out-of-line declaration that we're interested in.
1577     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1578         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1579       return false;
1580 
1581     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1582       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1583         return false;
1584     } else {
1585       // 'static inline' functions are defined in headers; don't warn.
1586       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1587         return false;
1588     }
1589 
1590     if (FD->doesThisDeclarationHaveABody() &&
1591         Context.DeclMustBeEmitted(FD))
1592       return false;
1593   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594     // Constants and utility variables are defined in headers with internal
1595     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1596     // like "inline".)
1597     if (!isMainFileLoc(*this, VD->getLocation()))
1598       return false;
1599 
1600     if (Context.DeclMustBeEmitted(VD))
1601       return false;
1602 
1603     if (VD->isStaticDataMember() &&
1604         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1605       return false;
1606     if (VD->isStaticDataMember() &&
1607         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1608         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1609       return false;
1610 
1611     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1612       return false;
1613   } else {
1614     return false;
1615   }
1616 
1617   // Only warn for unused decls internal to the translation unit.
1618   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1619   // for inline functions defined in the main source file, for instance.
1620   return mightHaveNonExternalLinkage(D);
1621 }
1622 
1623 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1624   if (!D)
1625     return;
1626 
1627   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1628     const FunctionDecl *First = FD->getFirstDecl();
1629     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1630       return; // First should already be in the vector.
1631   }
1632 
1633   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1634     const VarDecl *First = VD->getFirstDecl();
1635     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1636       return; // First should already be in the vector.
1637   }
1638 
1639   if (ShouldWarnIfUnusedFileScopedDecl(D))
1640     UnusedFileScopedDecls.push_back(D);
1641 }
1642 
1643 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1644   if (D->isInvalidDecl())
1645     return false;
1646 
1647   bool Referenced = false;
1648   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1649     // For a decomposition declaration, warn if none of the bindings are
1650     // referenced, instead of if the variable itself is referenced (which
1651     // it is, by the bindings' expressions).
1652     for (auto *BD : DD->bindings()) {
1653       if (BD->isReferenced()) {
1654         Referenced = true;
1655         break;
1656       }
1657     }
1658   } else if (!D->getDeclName()) {
1659     return false;
1660   } else if (D->isReferenced() || D->isUsed()) {
1661     Referenced = true;
1662   }
1663 
1664   if (Referenced || D->hasAttr<UnusedAttr>() ||
1665       D->hasAttr<ObjCPreciseLifetimeAttr>())
1666     return false;
1667 
1668   if (isa<LabelDecl>(D))
1669     return true;
1670 
1671   // Except for labels, we only care about unused decls that are local to
1672   // functions.
1673   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1674   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1675     // For dependent types, the diagnostic is deferred.
1676     WithinFunction =
1677         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1678   if (!WithinFunction)
1679     return false;
1680 
1681   if (isa<TypedefNameDecl>(D))
1682     return true;
1683 
1684   // White-list anything that isn't a local variable.
1685   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1686     return false;
1687 
1688   // Types of valid local variables should be complete, so this should succeed.
1689   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1690 
1691     // White-list anything with an __attribute__((unused)) type.
1692     const auto *Ty = VD->getType().getTypePtr();
1693 
1694     // Only look at the outermost level of typedef.
1695     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1696       if (TT->getDecl()->hasAttr<UnusedAttr>())
1697         return false;
1698     }
1699 
1700     // If we failed to complete the type for some reason, or if the type is
1701     // dependent, don't diagnose the variable.
1702     if (Ty->isIncompleteType() || Ty->isDependentType())
1703       return false;
1704 
1705     // Look at the element type to ensure that the warning behaviour is
1706     // consistent for both scalars and arrays.
1707     Ty = Ty->getBaseElementTypeUnsafe();
1708 
1709     if (const TagType *TT = Ty->getAs<TagType>()) {
1710       const TagDecl *Tag = TT->getDecl();
1711       if (Tag->hasAttr<UnusedAttr>())
1712         return false;
1713 
1714       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1715         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1716           return false;
1717 
1718         if (const Expr *Init = VD->getInit()) {
1719           if (const ExprWithCleanups *Cleanups =
1720                   dyn_cast<ExprWithCleanups>(Init))
1721             Init = Cleanups->getSubExpr();
1722           const CXXConstructExpr *Construct =
1723             dyn_cast<CXXConstructExpr>(Init);
1724           if (Construct && !Construct->isElidable()) {
1725             CXXConstructorDecl *CD = Construct->getConstructor();
1726             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1727                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1728               return false;
1729           }
1730         }
1731       }
1732     }
1733 
1734     // TODO: __attribute__((unused)) templates?
1735   }
1736 
1737   return true;
1738 }
1739 
1740 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1741                                      FixItHint &Hint) {
1742   if (isa<LabelDecl>(D)) {
1743     SourceLocation AfterColon = Lexer::findLocationAfterToken(
1744         D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1745         true);
1746     if (AfterColon.isInvalid())
1747       return;
1748     Hint = FixItHint::CreateRemoval(
1749         CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1750   }
1751 }
1752 
1753 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1754   if (D->getTypeForDecl()->isDependentType())
1755     return;
1756 
1757   for (auto *TmpD : D->decls()) {
1758     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1759       DiagnoseUnusedDecl(T);
1760     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1761       DiagnoseUnusedNestedTypedefs(R);
1762   }
1763 }
1764 
1765 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1766 /// unless they are marked attr(unused).
1767 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1768   if (!ShouldDiagnoseUnusedDecl(D))
1769     return;
1770 
1771   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1772     // typedefs can be referenced later on, so the diagnostics are emitted
1773     // at end-of-translation-unit.
1774     UnusedLocalTypedefNameCandidates.insert(TD);
1775     return;
1776   }
1777 
1778   FixItHint Hint;
1779   GenerateFixForUnusedDecl(D, Context, Hint);
1780 
1781   unsigned DiagID;
1782   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1783     DiagID = diag::warn_unused_exception_param;
1784   else if (isa<LabelDecl>(D))
1785     DiagID = diag::warn_unused_label;
1786   else
1787     DiagID = diag::warn_unused_variable;
1788 
1789   Diag(D->getLocation(), DiagID) << D << Hint;
1790 }
1791 
1792 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1793   // Verify that we have no forward references left.  If so, there was a goto
1794   // or address of a label taken, but no definition of it.  Label fwd
1795   // definitions are indicated with a null substmt which is also not a resolved
1796   // MS inline assembly label name.
1797   bool Diagnose = false;
1798   if (L->isMSAsmLabel())
1799     Diagnose = !L->isResolvedMSAsmLabel();
1800   else
1801     Diagnose = L->getStmt() == nullptr;
1802   if (Diagnose)
1803     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1804 }
1805 
1806 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1807   S->mergeNRVOIntoParent();
1808 
1809   if (S->decl_empty()) return;
1810   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1811          "Scope shouldn't contain decls!");
1812 
1813   for (auto *TmpD : S->decls()) {
1814     assert(TmpD && "This decl didn't get pushed??");
1815 
1816     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1817     NamedDecl *D = cast<NamedDecl>(TmpD);
1818 
1819     // Diagnose unused variables in this scope.
1820     if (!S->hasUnrecoverableErrorOccurred()) {
1821       DiagnoseUnusedDecl(D);
1822       if (const auto *RD = dyn_cast<RecordDecl>(D))
1823         DiagnoseUnusedNestedTypedefs(RD);
1824     }
1825 
1826     if (!D->getDeclName()) continue;
1827 
1828     // If this was a forward reference to a label, verify it was defined.
1829     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1830       CheckPoppedLabel(LD, *this);
1831 
1832     // Remove this name from our lexical scope, and warn on it if we haven't
1833     // already.
1834     IdResolver.RemoveDecl(D);
1835     auto ShadowI = ShadowingDecls.find(D);
1836     if (ShadowI != ShadowingDecls.end()) {
1837       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1838         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1839             << D << FD << FD->getParent();
1840         Diag(FD->getLocation(), diag::note_previous_declaration);
1841       }
1842       ShadowingDecls.erase(ShadowI);
1843     }
1844   }
1845 }
1846 
1847 /// Look for an Objective-C class in the translation unit.
1848 ///
1849 /// \param Id The name of the Objective-C class we're looking for. If
1850 /// typo-correction fixes this name, the Id will be updated
1851 /// to the fixed name.
1852 ///
1853 /// \param IdLoc The location of the name in the translation unit.
1854 ///
1855 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1856 /// if there is no class with the given name.
1857 ///
1858 /// \returns The declaration of the named Objective-C class, or NULL if the
1859 /// class could not be found.
1860 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1861                                               SourceLocation IdLoc,
1862                                               bool DoTypoCorrection) {
1863   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1864   // creation from this context.
1865   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1866 
1867   if (!IDecl && DoTypoCorrection) {
1868     // Perform typo correction at the given location, but only if we
1869     // find an Objective-C class name.
1870     DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1871     if (TypoCorrection C =
1872             CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1873                         TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1874       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1875       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1876       Id = IDecl->getIdentifier();
1877     }
1878   }
1879   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1880   // This routine must always return a class definition, if any.
1881   if (Def && Def->getDefinition())
1882       Def = Def->getDefinition();
1883   return Def;
1884 }
1885 
1886 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1887 /// from S, where a non-field would be declared. This routine copes
1888 /// with the difference between C and C++ scoping rules in structs and
1889 /// unions. For example, the following code is well-formed in C but
1890 /// ill-formed in C++:
1891 /// @code
1892 /// struct S6 {
1893 ///   enum { BAR } e;
1894 /// };
1895 ///
1896 /// void test_S6() {
1897 ///   struct S6 a;
1898 ///   a.e = BAR;
1899 /// }
1900 /// @endcode
1901 /// For the declaration of BAR, this routine will return a different
1902 /// scope. The scope S will be the scope of the unnamed enumeration
1903 /// within S6. In C++, this routine will return the scope associated
1904 /// with S6, because the enumeration's scope is a transparent
1905 /// context but structures can contain non-field names. In C, this
1906 /// routine will return the translation unit scope, since the
1907 /// enumeration's scope is a transparent context and structures cannot
1908 /// contain non-field names.
1909 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1910   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1911          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1912          (S->isClassScope() && !getLangOpts().CPlusPlus))
1913     S = S->getParent();
1914   return S;
1915 }
1916 
1917 /// Looks up the declaration of "struct objc_super" and
1918 /// saves it for later use in building builtin declaration of
1919 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1920 /// pre-existing declaration exists no action takes place.
1921 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1922                                         IdentifierInfo *II) {
1923   if (!II->isStr("objc_msgSendSuper"))
1924     return;
1925   ASTContext &Context = ThisSema.Context;
1926 
1927   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1928                       SourceLocation(), Sema::LookupTagName);
1929   ThisSema.LookupName(Result, S);
1930   if (Result.getResultKind() == LookupResult::Found)
1931     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1932       Context.setObjCSuperType(Context.getTagDeclType(TD));
1933 }
1934 
1935 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
1936                                ASTContext::GetBuiltinTypeError Error) {
1937   switch (Error) {
1938   case ASTContext::GE_None:
1939     return "";
1940   case ASTContext::GE_Missing_type:
1941     return BuiltinInfo.getHeaderName(ID);
1942   case ASTContext::GE_Missing_stdio:
1943     return "stdio.h";
1944   case ASTContext::GE_Missing_setjmp:
1945     return "setjmp.h";
1946   case ASTContext::GE_Missing_ucontext:
1947     return "ucontext.h";
1948   }
1949   llvm_unreachable("unhandled error kind");
1950 }
1951 
1952 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1953 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1954 /// if we're creating this built-in in anticipation of redeclaring the
1955 /// built-in.
1956 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1957                                      Scope *S, bool ForRedeclaration,
1958                                      SourceLocation Loc) {
1959   LookupPredefedObjCSuperType(*this, S, II);
1960 
1961   ASTContext::GetBuiltinTypeError Error;
1962   QualType R = Context.GetBuiltinType(ID, Error);
1963   if (Error) {
1964     if (ForRedeclaration)
1965       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1966           << getHeaderName(Context.BuiltinInfo, ID, Error)
1967           << Context.BuiltinInfo.getName(ID);
1968     return nullptr;
1969   }
1970 
1971   if (!ForRedeclaration &&
1972       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1973        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1974     Diag(Loc, diag::ext_implicit_lib_function_decl)
1975         << Context.BuiltinInfo.getName(ID) << R;
1976     if (Context.BuiltinInfo.getHeaderName(ID) &&
1977         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1978       Diag(Loc, diag::note_include_header_or_declare)
1979           << Context.BuiltinInfo.getHeaderName(ID)
1980           << Context.BuiltinInfo.getName(ID);
1981   }
1982 
1983   if (R.isNull())
1984     return nullptr;
1985 
1986   DeclContext *Parent = Context.getTranslationUnitDecl();
1987   if (getLangOpts().CPlusPlus) {
1988     LinkageSpecDecl *CLinkageDecl =
1989         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1990                                 LinkageSpecDecl::lang_c, false);
1991     CLinkageDecl->setImplicit();
1992     Parent->addDecl(CLinkageDecl);
1993     Parent = CLinkageDecl;
1994   }
1995 
1996   FunctionDecl *New = FunctionDecl::Create(Context,
1997                                            Parent,
1998                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1999                                            SC_Extern,
2000                                            false,
2001                                            R->isFunctionProtoType());
2002   New->setImplicit();
2003 
2004   // Create Decl objects for each parameter, adding them to the
2005   // FunctionDecl.
2006   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2007     SmallVector<ParmVarDecl*, 16> Params;
2008     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2009       ParmVarDecl *parm =
2010           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2011                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2012                               SC_None, nullptr);
2013       parm->setScopeInfo(0, i);
2014       Params.push_back(parm);
2015     }
2016     New->setParams(Params);
2017   }
2018 
2019   AddKnownFunctionAttributes(New);
2020   RegisterLocallyScopedExternCDecl(New, S);
2021 
2022   // TUScope is the translation-unit scope to insert this function into.
2023   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2024   // relate Scopes to DeclContexts, and probably eliminate CurContext
2025   // entirely, but we're not there yet.
2026   DeclContext *SavedContext = CurContext;
2027   CurContext = Parent;
2028   PushOnScopeChains(New, TUScope);
2029   CurContext = SavedContext;
2030   return New;
2031 }
2032 
2033 /// Typedef declarations don't have linkage, but they still denote the same
2034 /// entity if their types are the same.
2035 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2036 /// isSameEntity.
2037 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2038                                                      TypedefNameDecl *Decl,
2039                                                      LookupResult &Previous) {
2040   // This is only interesting when modules are enabled.
2041   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2042     return;
2043 
2044   // Empty sets are uninteresting.
2045   if (Previous.empty())
2046     return;
2047 
2048   LookupResult::Filter Filter = Previous.makeFilter();
2049   while (Filter.hasNext()) {
2050     NamedDecl *Old = Filter.next();
2051 
2052     // Non-hidden declarations are never ignored.
2053     if (S.isVisible(Old))
2054       continue;
2055 
2056     // Declarations of the same entity are not ignored, even if they have
2057     // different linkages.
2058     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2059       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2060                                 Decl->getUnderlyingType()))
2061         continue;
2062 
2063       // If both declarations give a tag declaration a typedef name for linkage
2064       // purposes, then they declare the same entity.
2065       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2066           Decl->getAnonDeclWithTypedefName())
2067         continue;
2068     }
2069 
2070     Filter.erase();
2071   }
2072 
2073   Filter.done();
2074 }
2075 
2076 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2077   QualType OldType;
2078   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2079     OldType = OldTypedef->getUnderlyingType();
2080   else
2081     OldType = Context.getTypeDeclType(Old);
2082   QualType NewType = New->getUnderlyingType();
2083 
2084   if (NewType->isVariablyModifiedType()) {
2085     // Must not redefine a typedef with a variably-modified type.
2086     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2087     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2088       << Kind << NewType;
2089     if (Old->getLocation().isValid())
2090       notePreviousDefinition(Old, New->getLocation());
2091     New->setInvalidDecl();
2092     return true;
2093   }
2094 
2095   if (OldType != NewType &&
2096       !OldType->isDependentType() &&
2097       !NewType->isDependentType() &&
2098       !Context.hasSameType(OldType, NewType)) {
2099     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2100     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2101       << Kind << NewType << OldType;
2102     if (Old->getLocation().isValid())
2103       notePreviousDefinition(Old, New->getLocation());
2104     New->setInvalidDecl();
2105     return true;
2106   }
2107   return false;
2108 }
2109 
2110 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2111 /// same name and scope as a previous declaration 'Old'.  Figure out
2112 /// how to resolve this situation, merging decls or emitting
2113 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2114 ///
2115 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2116                                 LookupResult &OldDecls) {
2117   // If the new decl is known invalid already, don't bother doing any
2118   // merging checks.
2119   if (New->isInvalidDecl()) return;
2120 
2121   // Allow multiple definitions for ObjC built-in typedefs.
2122   // FIXME: Verify the underlying types are equivalent!
2123   if (getLangOpts().ObjC) {
2124     const IdentifierInfo *TypeID = New->getIdentifier();
2125     switch (TypeID->getLength()) {
2126     default: break;
2127     case 2:
2128       {
2129         if (!TypeID->isStr("id"))
2130           break;
2131         QualType T = New->getUnderlyingType();
2132         if (!T->isPointerType())
2133           break;
2134         if (!T->isVoidPointerType()) {
2135           QualType PT = T->getAs<PointerType>()->getPointeeType();
2136           if (!PT->isStructureType())
2137             break;
2138         }
2139         Context.setObjCIdRedefinitionType(T);
2140         // Install the built-in type for 'id', ignoring the current definition.
2141         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2142         return;
2143       }
2144     case 5:
2145       if (!TypeID->isStr("Class"))
2146         break;
2147       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2148       // Install the built-in type for 'Class', ignoring the current definition.
2149       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2150       return;
2151     case 3:
2152       if (!TypeID->isStr("SEL"))
2153         break;
2154       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2155       // Install the built-in type for 'SEL', ignoring the current definition.
2156       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2157       return;
2158     }
2159     // Fall through - the typedef name was not a builtin type.
2160   }
2161 
2162   // Verify the old decl was also a type.
2163   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2164   if (!Old) {
2165     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2166       << New->getDeclName();
2167 
2168     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2169     if (OldD->getLocation().isValid())
2170       notePreviousDefinition(OldD, New->getLocation());
2171 
2172     return New->setInvalidDecl();
2173   }
2174 
2175   // If the old declaration is invalid, just give up here.
2176   if (Old->isInvalidDecl())
2177     return New->setInvalidDecl();
2178 
2179   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2180     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2181     auto *NewTag = New->getAnonDeclWithTypedefName();
2182     NamedDecl *Hidden = nullptr;
2183     if (OldTag && NewTag &&
2184         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2185         !hasVisibleDefinition(OldTag, &Hidden)) {
2186       // There is a definition of this tag, but it is not visible. Use it
2187       // instead of our tag.
2188       New->setTypeForDecl(OldTD->getTypeForDecl());
2189       if (OldTD->isModed())
2190         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2191                                     OldTD->getUnderlyingType());
2192       else
2193         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2194 
2195       // Make the old tag definition visible.
2196       makeMergedDefinitionVisible(Hidden);
2197 
2198       // If this was an unscoped enumeration, yank all of its enumerators
2199       // out of the scope.
2200       if (isa<EnumDecl>(NewTag)) {
2201         Scope *EnumScope = getNonFieldDeclScope(S);
2202         for (auto *D : NewTag->decls()) {
2203           auto *ED = cast<EnumConstantDecl>(D);
2204           assert(EnumScope->isDeclScope(ED));
2205           EnumScope->RemoveDecl(ED);
2206           IdResolver.RemoveDecl(ED);
2207           ED->getLexicalDeclContext()->removeDecl(ED);
2208         }
2209       }
2210     }
2211   }
2212 
2213   // If the typedef types are not identical, reject them in all languages and
2214   // with any extensions enabled.
2215   if (isIncompatibleTypedef(Old, New))
2216     return;
2217 
2218   // The types match.  Link up the redeclaration chain and merge attributes if
2219   // the old declaration was a typedef.
2220   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2221     New->setPreviousDecl(Typedef);
2222     mergeDeclAttributes(New, Old);
2223   }
2224 
2225   if (getLangOpts().MicrosoftExt)
2226     return;
2227 
2228   if (getLangOpts().CPlusPlus) {
2229     // C++ [dcl.typedef]p2:
2230     //   In a given non-class scope, a typedef specifier can be used to
2231     //   redefine the name of any type declared in that scope to refer
2232     //   to the type to which it already refers.
2233     if (!isa<CXXRecordDecl>(CurContext))
2234       return;
2235 
2236     // C++0x [dcl.typedef]p4:
2237     //   In a given class scope, a typedef specifier can be used to redefine
2238     //   any class-name declared in that scope that is not also a typedef-name
2239     //   to refer to the type to which it already refers.
2240     //
2241     // This wording came in via DR424, which was a correction to the
2242     // wording in DR56, which accidentally banned code like:
2243     //
2244     //   struct S {
2245     //     typedef struct A { } A;
2246     //   };
2247     //
2248     // in the C++03 standard. We implement the C++0x semantics, which
2249     // allow the above but disallow
2250     //
2251     //   struct S {
2252     //     typedef int I;
2253     //     typedef int I;
2254     //   };
2255     //
2256     // since that was the intent of DR56.
2257     if (!isa<TypedefNameDecl>(Old))
2258       return;
2259 
2260     Diag(New->getLocation(), diag::err_redefinition)
2261       << New->getDeclName();
2262     notePreviousDefinition(Old, New->getLocation());
2263     return New->setInvalidDecl();
2264   }
2265 
2266   // Modules always permit redefinition of typedefs, as does C11.
2267   if (getLangOpts().Modules || getLangOpts().C11)
2268     return;
2269 
2270   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2271   // is normally mapped to an error, but can be controlled with
2272   // -Wtypedef-redefinition.  If either the original or the redefinition is
2273   // in a system header, don't emit this for compatibility with GCC.
2274   if (getDiagnostics().getSuppressSystemWarnings() &&
2275       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2276       (Old->isImplicit() ||
2277        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2278        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2279     return;
2280 
2281   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2282     << New->getDeclName();
2283   notePreviousDefinition(Old, New->getLocation());
2284 }
2285 
2286 /// DeclhasAttr - returns true if decl Declaration already has the target
2287 /// attribute.
2288 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2289   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2290   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2291   for (const auto *i : D->attrs())
2292     if (i->getKind() == A->getKind()) {
2293       if (Ann) {
2294         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2295           return true;
2296         continue;
2297       }
2298       // FIXME: Don't hardcode this check
2299       if (OA && isa<OwnershipAttr>(i))
2300         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2301       return true;
2302     }
2303 
2304   return false;
2305 }
2306 
2307 static bool isAttributeTargetADefinition(Decl *D) {
2308   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2309     return VD->isThisDeclarationADefinition();
2310   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2311     return TD->isCompleteDefinition() || TD->isBeingDefined();
2312   return true;
2313 }
2314 
2315 /// Merge alignment attributes from \p Old to \p New, taking into account the
2316 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2317 ///
2318 /// \return \c true if any attributes were added to \p New.
2319 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2320   // Look for alignas attributes on Old, and pick out whichever attribute
2321   // specifies the strictest alignment requirement.
2322   AlignedAttr *OldAlignasAttr = nullptr;
2323   AlignedAttr *OldStrictestAlignAttr = nullptr;
2324   unsigned OldAlign = 0;
2325   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2326     // FIXME: We have no way of representing inherited dependent alignments
2327     // in a case like:
2328     //   template<int A, int B> struct alignas(A) X;
2329     //   template<int A, int B> struct alignas(B) X {};
2330     // For now, we just ignore any alignas attributes which are not on the
2331     // definition in such a case.
2332     if (I->isAlignmentDependent())
2333       return false;
2334 
2335     if (I->isAlignas())
2336       OldAlignasAttr = I;
2337 
2338     unsigned Align = I->getAlignment(S.Context);
2339     if (Align > OldAlign) {
2340       OldAlign = Align;
2341       OldStrictestAlignAttr = I;
2342     }
2343   }
2344 
2345   // Look for alignas attributes on New.
2346   AlignedAttr *NewAlignasAttr = nullptr;
2347   unsigned NewAlign = 0;
2348   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2349     if (I->isAlignmentDependent())
2350       return false;
2351 
2352     if (I->isAlignas())
2353       NewAlignasAttr = I;
2354 
2355     unsigned Align = I->getAlignment(S.Context);
2356     if (Align > NewAlign)
2357       NewAlign = Align;
2358   }
2359 
2360   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2361     // Both declarations have 'alignas' attributes. We require them to match.
2362     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2363     // fall short. (If two declarations both have alignas, they must both match
2364     // every definition, and so must match each other if there is a definition.)
2365 
2366     // If either declaration only contains 'alignas(0)' specifiers, then it
2367     // specifies the natural alignment for the type.
2368     if (OldAlign == 0 || NewAlign == 0) {
2369       QualType Ty;
2370       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2371         Ty = VD->getType();
2372       else
2373         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2374 
2375       if (OldAlign == 0)
2376         OldAlign = S.Context.getTypeAlign(Ty);
2377       if (NewAlign == 0)
2378         NewAlign = S.Context.getTypeAlign(Ty);
2379     }
2380 
2381     if (OldAlign != NewAlign) {
2382       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2383         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2384         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2385       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2386     }
2387   }
2388 
2389   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2390     // C++11 [dcl.align]p6:
2391     //   if any declaration of an entity has an alignment-specifier,
2392     //   every defining declaration of that entity shall specify an
2393     //   equivalent alignment.
2394     // C11 6.7.5/7:
2395     //   If the definition of an object does not have an alignment
2396     //   specifier, any other declaration of that object shall also
2397     //   have no alignment specifier.
2398     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2399       << OldAlignasAttr;
2400     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2401       << OldAlignasAttr;
2402   }
2403 
2404   bool AnyAdded = false;
2405 
2406   // Ensure we have an attribute representing the strictest alignment.
2407   if (OldAlign > NewAlign) {
2408     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2409     Clone->setInherited(true);
2410     New->addAttr(Clone);
2411     AnyAdded = true;
2412   }
2413 
2414   // Ensure we have an alignas attribute if the old declaration had one.
2415   if (OldAlignasAttr && !NewAlignasAttr &&
2416       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2417     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2418     Clone->setInherited(true);
2419     New->addAttr(Clone);
2420     AnyAdded = true;
2421   }
2422 
2423   return AnyAdded;
2424 }
2425 
2426 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2427                                const InheritableAttr *Attr,
2428                                Sema::AvailabilityMergeKind AMK) {
2429   // This function copies an attribute Attr from a previous declaration to the
2430   // new declaration D if the new declaration doesn't itself have that attribute
2431   // yet or if that attribute allows duplicates.
2432   // If you're adding a new attribute that requires logic different from
2433   // "use explicit attribute on decl if present, else use attribute from
2434   // previous decl", for example if the attribute needs to be consistent
2435   // between redeclarations, you need to call a custom merge function here.
2436   InheritableAttr *NewAttr = nullptr;
2437   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2438   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2439     NewAttr = S.mergeAvailabilityAttr(
2440         D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2441         AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2442         AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2443         AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2444   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2445     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2446                                     AttrSpellingListIndex);
2447   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2448     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2449                                         AttrSpellingListIndex);
2450   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2451     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2452                                    AttrSpellingListIndex);
2453   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2454     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2455                                    AttrSpellingListIndex);
2456   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2457     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2458                                 FA->getFormatIdx(), FA->getFirstArg(),
2459                                 AttrSpellingListIndex);
2460   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2461     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2462                                  AttrSpellingListIndex);
2463   else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2464     NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2465                                  AttrSpellingListIndex);
2466   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2467     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2468                                        AttrSpellingListIndex,
2469                                        IA->getSemanticSpelling());
2470   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2471     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2472                                       &S.Context.Idents.get(AA->getSpelling()),
2473                                       AttrSpellingListIndex);
2474   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2475            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2476             isa<CUDAGlobalAttr>(Attr))) {
2477     // CUDA target attributes are part of function signature for
2478     // overloading purposes and must not be merged.
2479     return false;
2480   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2481     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2482   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2483     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2484   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2485     NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2486   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2487     NewAttr = S.mergeCommonAttr(D, *CommonA);
2488   else if (isa<AlignedAttr>(Attr))
2489     // AlignedAttrs are handled separately, because we need to handle all
2490     // such attributes on a declaration at the same time.
2491     NewAttr = nullptr;
2492   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2493            (AMK == Sema::AMK_Override ||
2494             AMK == Sema::AMK_ProtocolImplementation))
2495     NewAttr = nullptr;
2496   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2497     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2498                               UA->getGuid());
2499   else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2500     NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2501   else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2502     NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2503   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2504     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2505 
2506   if (NewAttr) {
2507     NewAttr->setInherited(true);
2508     D->addAttr(NewAttr);
2509     if (isa<MSInheritanceAttr>(NewAttr))
2510       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2511     return true;
2512   }
2513 
2514   return false;
2515 }
2516 
2517 static const NamedDecl *getDefinition(const Decl *D) {
2518   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2519     return TD->getDefinition();
2520   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2521     const VarDecl *Def = VD->getDefinition();
2522     if (Def)
2523       return Def;
2524     return VD->getActingDefinition();
2525   }
2526   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2527     return FD->getDefinition();
2528   return nullptr;
2529 }
2530 
2531 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2532   for (const auto *Attribute : D->attrs())
2533     if (Attribute->getKind() == Kind)
2534       return true;
2535   return false;
2536 }
2537 
2538 /// checkNewAttributesAfterDef - If we already have a definition, check that
2539 /// there are no new attributes in this declaration.
2540 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2541   if (!New->hasAttrs())
2542     return;
2543 
2544   const NamedDecl *Def = getDefinition(Old);
2545   if (!Def || Def == New)
2546     return;
2547 
2548   AttrVec &NewAttributes = New->getAttrs();
2549   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2550     const Attr *NewAttribute = NewAttributes[I];
2551 
2552     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2553       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2554         Sema::SkipBodyInfo SkipBody;
2555         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2556 
2557         // If we're skipping this definition, drop the "alias" attribute.
2558         if (SkipBody.ShouldSkip) {
2559           NewAttributes.erase(NewAttributes.begin() + I);
2560           --E;
2561           continue;
2562         }
2563       } else {
2564         VarDecl *VD = cast<VarDecl>(New);
2565         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2566                                 VarDecl::TentativeDefinition
2567                             ? diag::err_alias_after_tentative
2568                             : diag::err_redefinition;
2569         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2570         if (Diag == diag::err_redefinition)
2571           S.notePreviousDefinition(Def, VD->getLocation());
2572         else
2573           S.Diag(Def->getLocation(), diag::note_previous_definition);
2574         VD->setInvalidDecl();
2575       }
2576       ++I;
2577       continue;
2578     }
2579 
2580     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2581       // Tentative definitions are only interesting for the alias check above.
2582       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2583         ++I;
2584         continue;
2585       }
2586     }
2587 
2588     if (hasAttribute(Def, NewAttribute->getKind())) {
2589       ++I;
2590       continue; // regular attr merging will take care of validating this.
2591     }
2592 
2593     if (isa<C11NoReturnAttr>(NewAttribute)) {
2594       // C's _Noreturn is allowed to be added to a function after it is defined.
2595       ++I;
2596       continue;
2597     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2598       if (AA->isAlignas()) {
2599         // C++11 [dcl.align]p6:
2600         //   if any declaration of an entity has an alignment-specifier,
2601         //   every defining declaration of that entity shall specify an
2602         //   equivalent alignment.
2603         // C11 6.7.5/7:
2604         //   If the definition of an object does not have an alignment
2605         //   specifier, any other declaration of that object shall also
2606         //   have no alignment specifier.
2607         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2608           << AA;
2609         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2610           << AA;
2611         NewAttributes.erase(NewAttributes.begin() + I);
2612         --E;
2613         continue;
2614       }
2615     }
2616 
2617     S.Diag(NewAttribute->getLocation(),
2618            diag::warn_attribute_precede_definition);
2619     S.Diag(Def->getLocation(), diag::note_previous_definition);
2620     NewAttributes.erase(NewAttributes.begin() + I);
2621     --E;
2622   }
2623 }
2624 
2625 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2626 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2627                                AvailabilityMergeKind AMK) {
2628   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2629     UsedAttr *NewAttr = OldAttr->clone(Context);
2630     NewAttr->setInherited(true);
2631     New->addAttr(NewAttr);
2632   }
2633 
2634   if (!Old->hasAttrs() && !New->hasAttrs())
2635     return;
2636 
2637   // Attributes declared post-definition are currently ignored.
2638   checkNewAttributesAfterDef(*this, New, Old);
2639 
2640   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2641     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2642       if (OldA->getLabel() != NewA->getLabel()) {
2643         // This redeclaration changes __asm__ label.
2644         Diag(New->getLocation(), diag::err_different_asm_label);
2645         Diag(OldA->getLocation(), diag::note_previous_declaration);
2646       }
2647     } else if (Old->isUsed()) {
2648       // This redeclaration adds an __asm__ label to a declaration that has
2649       // already been ODR-used.
2650       Diag(New->getLocation(), diag::err_late_asm_label_name)
2651         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2652     }
2653   }
2654 
2655   // Re-declaration cannot add abi_tag's.
2656   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2657     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2658       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2659         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2660                       NewTag) == OldAbiTagAttr->tags_end()) {
2661           Diag(NewAbiTagAttr->getLocation(),
2662                diag::err_new_abi_tag_on_redeclaration)
2663               << NewTag;
2664           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2665         }
2666       }
2667     } else {
2668       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2669       Diag(Old->getLocation(), diag::note_previous_declaration);
2670     }
2671   }
2672 
2673   // This redeclaration adds a section attribute.
2674   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2675     if (auto *VD = dyn_cast<VarDecl>(New)) {
2676       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2677         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2678         Diag(Old->getLocation(), diag::note_previous_declaration);
2679       }
2680     }
2681   }
2682 
2683   // Redeclaration adds code-seg attribute.
2684   const auto *NewCSA = New->getAttr<CodeSegAttr>();
2685   if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2686       !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2687     Diag(New->getLocation(), diag::warn_mismatched_section)
2688          << 0 /*codeseg*/;
2689     Diag(Old->getLocation(), diag::note_previous_declaration);
2690   }
2691 
2692   if (!Old->hasAttrs())
2693     return;
2694 
2695   bool foundAny = New->hasAttrs();
2696 
2697   // Ensure that any moving of objects within the allocated map is done before
2698   // we process them.
2699   if (!foundAny) New->setAttrs(AttrVec());
2700 
2701   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2702     // Ignore deprecated/unavailable/availability attributes if requested.
2703     AvailabilityMergeKind LocalAMK = AMK_None;
2704     if (isa<DeprecatedAttr>(I) ||
2705         isa<UnavailableAttr>(I) ||
2706         isa<AvailabilityAttr>(I)) {
2707       switch (AMK) {
2708       case AMK_None:
2709         continue;
2710 
2711       case AMK_Redeclaration:
2712       case AMK_Override:
2713       case AMK_ProtocolImplementation:
2714         LocalAMK = AMK;
2715         break;
2716       }
2717     }
2718 
2719     // Already handled.
2720     if (isa<UsedAttr>(I))
2721       continue;
2722 
2723     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2724       foundAny = true;
2725   }
2726 
2727   if (mergeAlignedAttrs(*this, New, Old))
2728     foundAny = true;
2729 
2730   if (!foundAny) New->dropAttrs();
2731 }
2732 
2733 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2734 /// to the new one.
2735 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2736                                      const ParmVarDecl *oldDecl,
2737                                      Sema &S) {
2738   // C++11 [dcl.attr.depend]p2:
2739   //   The first declaration of a function shall specify the
2740   //   carries_dependency attribute for its declarator-id if any declaration
2741   //   of the function specifies the carries_dependency attribute.
2742   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2743   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2744     S.Diag(CDA->getLocation(),
2745            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2746     // Find the first declaration of the parameter.
2747     // FIXME: Should we build redeclaration chains for function parameters?
2748     const FunctionDecl *FirstFD =
2749       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2750     const ParmVarDecl *FirstVD =
2751       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2752     S.Diag(FirstVD->getLocation(),
2753            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2754   }
2755 
2756   if (!oldDecl->hasAttrs())
2757     return;
2758 
2759   bool foundAny = newDecl->hasAttrs();
2760 
2761   // Ensure that any moving of objects within the allocated map is
2762   // done before we process them.
2763   if (!foundAny) newDecl->setAttrs(AttrVec());
2764 
2765   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2766     if (!DeclHasAttr(newDecl, I)) {
2767       InheritableAttr *newAttr =
2768         cast<InheritableParamAttr>(I->clone(S.Context));
2769       newAttr->setInherited(true);
2770       newDecl->addAttr(newAttr);
2771       foundAny = true;
2772     }
2773   }
2774 
2775   if (!foundAny) newDecl->dropAttrs();
2776 }
2777 
2778 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2779                                 const ParmVarDecl *OldParam,
2780                                 Sema &S) {
2781   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2782     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2783       if (*Oldnullability != *Newnullability) {
2784         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2785           << DiagNullabilityKind(
2786                *Newnullability,
2787                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2788                 != 0))
2789           << DiagNullabilityKind(
2790                *Oldnullability,
2791                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2792                 != 0));
2793         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2794       }
2795     } else {
2796       QualType NewT = NewParam->getType();
2797       NewT = S.Context.getAttributedType(
2798                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2799                          NewT, NewT);
2800       NewParam->setType(NewT);
2801     }
2802   }
2803 }
2804 
2805 namespace {
2806 
2807 /// Used in MergeFunctionDecl to keep track of function parameters in
2808 /// C.
2809 struct GNUCompatibleParamWarning {
2810   ParmVarDecl *OldParm;
2811   ParmVarDecl *NewParm;
2812   QualType PromotedType;
2813 };
2814 
2815 } // end anonymous namespace
2816 
2817 /// getSpecialMember - get the special member enum for a method.
2818 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2819   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2820     if (Ctor->isDefaultConstructor())
2821       return Sema::CXXDefaultConstructor;
2822 
2823     if (Ctor->isCopyConstructor())
2824       return Sema::CXXCopyConstructor;
2825 
2826     if (Ctor->isMoveConstructor())
2827       return Sema::CXXMoveConstructor;
2828   } else if (isa<CXXDestructorDecl>(MD)) {
2829     return Sema::CXXDestructor;
2830   } else if (MD->isCopyAssignmentOperator()) {
2831     return Sema::CXXCopyAssignment;
2832   } else if (MD->isMoveAssignmentOperator()) {
2833     return Sema::CXXMoveAssignment;
2834   }
2835 
2836   return Sema::CXXInvalid;
2837 }
2838 
2839 // Determine whether the previous declaration was a definition, implicit
2840 // declaration, or a declaration.
2841 template <typename T>
2842 static std::pair<diag::kind, SourceLocation>
2843 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2844   diag::kind PrevDiag;
2845   SourceLocation OldLocation = Old->getLocation();
2846   if (Old->isThisDeclarationADefinition())
2847     PrevDiag = diag::note_previous_definition;
2848   else if (Old->isImplicit()) {
2849     PrevDiag = diag::note_previous_implicit_declaration;
2850     if (OldLocation.isInvalid())
2851       OldLocation = New->getLocation();
2852   } else
2853     PrevDiag = diag::note_previous_declaration;
2854   return std::make_pair(PrevDiag, OldLocation);
2855 }
2856 
2857 /// canRedefineFunction - checks if a function can be redefined. Currently,
2858 /// only extern inline functions can be redefined, and even then only in
2859 /// GNU89 mode.
2860 static bool canRedefineFunction(const FunctionDecl *FD,
2861                                 const LangOptions& LangOpts) {
2862   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2863           !LangOpts.CPlusPlus &&
2864           FD->isInlineSpecified() &&
2865           FD->getStorageClass() == SC_Extern);
2866 }
2867 
2868 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2869   const AttributedType *AT = T->getAs<AttributedType>();
2870   while (AT && !AT->isCallingConv())
2871     AT = AT->getModifiedType()->getAs<AttributedType>();
2872   return AT;
2873 }
2874 
2875 template <typename T>
2876 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2877   const DeclContext *DC = Old->getDeclContext();
2878   if (DC->isRecord())
2879     return false;
2880 
2881   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2882   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2883     return true;
2884   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2885     return true;
2886   return false;
2887 }
2888 
2889 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2890 static bool isExternC(VarTemplateDecl *) { return false; }
2891 
2892 /// Check whether a redeclaration of an entity introduced by a
2893 /// using-declaration is valid, given that we know it's not an overload
2894 /// (nor a hidden tag declaration).
2895 template<typename ExpectedDecl>
2896 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2897                                    ExpectedDecl *New) {
2898   // C++11 [basic.scope.declarative]p4:
2899   //   Given a set of declarations in a single declarative region, each of
2900   //   which specifies the same unqualified name,
2901   //   -- they shall all refer to the same entity, or all refer to functions
2902   //      and function templates; or
2903   //   -- exactly one declaration shall declare a class name or enumeration
2904   //      name that is not a typedef name and the other declarations shall all
2905   //      refer to the same variable or enumerator, or all refer to functions
2906   //      and function templates; in this case the class name or enumeration
2907   //      name is hidden (3.3.10).
2908 
2909   // C++11 [namespace.udecl]p14:
2910   //   If a function declaration in namespace scope or block scope has the
2911   //   same name and the same parameter-type-list as a function introduced
2912   //   by a using-declaration, and the declarations do not declare the same
2913   //   function, the program is ill-formed.
2914 
2915   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2916   if (Old &&
2917       !Old->getDeclContext()->getRedeclContext()->Equals(
2918           New->getDeclContext()->getRedeclContext()) &&
2919       !(isExternC(Old) && isExternC(New)))
2920     Old = nullptr;
2921 
2922   if (!Old) {
2923     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2924     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2925     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2926     return true;
2927   }
2928   return false;
2929 }
2930 
2931 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2932                                             const FunctionDecl *B) {
2933   assert(A->getNumParams() == B->getNumParams());
2934 
2935   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2936     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2937     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2938     if (AttrA == AttrB)
2939       return true;
2940     return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2941            AttrA->isDynamic() == AttrB->isDynamic();
2942   };
2943 
2944   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2945 }
2946 
2947 /// If necessary, adjust the semantic declaration context for a qualified
2948 /// declaration to name the correct inline namespace within the qualifier.
2949 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2950                                                DeclaratorDecl *OldD) {
2951   // The only case where we need to update the DeclContext is when
2952   // redeclaration lookup for a qualified name finds a declaration
2953   // in an inline namespace within the context named by the qualifier:
2954   //
2955   //   inline namespace N { int f(); }
2956   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2957   //
2958   // For unqualified declarations, the semantic context *can* change
2959   // along the redeclaration chain (for local extern declarations,
2960   // extern "C" declarations, and friend declarations in particular).
2961   if (!NewD->getQualifier())
2962     return;
2963 
2964   // NewD is probably already in the right context.
2965   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2966   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2967   if (NamedDC->Equals(SemaDC))
2968     return;
2969 
2970   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2971           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2972          "unexpected context for redeclaration");
2973 
2974   auto *LexDC = NewD->getLexicalDeclContext();
2975   auto FixSemaDC = [=](NamedDecl *D) {
2976     if (!D)
2977       return;
2978     D->setDeclContext(SemaDC);
2979     D->setLexicalDeclContext(LexDC);
2980   };
2981 
2982   FixSemaDC(NewD);
2983   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2984     FixSemaDC(FD->getDescribedFunctionTemplate());
2985   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2986     FixSemaDC(VD->getDescribedVarTemplate());
2987 }
2988 
2989 /// MergeFunctionDecl - We just parsed a function 'New' from
2990 /// declarator D which has the same name and scope as a previous
2991 /// declaration 'Old'.  Figure out how to resolve this situation,
2992 /// merging decls or emitting diagnostics as appropriate.
2993 ///
2994 /// In C++, New and Old must be declarations that are not
2995 /// overloaded. Use IsOverload to determine whether New and Old are
2996 /// overloaded, and to select the Old declaration that New should be
2997 /// merged with.
2998 ///
2999 /// Returns true if there was an error, false otherwise.
3000 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3001                              Scope *S, bool MergeTypeWithOld) {
3002   // Verify the old decl was also a function.
3003   FunctionDecl *Old = OldD->getAsFunction();
3004   if (!Old) {
3005     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3006       if (New->getFriendObjectKind()) {
3007         Diag(New->getLocation(), diag::err_using_decl_friend);
3008         Diag(Shadow->getTargetDecl()->getLocation(),
3009              diag::note_using_decl_target);
3010         Diag(Shadow->getUsingDecl()->getLocation(),
3011              diag::note_using_decl) << 0;
3012         return true;
3013       }
3014 
3015       // Check whether the two declarations might declare the same function.
3016       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3017         return true;
3018       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3019     } else {
3020       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3021         << New->getDeclName();
3022       notePreviousDefinition(OldD, New->getLocation());
3023       return true;
3024     }
3025   }
3026 
3027   // If the old declaration is invalid, just give up here.
3028   if (Old->isInvalidDecl())
3029     return true;
3030 
3031   // Disallow redeclaration of some builtins.
3032   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3033     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3034     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3035         << Old << Old->getType();
3036     return true;
3037   }
3038 
3039   diag::kind PrevDiag;
3040   SourceLocation OldLocation;
3041   std::tie(PrevDiag, OldLocation) =
3042       getNoteDiagForInvalidRedeclaration(Old, New);
3043 
3044   // Don't complain about this if we're in GNU89 mode and the old function
3045   // is an extern inline function.
3046   // Don't complain about specializations. They are not supposed to have
3047   // storage classes.
3048   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3049       New->getStorageClass() == SC_Static &&
3050       Old->hasExternalFormalLinkage() &&
3051       !New->getTemplateSpecializationInfo() &&
3052       !canRedefineFunction(Old, getLangOpts())) {
3053     if (getLangOpts().MicrosoftExt) {
3054       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3055       Diag(OldLocation, PrevDiag);
3056     } else {
3057       Diag(New->getLocation(), diag::err_static_non_static) << New;
3058       Diag(OldLocation, PrevDiag);
3059       return true;
3060     }
3061   }
3062 
3063   if (New->hasAttr<InternalLinkageAttr>() &&
3064       !Old->hasAttr<InternalLinkageAttr>()) {
3065     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3066         << New->getDeclName();
3067     notePreviousDefinition(Old, New->getLocation());
3068     New->dropAttr<InternalLinkageAttr>();
3069   }
3070 
3071   if (CheckRedeclarationModuleOwnership(New, Old))
3072     return true;
3073 
3074   if (!getLangOpts().CPlusPlus) {
3075     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3076     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3077       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3078         << New << OldOvl;
3079 
3080       // Try our best to find a decl that actually has the overloadable
3081       // attribute for the note. In most cases (e.g. programs with only one
3082       // broken declaration/definition), this won't matter.
3083       //
3084       // FIXME: We could do this if we juggled some extra state in
3085       // OverloadableAttr, rather than just removing it.
3086       const Decl *DiagOld = Old;
3087       if (OldOvl) {
3088         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3089           const auto *A = D->getAttr<OverloadableAttr>();
3090           return A && !A->isImplicit();
3091         });
3092         // If we've implicitly added *all* of the overloadable attrs to this
3093         // chain, emitting a "previous redecl" note is pointless.
3094         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3095       }
3096 
3097       if (DiagOld)
3098         Diag(DiagOld->getLocation(),
3099              diag::note_attribute_overloadable_prev_overload)
3100           << OldOvl;
3101 
3102       if (OldOvl)
3103         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3104       else
3105         New->dropAttr<OverloadableAttr>();
3106     }
3107   }
3108 
3109   // If a function is first declared with a calling convention, but is later
3110   // declared or defined without one, all following decls assume the calling
3111   // convention of the first.
3112   //
3113   // It's OK if a function is first declared without a calling convention,
3114   // but is later declared or defined with the default calling convention.
3115   //
3116   // To test if either decl has an explicit calling convention, we look for
3117   // AttributedType sugar nodes on the type as written.  If they are missing or
3118   // were canonicalized away, we assume the calling convention was implicit.
3119   //
3120   // Note also that we DO NOT return at this point, because we still have
3121   // other tests to run.
3122   QualType OldQType = Context.getCanonicalType(Old->getType());
3123   QualType NewQType = Context.getCanonicalType(New->getType());
3124   const FunctionType *OldType = cast<FunctionType>(OldQType);
3125   const FunctionType *NewType = cast<FunctionType>(NewQType);
3126   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3127   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3128   bool RequiresAdjustment = false;
3129 
3130   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3131     FunctionDecl *First = Old->getFirstDecl();
3132     const FunctionType *FT =
3133         First->getType().getCanonicalType()->castAs<FunctionType>();
3134     FunctionType::ExtInfo FI = FT->getExtInfo();
3135     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3136     if (!NewCCExplicit) {
3137       // Inherit the CC from the previous declaration if it was specified
3138       // there but not here.
3139       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3140       RequiresAdjustment = true;
3141     } else if (New->getBuiltinID()) {
3142       // Calling Conventions on a Builtin aren't really useful and setting a
3143       // default calling convention and cdecl'ing some builtin redeclarations is
3144       // common, so warn and ignore the calling convention on the redeclaration.
3145       Diag(New->getLocation(), diag::warn_cconv_ignored)
3146           << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3147           << (int)CallingConventionIgnoredReason::BuiltinFunction;
3148       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3149       RequiresAdjustment = true;
3150     } else {
3151       // Calling conventions aren't compatible, so complain.
3152       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3153       Diag(New->getLocation(), diag::err_cconv_change)
3154         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3155         << !FirstCCExplicit
3156         << (!FirstCCExplicit ? "" :
3157             FunctionType::getNameForCallConv(FI.getCC()));
3158 
3159       // Put the note on the first decl, since it is the one that matters.
3160       Diag(First->getLocation(), diag::note_previous_declaration);
3161       return true;
3162     }
3163   }
3164 
3165   // FIXME: diagnose the other way around?
3166   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3167     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3168     RequiresAdjustment = true;
3169   }
3170 
3171   // Merge regparm attribute.
3172   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3173       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3174     if (NewTypeInfo.getHasRegParm()) {
3175       Diag(New->getLocation(), diag::err_regparm_mismatch)
3176         << NewType->getRegParmType()
3177         << OldType->getRegParmType();
3178       Diag(OldLocation, diag::note_previous_declaration);
3179       return true;
3180     }
3181 
3182     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3183     RequiresAdjustment = true;
3184   }
3185 
3186   // Merge ns_returns_retained attribute.
3187   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3188     if (NewTypeInfo.getProducesResult()) {
3189       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3190           << "'ns_returns_retained'";
3191       Diag(OldLocation, diag::note_previous_declaration);
3192       return true;
3193     }
3194 
3195     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3196     RequiresAdjustment = true;
3197   }
3198 
3199   if (OldTypeInfo.getNoCallerSavedRegs() !=
3200       NewTypeInfo.getNoCallerSavedRegs()) {
3201     if (NewTypeInfo.getNoCallerSavedRegs()) {
3202       AnyX86NoCallerSavedRegistersAttr *Attr =
3203         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3204       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3205       Diag(OldLocation, diag::note_previous_declaration);
3206       return true;
3207     }
3208 
3209     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3210     RequiresAdjustment = true;
3211   }
3212 
3213   if (RequiresAdjustment) {
3214     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3215     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3216     New->setType(QualType(AdjustedType, 0));
3217     NewQType = Context.getCanonicalType(New->getType());
3218     NewType = cast<FunctionType>(NewQType);
3219   }
3220 
3221   // If this redeclaration makes the function inline, we may need to add it to
3222   // UndefinedButUsed.
3223   if (!Old->isInlined() && New->isInlined() &&
3224       !New->hasAttr<GNUInlineAttr>() &&
3225       !getLangOpts().GNUInline &&
3226       Old->isUsed(false) &&
3227       !Old->isDefined() && !New->isThisDeclarationADefinition())
3228     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3229                                            SourceLocation()));
3230 
3231   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3232   // about it.
3233   if (New->hasAttr<GNUInlineAttr>() &&
3234       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3235     UndefinedButUsed.erase(Old->getCanonicalDecl());
3236   }
3237 
3238   // If pass_object_size params don't match up perfectly, this isn't a valid
3239   // redeclaration.
3240   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3241       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3242     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3243         << New->getDeclName();
3244     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3245     return true;
3246   }
3247 
3248   if (getLangOpts().CPlusPlus) {
3249     // C++1z [over.load]p2
3250     //   Certain function declarations cannot be overloaded:
3251     //     -- Function declarations that differ only in the return type,
3252     //        the exception specification, or both cannot be overloaded.
3253 
3254     // Check the exception specifications match. This may recompute the type of
3255     // both Old and New if it resolved exception specifications, so grab the
3256     // types again after this. Because this updates the type, we do this before
3257     // any of the other checks below, which may update the "de facto" NewQType
3258     // but do not necessarily update the type of New.
3259     if (CheckEquivalentExceptionSpec(Old, New))
3260       return true;
3261     OldQType = Context.getCanonicalType(Old->getType());
3262     NewQType = Context.getCanonicalType(New->getType());
3263 
3264     // Go back to the type source info to compare the declared return types,
3265     // per C++1y [dcl.type.auto]p13:
3266     //   Redeclarations or specializations of a function or function template
3267     //   with a declared return type that uses a placeholder type shall also
3268     //   use that placeholder, not a deduced type.
3269     QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3270     QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3271     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3272         canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3273                                        OldDeclaredReturnType)) {
3274       QualType ResQT;
3275       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3276           OldDeclaredReturnType->isObjCObjectPointerType())
3277         // FIXME: This does the wrong thing for a deduced return type.
3278         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3279       if (ResQT.isNull()) {
3280         if (New->isCXXClassMember() && New->isOutOfLine())
3281           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3282               << New << New->getReturnTypeSourceRange();
3283         else
3284           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3285               << New->getReturnTypeSourceRange();
3286         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3287                                     << Old->getReturnTypeSourceRange();
3288         return true;
3289       }
3290       else
3291         NewQType = ResQT;
3292     }
3293 
3294     QualType OldReturnType = OldType->getReturnType();
3295     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3296     if (OldReturnType != NewReturnType) {
3297       // If this function has a deduced return type and has already been
3298       // defined, copy the deduced value from the old declaration.
3299       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3300       if (OldAT && OldAT->isDeduced()) {
3301         New->setType(
3302             SubstAutoType(New->getType(),
3303                           OldAT->isDependentType() ? Context.DependentTy
3304                                                    : OldAT->getDeducedType()));
3305         NewQType = Context.getCanonicalType(
3306             SubstAutoType(NewQType,
3307                           OldAT->isDependentType() ? Context.DependentTy
3308                                                    : OldAT->getDeducedType()));
3309       }
3310     }
3311 
3312     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3313     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3314     if (OldMethod && NewMethod) {
3315       // Preserve triviality.
3316       NewMethod->setTrivial(OldMethod->isTrivial());
3317 
3318       // MSVC allows explicit template specialization at class scope:
3319       // 2 CXXMethodDecls referring to the same function will be injected.
3320       // We don't want a redeclaration error.
3321       bool IsClassScopeExplicitSpecialization =
3322                               OldMethod->isFunctionTemplateSpecialization() &&
3323                               NewMethod->isFunctionTemplateSpecialization();
3324       bool isFriend = NewMethod->getFriendObjectKind();
3325 
3326       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3327           !IsClassScopeExplicitSpecialization) {
3328         //    -- Member function declarations with the same name and the
3329         //       same parameter types cannot be overloaded if any of them
3330         //       is a static member function declaration.
3331         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3332           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3333           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3334           return true;
3335         }
3336 
3337         // C++ [class.mem]p1:
3338         //   [...] A member shall not be declared twice in the
3339         //   member-specification, except that a nested class or member
3340         //   class template can be declared and then later defined.
3341         if (!inTemplateInstantiation()) {
3342           unsigned NewDiag;
3343           if (isa<CXXConstructorDecl>(OldMethod))
3344             NewDiag = diag::err_constructor_redeclared;
3345           else if (isa<CXXDestructorDecl>(NewMethod))
3346             NewDiag = diag::err_destructor_redeclared;
3347           else if (isa<CXXConversionDecl>(NewMethod))
3348             NewDiag = diag::err_conv_function_redeclared;
3349           else
3350             NewDiag = diag::err_member_redeclared;
3351 
3352           Diag(New->getLocation(), NewDiag);
3353         } else {
3354           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3355             << New << New->getType();
3356         }
3357         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3358         return true;
3359 
3360       // Complain if this is an explicit declaration of a special
3361       // member that was initially declared implicitly.
3362       //
3363       // As an exception, it's okay to befriend such methods in order
3364       // to permit the implicit constructor/destructor/operator calls.
3365       } else if (OldMethod->isImplicit()) {
3366         if (isFriend) {
3367           NewMethod->setImplicit();
3368         } else {
3369           Diag(NewMethod->getLocation(),
3370                diag::err_definition_of_implicitly_declared_member)
3371             << New << getSpecialMember(OldMethod);
3372           return true;
3373         }
3374       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3375         Diag(NewMethod->getLocation(),
3376              diag::err_definition_of_explicitly_defaulted_member)
3377           << getSpecialMember(OldMethod);
3378         return true;
3379       }
3380     }
3381 
3382     // C++11 [dcl.attr.noreturn]p1:
3383     //   The first declaration of a function shall specify the noreturn
3384     //   attribute if any declaration of that function specifies the noreturn
3385     //   attribute.
3386     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3387     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3388       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3389       Diag(Old->getFirstDecl()->getLocation(),
3390            diag::note_noreturn_missing_first_decl);
3391     }
3392 
3393     // C++11 [dcl.attr.depend]p2:
3394     //   The first declaration of a function shall specify the
3395     //   carries_dependency attribute for its declarator-id if any declaration
3396     //   of the function specifies the carries_dependency attribute.
3397     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3398     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3399       Diag(CDA->getLocation(),
3400            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3401       Diag(Old->getFirstDecl()->getLocation(),
3402            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3403     }
3404 
3405     // (C++98 8.3.5p3):
3406     //   All declarations for a function shall agree exactly in both the
3407     //   return type and the parameter-type-list.
3408     // We also want to respect all the extended bits except noreturn.
3409 
3410     // noreturn should now match unless the old type info didn't have it.
3411     QualType OldQTypeForComparison = OldQType;
3412     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3413       auto *OldType = OldQType->castAs<FunctionProtoType>();
3414       const FunctionType *OldTypeForComparison
3415         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3416       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3417       assert(OldQTypeForComparison.isCanonical());
3418     }
3419 
3420     if (haveIncompatibleLanguageLinkages(Old, New)) {
3421       // As a special case, retain the language linkage from previous
3422       // declarations of a friend function as an extension.
3423       //
3424       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3425       // and is useful because there's otherwise no way to specify language
3426       // linkage within class scope.
3427       //
3428       // Check cautiously as the friend object kind isn't yet complete.
3429       if (New->getFriendObjectKind() != Decl::FOK_None) {
3430         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3431         Diag(OldLocation, PrevDiag);
3432       } else {
3433         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3434         Diag(OldLocation, PrevDiag);
3435         return true;
3436       }
3437     }
3438 
3439     if (OldQTypeForComparison == NewQType)
3440       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3441 
3442     // If the types are imprecise (due to dependent constructs in friends or
3443     // local extern declarations), it's OK if they differ. We'll check again
3444     // during instantiation.
3445     if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3446       return false;
3447 
3448     // Fall through for conflicting redeclarations and redefinitions.
3449   }
3450 
3451   // C: Function types need to be compatible, not identical. This handles
3452   // duplicate function decls like "void f(int); void f(enum X);" properly.
3453   if (!getLangOpts().CPlusPlus &&
3454       Context.typesAreCompatible(OldQType, NewQType)) {
3455     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3456     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3457     const FunctionProtoType *OldProto = nullptr;
3458     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3459         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3460       // The old declaration provided a function prototype, but the
3461       // new declaration does not. Merge in the prototype.
3462       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3463       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3464       NewQType =
3465           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3466                                   OldProto->getExtProtoInfo());
3467       New->setType(NewQType);
3468       New->setHasInheritedPrototype();
3469 
3470       // Synthesize parameters with the same types.
3471       SmallVector<ParmVarDecl*, 16> Params;
3472       for (const auto &ParamType : OldProto->param_types()) {
3473         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3474                                                  SourceLocation(), nullptr,
3475                                                  ParamType, /*TInfo=*/nullptr,
3476                                                  SC_None, nullptr);
3477         Param->setScopeInfo(0, Params.size());
3478         Param->setImplicit();
3479         Params.push_back(Param);
3480       }
3481 
3482       New->setParams(Params);
3483     }
3484 
3485     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3486   }
3487 
3488   // GNU C permits a K&R definition to follow a prototype declaration
3489   // if the declared types of the parameters in the K&R definition
3490   // match the types in the prototype declaration, even when the
3491   // promoted types of the parameters from the K&R definition differ
3492   // from the types in the prototype. GCC then keeps the types from
3493   // the prototype.
3494   //
3495   // If a variadic prototype is followed by a non-variadic K&R definition,
3496   // the K&R definition becomes variadic.  This is sort of an edge case, but
3497   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3498   // C99 6.9.1p8.
3499   if (!getLangOpts().CPlusPlus &&
3500       Old->hasPrototype() && !New->hasPrototype() &&
3501       New->getType()->getAs<FunctionProtoType>() &&
3502       Old->getNumParams() == New->getNumParams()) {
3503     SmallVector<QualType, 16> ArgTypes;
3504     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3505     const FunctionProtoType *OldProto
3506       = Old->getType()->getAs<FunctionProtoType>();
3507     const FunctionProtoType *NewProto
3508       = New->getType()->getAs<FunctionProtoType>();
3509 
3510     // Determine whether this is the GNU C extension.
3511     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3512                                                NewProto->getReturnType());
3513     bool LooseCompatible = !MergedReturn.isNull();
3514     for (unsigned Idx = 0, End = Old->getNumParams();
3515          LooseCompatible && Idx != End; ++Idx) {
3516       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3517       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3518       if (Context.typesAreCompatible(OldParm->getType(),
3519                                      NewProto->getParamType(Idx))) {
3520         ArgTypes.push_back(NewParm->getType());
3521       } else if (Context.typesAreCompatible(OldParm->getType(),
3522                                             NewParm->getType(),
3523                                             /*CompareUnqualified=*/true)) {
3524         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3525                                            NewProto->getParamType(Idx) };
3526         Warnings.push_back(Warn);
3527         ArgTypes.push_back(NewParm->getType());
3528       } else
3529         LooseCompatible = false;
3530     }
3531 
3532     if (LooseCompatible) {
3533       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3534         Diag(Warnings[Warn].NewParm->getLocation(),
3535              diag::ext_param_promoted_not_compatible_with_prototype)
3536           << Warnings[Warn].PromotedType
3537           << Warnings[Warn].OldParm->getType();
3538         if (Warnings[Warn].OldParm->getLocation().isValid())
3539           Diag(Warnings[Warn].OldParm->getLocation(),
3540                diag::note_previous_declaration);
3541       }
3542 
3543       if (MergeTypeWithOld)
3544         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3545                                              OldProto->getExtProtoInfo()));
3546       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3547     }
3548 
3549     // Fall through to diagnose conflicting types.
3550   }
3551 
3552   // A function that has already been declared has been redeclared or
3553   // defined with a different type; show an appropriate diagnostic.
3554 
3555   // If the previous declaration was an implicitly-generated builtin
3556   // declaration, then at the very least we should use a specialized note.
3557   unsigned BuiltinID;
3558   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3559     // If it's actually a library-defined builtin function like 'malloc'
3560     // or 'printf', just warn about the incompatible redeclaration.
3561     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3562       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3563       Diag(OldLocation, diag::note_previous_builtin_declaration)
3564         << Old << Old->getType();
3565 
3566       // If this is a global redeclaration, just forget hereafter
3567       // about the "builtin-ness" of the function.
3568       //
3569       // Doing this for local extern declarations is problematic.  If
3570       // the builtin declaration remains visible, a second invalid
3571       // local declaration will produce a hard error; if it doesn't
3572       // remain visible, a single bogus local redeclaration (which is
3573       // actually only a warning) could break all the downstream code.
3574       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3575         New->getIdentifier()->revertBuiltin();
3576 
3577       return false;
3578     }
3579 
3580     PrevDiag = diag::note_previous_builtin_declaration;
3581   }
3582 
3583   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3584   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3585   return true;
3586 }
3587 
3588 /// Completes the merge of two function declarations that are
3589 /// known to be compatible.
3590 ///
3591 /// This routine handles the merging of attributes and other
3592 /// properties of function declarations from the old declaration to
3593 /// the new declaration, once we know that New is in fact a
3594 /// redeclaration of Old.
3595 ///
3596 /// \returns false
3597 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3598                                         Scope *S, bool MergeTypeWithOld) {
3599   // Merge the attributes
3600   mergeDeclAttributes(New, Old);
3601 
3602   // Merge "pure" flag.
3603   if (Old->isPure())
3604     New->setPure();
3605 
3606   // Merge "used" flag.
3607   if (Old->getMostRecentDecl()->isUsed(false))
3608     New->setIsUsed();
3609 
3610   // Merge attributes from the parameters.  These can mismatch with K&R
3611   // declarations.
3612   if (New->getNumParams() == Old->getNumParams())
3613       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3614         ParmVarDecl *NewParam = New->getParamDecl(i);
3615         ParmVarDecl *OldParam = Old->getParamDecl(i);
3616         mergeParamDeclAttributes(NewParam, OldParam, *this);
3617         mergeParamDeclTypes(NewParam, OldParam, *this);
3618       }
3619 
3620   if (getLangOpts().CPlusPlus)
3621     return MergeCXXFunctionDecl(New, Old, S);
3622 
3623   // Merge the function types so the we get the composite types for the return
3624   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3625   // was visible.
3626   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3627   if (!Merged.isNull() && MergeTypeWithOld)
3628     New->setType(Merged);
3629 
3630   return false;
3631 }
3632 
3633 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3634                                 ObjCMethodDecl *oldMethod) {
3635   // Merge the attributes, including deprecated/unavailable
3636   AvailabilityMergeKind MergeKind =
3637     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3638       ? AMK_ProtocolImplementation
3639       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3640                                                        : AMK_Override;
3641 
3642   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3643 
3644   // Merge attributes from the parameters.
3645   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3646                                        oe = oldMethod->param_end();
3647   for (ObjCMethodDecl::param_iterator
3648          ni = newMethod->param_begin(), ne = newMethod->param_end();
3649        ni != ne && oi != oe; ++ni, ++oi)
3650     mergeParamDeclAttributes(*ni, *oi, *this);
3651 
3652   CheckObjCMethodOverride(newMethod, oldMethod);
3653 }
3654 
3655 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3656   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3657 
3658   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3659          ? diag::err_redefinition_different_type
3660          : diag::err_redeclaration_different_type)
3661     << New->getDeclName() << New->getType() << Old->getType();
3662 
3663   diag::kind PrevDiag;
3664   SourceLocation OldLocation;
3665   std::tie(PrevDiag, OldLocation)
3666     = getNoteDiagForInvalidRedeclaration(Old, New);
3667   S.Diag(OldLocation, PrevDiag);
3668   New->setInvalidDecl();
3669 }
3670 
3671 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3672 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3673 /// emitting diagnostics as appropriate.
3674 ///
3675 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3676 /// to here in AddInitializerToDecl. We can't check them before the initializer
3677 /// is attached.
3678 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3679                              bool MergeTypeWithOld) {
3680   if (New->isInvalidDecl() || Old->isInvalidDecl())
3681     return;
3682 
3683   QualType MergedT;
3684   if (getLangOpts().CPlusPlus) {
3685     if (New->getType()->isUndeducedType()) {
3686       // We don't know what the new type is until the initializer is attached.
3687       return;
3688     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3689       // These could still be something that needs exception specs checked.
3690       return MergeVarDeclExceptionSpecs(New, Old);
3691     }
3692     // C++ [basic.link]p10:
3693     //   [...] the types specified by all declarations referring to a given
3694     //   object or function shall be identical, except that declarations for an
3695     //   array object can specify array types that differ by the presence or
3696     //   absence of a major array bound (8.3.4).
3697     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3698       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3699       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3700 
3701       // We are merging a variable declaration New into Old. If it has an array
3702       // bound, and that bound differs from Old's bound, we should diagnose the
3703       // mismatch.
3704       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3705         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3706              PrevVD = PrevVD->getPreviousDecl()) {
3707           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3708           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3709             continue;
3710 
3711           if (!Context.hasSameType(NewArray, PrevVDTy))
3712             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3713         }
3714       }
3715 
3716       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3717         if (Context.hasSameType(OldArray->getElementType(),
3718                                 NewArray->getElementType()))
3719           MergedT = New->getType();
3720       }
3721       // FIXME: Check visibility. New is hidden but has a complete type. If New
3722       // has no array bound, it should not inherit one from Old, if Old is not
3723       // visible.
3724       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3725         if (Context.hasSameType(OldArray->getElementType(),
3726                                 NewArray->getElementType()))
3727           MergedT = Old->getType();
3728       }
3729     }
3730     else if (New->getType()->isObjCObjectPointerType() &&
3731                Old->getType()->isObjCObjectPointerType()) {
3732       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3733                                               Old->getType());
3734     }
3735   } else {
3736     // C 6.2.7p2:
3737     //   All declarations that refer to the same object or function shall have
3738     //   compatible type.
3739     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3740   }
3741   if (MergedT.isNull()) {
3742     // It's OK if we couldn't merge types if either type is dependent, for a
3743     // block-scope variable. In other cases (static data members of class
3744     // templates, variable templates, ...), we require the types to be
3745     // equivalent.
3746     // FIXME: The C++ standard doesn't say anything about this.
3747     if ((New->getType()->isDependentType() ||
3748          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3749       // If the old type was dependent, we can't merge with it, so the new type
3750       // becomes dependent for now. We'll reproduce the original type when we
3751       // instantiate the TypeSourceInfo for the variable.
3752       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3753         New->setType(Context.DependentTy);
3754       return;
3755     }
3756     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3757   }
3758 
3759   // Don't actually update the type on the new declaration if the old
3760   // declaration was an extern declaration in a different scope.
3761   if (MergeTypeWithOld)
3762     New->setType(MergedT);
3763 }
3764 
3765 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3766                                   LookupResult &Previous) {
3767   // C11 6.2.7p4:
3768   //   For an identifier with internal or external linkage declared
3769   //   in a scope in which a prior declaration of that identifier is
3770   //   visible, if the prior declaration specifies internal or
3771   //   external linkage, the type of the identifier at the later
3772   //   declaration becomes the composite type.
3773   //
3774   // If the variable isn't visible, we do not merge with its type.
3775   if (Previous.isShadowed())
3776     return false;
3777 
3778   if (S.getLangOpts().CPlusPlus) {
3779     // C++11 [dcl.array]p3:
3780     //   If there is a preceding declaration of the entity in the same
3781     //   scope in which the bound was specified, an omitted array bound
3782     //   is taken to be the same as in that earlier declaration.
3783     return NewVD->isPreviousDeclInSameBlockScope() ||
3784            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3785             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3786   } else {
3787     // If the old declaration was function-local, don't merge with its
3788     // type unless we're in the same function.
3789     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3790            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3791   }
3792 }
3793 
3794 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3795 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3796 /// situation, merging decls or emitting diagnostics as appropriate.
3797 ///
3798 /// Tentative definition rules (C99 6.9.2p2) are checked by
3799 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3800 /// definitions here, since the initializer hasn't been attached.
3801 ///
3802 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3803   // If the new decl is already invalid, don't do any other checking.
3804   if (New->isInvalidDecl())
3805     return;
3806 
3807   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3808     return;
3809 
3810   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3811 
3812   // Verify the old decl was also a variable or variable template.
3813   VarDecl *Old = nullptr;
3814   VarTemplateDecl *OldTemplate = nullptr;
3815   if (Previous.isSingleResult()) {
3816     if (NewTemplate) {
3817       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3818       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3819 
3820       if (auto *Shadow =
3821               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3822         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3823           return New->setInvalidDecl();
3824     } else {
3825       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3826 
3827       if (auto *Shadow =
3828               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3829         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3830           return New->setInvalidDecl();
3831     }
3832   }
3833   if (!Old) {
3834     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3835         << New->getDeclName();
3836     notePreviousDefinition(Previous.getRepresentativeDecl(),
3837                            New->getLocation());
3838     return New->setInvalidDecl();
3839   }
3840 
3841   // Ensure the template parameters are compatible.
3842   if (NewTemplate &&
3843       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3844                                       OldTemplate->getTemplateParameters(),
3845                                       /*Complain=*/true, TPL_TemplateMatch))
3846     return New->setInvalidDecl();
3847 
3848   // C++ [class.mem]p1:
3849   //   A member shall not be declared twice in the member-specification [...]
3850   //
3851   // Here, we need only consider static data members.
3852   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3853     Diag(New->getLocation(), diag::err_duplicate_member)
3854       << New->getIdentifier();
3855     Diag(Old->getLocation(), diag::note_previous_declaration);
3856     New->setInvalidDecl();
3857   }
3858 
3859   mergeDeclAttributes(New, Old);
3860   // Warn if an already-declared variable is made a weak_import in a subsequent
3861   // declaration
3862   if (New->hasAttr<WeakImportAttr>() &&
3863       Old->getStorageClass() == SC_None &&
3864       !Old->hasAttr<WeakImportAttr>()) {
3865     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3866     notePreviousDefinition(Old, New->getLocation());
3867     // Remove weak_import attribute on new declaration.
3868     New->dropAttr<WeakImportAttr>();
3869   }
3870 
3871   if (New->hasAttr<InternalLinkageAttr>() &&
3872       !Old->hasAttr<InternalLinkageAttr>()) {
3873     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3874         << New->getDeclName();
3875     notePreviousDefinition(Old, New->getLocation());
3876     New->dropAttr<InternalLinkageAttr>();
3877   }
3878 
3879   // Merge the types.
3880   VarDecl *MostRecent = Old->getMostRecentDecl();
3881   if (MostRecent != Old) {
3882     MergeVarDeclTypes(New, MostRecent,
3883                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3884     if (New->isInvalidDecl())
3885       return;
3886   }
3887 
3888   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3889   if (New->isInvalidDecl())
3890     return;
3891 
3892   diag::kind PrevDiag;
3893   SourceLocation OldLocation;
3894   std::tie(PrevDiag, OldLocation) =
3895       getNoteDiagForInvalidRedeclaration(Old, New);
3896 
3897   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3898   if (New->getStorageClass() == SC_Static &&
3899       !New->isStaticDataMember() &&
3900       Old->hasExternalFormalLinkage()) {
3901     if (getLangOpts().MicrosoftExt) {
3902       Diag(New->getLocation(), diag::ext_static_non_static)
3903           << New->getDeclName();
3904       Diag(OldLocation, PrevDiag);
3905     } else {
3906       Diag(New->getLocation(), diag::err_static_non_static)
3907           << New->getDeclName();
3908       Diag(OldLocation, PrevDiag);
3909       return New->setInvalidDecl();
3910     }
3911   }
3912   // C99 6.2.2p4:
3913   //   For an identifier declared with the storage-class specifier
3914   //   extern in a scope in which a prior declaration of that
3915   //   identifier is visible,23) if the prior declaration specifies
3916   //   internal or external linkage, the linkage of the identifier at
3917   //   the later declaration is the same as the linkage specified at
3918   //   the prior declaration. If no prior declaration is visible, or
3919   //   if the prior declaration specifies no linkage, then the
3920   //   identifier has external linkage.
3921   if (New->hasExternalStorage() && Old->hasLinkage())
3922     /* Okay */;
3923   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3924            !New->isStaticDataMember() &&
3925            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3926     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3927     Diag(OldLocation, PrevDiag);
3928     return New->setInvalidDecl();
3929   }
3930 
3931   // Check if extern is followed by non-extern and vice-versa.
3932   if (New->hasExternalStorage() &&
3933       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3934     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3935     Diag(OldLocation, PrevDiag);
3936     return New->setInvalidDecl();
3937   }
3938   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3939       !New->hasExternalStorage()) {
3940     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3941     Diag(OldLocation, PrevDiag);
3942     return New->setInvalidDecl();
3943   }
3944 
3945   if (CheckRedeclarationModuleOwnership(New, Old))
3946     return;
3947 
3948   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3949 
3950   // FIXME: The test for external storage here seems wrong? We still
3951   // need to check for mismatches.
3952   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3953       // Don't complain about out-of-line definitions of static members.
3954       !(Old->getLexicalDeclContext()->isRecord() &&
3955         !New->getLexicalDeclContext()->isRecord())) {
3956     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3957     Diag(OldLocation, PrevDiag);
3958     return New->setInvalidDecl();
3959   }
3960 
3961   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3962     if (VarDecl *Def = Old->getDefinition()) {
3963       // C++1z [dcl.fcn.spec]p4:
3964       //   If the definition of a variable appears in a translation unit before
3965       //   its first declaration as inline, the program is ill-formed.
3966       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3967       Diag(Def->getLocation(), diag::note_previous_definition);
3968     }
3969   }
3970 
3971   // If this redeclaration makes the variable inline, we may need to add it to
3972   // UndefinedButUsed.
3973   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3974       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3975     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3976                                            SourceLocation()));
3977 
3978   if (New->getTLSKind() != Old->getTLSKind()) {
3979     if (!Old->getTLSKind()) {
3980       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3981       Diag(OldLocation, PrevDiag);
3982     } else if (!New->getTLSKind()) {
3983       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3984       Diag(OldLocation, PrevDiag);
3985     } else {
3986       // Do not allow redeclaration to change the variable between requiring
3987       // static and dynamic initialization.
3988       // FIXME: GCC allows this, but uses the TLS keyword on the first
3989       // declaration to determine the kind. Do we need to be compatible here?
3990       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3991         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3992       Diag(OldLocation, PrevDiag);
3993     }
3994   }
3995 
3996   // C++ doesn't have tentative definitions, so go right ahead and check here.
3997   if (getLangOpts().CPlusPlus &&
3998       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3999     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4000         Old->getCanonicalDecl()->isConstexpr()) {
4001       // This definition won't be a definition any more once it's been merged.
4002       Diag(New->getLocation(),
4003            diag::warn_deprecated_redundant_constexpr_static_def);
4004     } else if (VarDecl *Def = Old->getDefinition()) {
4005       if (checkVarDeclRedefinition(Def, New))
4006         return;
4007     }
4008   }
4009 
4010   if (haveIncompatibleLanguageLinkages(Old, New)) {
4011     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4012     Diag(OldLocation, PrevDiag);
4013     New->setInvalidDecl();
4014     return;
4015   }
4016 
4017   // Merge "used" flag.
4018   if (Old->getMostRecentDecl()->isUsed(false))
4019     New->setIsUsed();
4020 
4021   // Keep a chain of previous declarations.
4022   New->setPreviousDecl(Old);
4023   if (NewTemplate)
4024     NewTemplate->setPreviousDecl(OldTemplate);
4025   adjustDeclContextForDeclaratorDecl(New, Old);
4026 
4027   // Inherit access appropriately.
4028   New->setAccess(Old->getAccess());
4029   if (NewTemplate)
4030     NewTemplate->setAccess(New->getAccess());
4031 
4032   if (Old->isInline())
4033     New->setImplicitlyInline();
4034 }
4035 
4036 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4037   SourceManager &SrcMgr = getSourceManager();
4038   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4039   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4040   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4041   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4042   auto &HSI = PP.getHeaderSearchInfo();
4043   StringRef HdrFilename =
4044       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4045 
4046   auto noteFromModuleOrInclude = [&](Module *Mod,
4047                                      SourceLocation IncLoc) -> bool {
4048     // Redefinition errors with modules are common with non modular mapped
4049     // headers, example: a non-modular header H in module A that also gets
4050     // included directly in a TU. Pointing twice to the same header/definition
4051     // is confusing, try to get better diagnostics when modules is on.
4052     if (IncLoc.isValid()) {
4053       if (Mod) {
4054         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4055             << HdrFilename.str() << Mod->getFullModuleName();
4056         if (!Mod->DefinitionLoc.isInvalid())
4057           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4058               << Mod->getFullModuleName();
4059       } else {
4060         Diag(IncLoc, diag::note_redefinition_include_same_file)
4061             << HdrFilename.str();
4062       }
4063       return true;
4064     }
4065 
4066     return false;
4067   };
4068 
4069   // Is it the same file and same offset? Provide more information on why
4070   // this leads to a redefinition error.
4071   bool EmittedDiag = false;
4072   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4073     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4074     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4075     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4076     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4077 
4078     // If the header has no guards, emit a note suggesting one.
4079     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4080       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4081 
4082     if (EmittedDiag)
4083       return;
4084   }
4085 
4086   // Redefinition coming from different files or couldn't do better above.
4087   if (Old->getLocation().isValid())
4088     Diag(Old->getLocation(), diag::note_previous_definition);
4089 }
4090 
4091 /// We've just determined that \p Old and \p New both appear to be definitions
4092 /// of the same variable. Either diagnose or fix the problem.
4093 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4094   if (!hasVisibleDefinition(Old) &&
4095       (New->getFormalLinkage() == InternalLinkage ||
4096        New->isInline() ||
4097        New->getDescribedVarTemplate() ||
4098        New->getNumTemplateParameterLists() ||
4099        New->getDeclContext()->isDependentContext())) {
4100     // The previous definition is hidden, and multiple definitions are
4101     // permitted (in separate TUs). Demote this to a declaration.
4102     New->demoteThisDefinitionToDeclaration();
4103 
4104     // Make the canonical definition visible.
4105     if (auto *OldTD = Old->getDescribedVarTemplate())
4106       makeMergedDefinitionVisible(OldTD);
4107     makeMergedDefinitionVisible(Old);
4108     return false;
4109   } else {
4110     Diag(New->getLocation(), diag::err_redefinition) << New;
4111     notePreviousDefinition(Old, New->getLocation());
4112     New->setInvalidDecl();
4113     return true;
4114   }
4115 }
4116 
4117 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4118 /// no declarator (e.g. "struct foo;") is parsed.
4119 Decl *
4120 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4121                                  RecordDecl *&AnonRecord) {
4122   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4123                                     AnonRecord);
4124 }
4125 
4126 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4127 // disambiguate entities defined in different scopes.
4128 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4129 // compatibility.
4130 // We will pick our mangling number depending on which version of MSVC is being
4131 // targeted.
4132 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4133   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4134              ? S->getMSCurManglingNumber()
4135              : S->getMSLastManglingNumber();
4136 }
4137 
4138 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4139   if (!Context.getLangOpts().CPlusPlus)
4140     return;
4141 
4142   if (isa<CXXRecordDecl>(Tag->getParent())) {
4143     // If this tag is the direct child of a class, number it if
4144     // it is anonymous.
4145     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4146       return;
4147     MangleNumberingContext &MCtx =
4148         Context.getManglingNumberContext(Tag->getParent());
4149     Context.setManglingNumber(
4150         Tag, MCtx.getManglingNumber(
4151                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4152     return;
4153   }
4154 
4155   // If this tag isn't a direct child of a class, number it if it is local.
4156   Decl *ManglingContextDecl;
4157   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4158           Tag->getDeclContext(), ManglingContextDecl)) {
4159     Context.setManglingNumber(
4160         Tag, MCtx->getManglingNumber(
4161                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4162   }
4163 }
4164 
4165 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4166                                         TypedefNameDecl *NewTD) {
4167   if (TagFromDeclSpec->isInvalidDecl())
4168     return;
4169 
4170   // Do nothing if the tag already has a name for linkage purposes.
4171   if (TagFromDeclSpec->hasNameForLinkage())
4172     return;
4173 
4174   // A well-formed anonymous tag must always be a TUK_Definition.
4175   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4176 
4177   // The type must match the tag exactly;  no qualifiers allowed.
4178   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4179                            Context.getTagDeclType(TagFromDeclSpec))) {
4180     if (getLangOpts().CPlusPlus)
4181       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4182     return;
4183   }
4184 
4185   // If we've already computed linkage for the anonymous tag, then
4186   // adding a typedef name for the anonymous decl can change that
4187   // linkage, which might be a serious problem.  Diagnose this as
4188   // unsupported and ignore the typedef name.  TODO: we should
4189   // pursue this as a language defect and establish a formal rule
4190   // for how to handle it.
4191   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4192     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4193 
4194     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4195     tagLoc = getLocForEndOfToken(tagLoc);
4196 
4197     llvm::SmallString<40> textToInsert;
4198     textToInsert += ' ';
4199     textToInsert += NewTD->getIdentifier()->getName();
4200     Diag(tagLoc, diag::note_typedef_changes_linkage)
4201         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4202     return;
4203   }
4204 
4205   // Otherwise, set this is the anon-decl typedef for the tag.
4206   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4207 }
4208 
4209 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4210   switch (T) {
4211   case DeclSpec::TST_class:
4212     return 0;
4213   case DeclSpec::TST_struct:
4214     return 1;
4215   case DeclSpec::TST_interface:
4216     return 2;
4217   case DeclSpec::TST_union:
4218     return 3;
4219   case DeclSpec::TST_enum:
4220     return 4;
4221   default:
4222     llvm_unreachable("unexpected type specifier");
4223   }
4224 }
4225 
4226 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4227 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4228 /// parameters to cope with template friend declarations.
4229 Decl *
4230 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4231                                  MultiTemplateParamsArg TemplateParams,
4232                                  bool IsExplicitInstantiation,
4233                                  RecordDecl *&AnonRecord) {
4234   Decl *TagD = nullptr;
4235   TagDecl *Tag = nullptr;
4236   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4237       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4238       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4239       DS.getTypeSpecType() == DeclSpec::TST_union ||
4240       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4241     TagD = DS.getRepAsDecl();
4242 
4243     if (!TagD) // We probably had an error
4244       return nullptr;
4245 
4246     // Note that the above type specs guarantee that the
4247     // type rep is a Decl, whereas in many of the others
4248     // it's a Type.
4249     if (isa<TagDecl>(TagD))
4250       Tag = cast<TagDecl>(TagD);
4251     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4252       Tag = CTD->getTemplatedDecl();
4253   }
4254 
4255   if (Tag) {
4256     handleTagNumbering(Tag, S);
4257     Tag->setFreeStanding();
4258     if (Tag->isInvalidDecl())
4259       return Tag;
4260   }
4261 
4262   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4263     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4264     // or incomplete types shall not be restrict-qualified."
4265     if (TypeQuals & DeclSpec::TQ_restrict)
4266       Diag(DS.getRestrictSpecLoc(),
4267            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4268            << DS.getSourceRange();
4269   }
4270 
4271   if (DS.isInlineSpecified())
4272     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4273         << getLangOpts().CPlusPlus17;
4274 
4275   if (DS.isConstexprSpecified()) {
4276     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4277     // and definitions of functions and variables.
4278     if (Tag)
4279       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4280           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4281     else
4282       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4283     // Don't emit warnings after this error.
4284     return TagD;
4285   }
4286 
4287   DiagnoseFunctionSpecifiers(DS);
4288 
4289   if (DS.isFriendSpecified()) {
4290     // If we're dealing with a decl but not a TagDecl, assume that
4291     // whatever routines created it handled the friendship aspect.
4292     if (TagD && !Tag)
4293       return nullptr;
4294     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4295   }
4296 
4297   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4298   bool IsExplicitSpecialization =
4299     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4300   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4301       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4302       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4303     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4304     // nested-name-specifier unless it is an explicit instantiation
4305     // or an explicit specialization.
4306     //
4307     // FIXME: We allow class template partial specializations here too, per the
4308     // obvious intent of DR1819.
4309     //
4310     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4311     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4312         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4313     return nullptr;
4314   }
4315 
4316   // Track whether this decl-specifier declares anything.
4317   bool DeclaresAnything = true;
4318 
4319   // Handle anonymous struct definitions.
4320   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4321     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4322         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4323       if (getLangOpts().CPlusPlus ||
4324           Record->getDeclContext()->isRecord()) {
4325         // If CurContext is a DeclContext that can contain statements,
4326         // RecursiveASTVisitor won't visit the decls that
4327         // BuildAnonymousStructOrUnion() will put into CurContext.
4328         // Also store them here so that they can be part of the
4329         // DeclStmt that gets created in this case.
4330         // FIXME: Also return the IndirectFieldDecls created by
4331         // BuildAnonymousStructOr union, for the same reason?
4332         if (CurContext->isFunctionOrMethod())
4333           AnonRecord = Record;
4334         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4335                                            Context.getPrintingPolicy());
4336       }
4337 
4338       DeclaresAnything = false;
4339     }
4340   }
4341 
4342   // C11 6.7.2.1p2:
4343   //   A struct-declaration that does not declare an anonymous structure or
4344   //   anonymous union shall contain a struct-declarator-list.
4345   //
4346   // This rule also existed in C89 and C99; the grammar for struct-declaration
4347   // did not permit a struct-declaration without a struct-declarator-list.
4348   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4349       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4350     // Check for Microsoft C extension: anonymous struct/union member.
4351     // Handle 2 kinds of anonymous struct/union:
4352     //   struct STRUCT;
4353     //   union UNION;
4354     // and
4355     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4356     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4357     if ((Tag && Tag->getDeclName()) ||
4358         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4359       RecordDecl *Record = nullptr;
4360       if (Tag)
4361         Record = dyn_cast<RecordDecl>(Tag);
4362       else if (const RecordType *RT =
4363                    DS.getRepAsType().get()->getAsStructureType())
4364         Record = RT->getDecl();
4365       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4366         Record = UT->getDecl();
4367 
4368       if (Record && getLangOpts().MicrosoftExt) {
4369         Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4370             << Record->isUnion() << DS.getSourceRange();
4371         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4372       }
4373 
4374       DeclaresAnything = false;
4375     }
4376   }
4377 
4378   // Skip all the checks below if we have a type error.
4379   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4380       (TagD && TagD->isInvalidDecl()))
4381     return TagD;
4382 
4383   if (getLangOpts().CPlusPlus &&
4384       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4385     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4386       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4387           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4388         DeclaresAnything = false;
4389 
4390   if (!DS.isMissingDeclaratorOk()) {
4391     // Customize diagnostic for a typedef missing a name.
4392     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4393       Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4394           << DS.getSourceRange();
4395     else
4396       DeclaresAnything = false;
4397   }
4398 
4399   if (DS.isModulePrivateSpecified() &&
4400       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4401     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4402       << Tag->getTagKind()
4403       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4404 
4405   ActOnDocumentableDecl(TagD);
4406 
4407   // C 6.7/2:
4408   //   A declaration [...] shall declare at least a declarator [...], a tag,
4409   //   or the members of an enumeration.
4410   // C++ [dcl.dcl]p3:
4411   //   [If there are no declarators], and except for the declaration of an
4412   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4413   //   names into the program, or shall redeclare a name introduced by a
4414   //   previous declaration.
4415   if (!DeclaresAnything) {
4416     // In C, we allow this as a (popular) extension / bug. Don't bother
4417     // producing further diagnostics for redundant qualifiers after this.
4418     Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4419     return TagD;
4420   }
4421 
4422   // C++ [dcl.stc]p1:
4423   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4424   //   init-declarator-list of the declaration shall not be empty.
4425   // C++ [dcl.fct.spec]p1:
4426   //   If a cv-qualifier appears in a decl-specifier-seq, the
4427   //   init-declarator-list of the declaration shall not be empty.
4428   //
4429   // Spurious qualifiers here appear to be valid in C.
4430   unsigned DiagID = diag::warn_standalone_specifier;
4431   if (getLangOpts().CPlusPlus)
4432     DiagID = diag::ext_standalone_specifier;
4433 
4434   // Note that a linkage-specification sets a storage class, but
4435   // 'extern "C" struct foo;' is actually valid and not theoretically
4436   // useless.
4437   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4438     if (SCS == DeclSpec::SCS_mutable)
4439       // Since mutable is not a viable storage class specifier in C, there is
4440       // no reason to treat it as an extension. Instead, diagnose as an error.
4441       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4442     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4443       Diag(DS.getStorageClassSpecLoc(), DiagID)
4444         << DeclSpec::getSpecifierName(SCS);
4445   }
4446 
4447   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4448     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4449       << DeclSpec::getSpecifierName(TSCS);
4450   if (DS.getTypeQualifiers()) {
4451     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4452       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4453     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4454       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4455     // Restrict is covered above.
4456     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4457       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4458     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4459       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4460   }
4461 
4462   // Warn about ignored type attributes, for example:
4463   // __attribute__((aligned)) struct A;
4464   // Attributes should be placed after tag to apply to type declaration.
4465   if (!DS.getAttributes().empty()) {
4466     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4467     if (TypeSpecType == DeclSpec::TST_class ||
4468         TypeSpecType == DeclSpec::TST_struct ||
4469         TypeSpecType == DeclSpec::TST_interface ||
4470         TypeSpecType == DeclSpec::TST_union ||
4471         TypeSpecType == DeclSpec::TST_enum) {
4472       for (const ParsedAttr &AL : DS.getAttributes())
4473         Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4474             << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4475     }
4476   }
4477 
4478   return TagD;
4479 }
4480 
4481 /// We are trying to inject an anonymous member into the given scope;
4482 /// check if there's an existing declaration that can't be overloaded.
4483 ///
4484 /// \return true if this is a forbidden redeclaration
4485 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4486                                          Scope *S,
4487                                          DeclContext *Owner,
4488                                          DeclarationName Name,
4489                                          SourceLocation NameLoc,
4490                                          bool IsUnion) {
4491   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4492                  Sema::ForVisibleRedeclaration);
4493   if (!SemaRef.LookupName(R, S)) return false;
4494 
4495   // Pick a representative declaration.
4496   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4497   assert(PrevDecl && "Expected a non-null Decl");
4498 
4499   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4500     return false;
4501 
4502   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4503     << IsUnion << Name;
4504   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4505 
4506   return true;
4507 }
4508 
4509 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4510 /// anonymous struct or union AnonRecord into the owning context Owner
4511 /// and scope S. This routine will be invoked just after we realize
4512 /// that an unnamed union or struct is actually an anonymous union or
4513 /// struct, e.g.,
4514 ///
4515 /// @code
4516 /// union {
4517 ///   int i;
4518 ///   float f;
4519 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4520 ///    // f into the surrounding scope.x
4521 /// @endcode
4522 ///
4523 /// This routine is recursive, injecting the names of nested anonymous
4524 /// structs/unions into the owning context and scope as well.
4525 static bool
4526 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4527                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4528                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4529   bool Invalid = false;
4530 
4531   // Look every FieldDecl and IndirectFieldDecl with a name.
4532   for (auto *D : AnonRecord->decls()) {
4533     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4534         cast<NamedDecl>(D)->getDeclName()) {
4535       ValueDecl *VD = cast<ValueDecl>(D);
4536       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4537                                        VD->getLocation(),
4538                                        AnonRecord->isUnion())) {
4539         // C++ [class.union]p2:
4540         //   The names of the members of an anonymous union shall be
4541         //   distinct from the names of any other entity in the
4542         //   scope in which the anonymous union is declared.
4543         Invalid = true;
4544       } else {
4545         // C++ [class.union]p2:
4546         //   For the purpose of name lookup, after the anonymous union
4547         //   definition, the members of the anonymous union are
4548         //   considered to have been defined in the scope in which the
4549         //   anonymous union is declared.
4550         unsigned OldChainingSize = Chaining.size();
4551         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4552           Chaining.append(IF->chain_begin(), IF->chain_end());
4553         else
4554           Chaining.push_back(VD);
4555 
4556         assert(Chaining.size() >= 2);
4557         NamedDecl **NamedChain =
4558           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4559         for (unsigned i = 0; i < Chaining.size(); i++)
4560           NamedChain[i] = Chaining[i];
4561 
4562         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4563             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4564             VD->getType(), {NamedChain, Chaining.size()});
4565 
4566         for (const auto *Attr : VD->attrs())
4567           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4568 
4569         IndirectField->setAccess(AS);
4570         IndirectField->setImplicit();
4571         SemaRef.PushOnScopeChains(IndirectField, S);
4572 
4573         // That includes picking up the appropriate access specifier.
4574         if (AS != AS_none) IndirectField->setAccess(AS);
4575 
4576         Chaining.resize(OldChainingSize);
4577       }
4578     }
4579   }
4580 
4581   return Invalid;
4582 }
4583 
4584 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4585 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4586 /// illegal input values are mapped to SC_None.
4587 static StorageClass
4588 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4589   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4590   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4591          "Parser allowed 'typedef' as storage class VarDecl.");
4592   switch (StorageClassSpec) {
4593   case DeclSpec::SCS_unspecified:    return SC_None;
4594   case DeclSpec::SCS_extern:
4595     if (DS.isExternInLinkageSpec())
4596       return SC_None;
4597     return SC_Extern;
4598   case DeclSpec::SCS_static:         return SC_Static;
4599   case DeclSpec::SCS_auto:           return SC_Auto;
4600   case DeclSpec::SCS_register:       return SC_Register;
4601   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4602     // Illegal SCSs map to None: error reporting is up to the caller.
4603   case DeclSpec::SCS_mutable:        // Fall through.
4604   case DeclSpec::SCS_typedef:        return SC_None;
4605   }
4606   llvm_unreachable("unknown storage class specifier");
4607 }
4608 
4609 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4610   assert(Record->hasInClassInitializer());
4611 
4612   for (const auto *I : Record->decls()) {
4613     const auto *FD = dyn_cast<FieldDecl>(I);
4614     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4615       FD = IFD->getAnonField();
4616     if (FD && FD->hasInClassInitializer())
4617       return FD->getLocation();
4618   }
4619 
4620   llvm_unreachable("couldn't find in-class initializer");
4621 }
4622 
4623 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4624                                       SourceLocation DefaultInitLoc) {
4625   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4626     return;
4627 
4628   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4629   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4630 }
4631 
4632 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4633                                       CXXRecordDecl *AnonUnion) {
4634   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4635     return;
4636 
4637   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4638 }
4639 
4640 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4641 /// anonymous structure or union. Anonymous unions are a C++ feature
4642 /// (C++ [class.union]) and a C11 feature; anonymous structures
4643 /// are a C11 feature and GNU C++ extension.
4644 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4645                                         AccessSpecifier AS,
4646                                         RecordDecl *Record,
4647                                         const PrintingPolicy &Policy) {
4648   DeclContext *Owner = Record->getDeclContext();
4649 
4650   // Diagnose whether this anonymous struct/union is an extension.
4651   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4652     Diag(Record->getLocation(), diag::ext_anonymous_union);
4653   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4654     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4655   else if (!Record->isUnion() && !getLangOpts().C11)
4656     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4657 
4658   // C and C++ require different kinds of checks for anonymous
4659   // structs/unions.
4660   bool Invalid = false;
4661   if (getLangOpts().CPlusPlus) {
4662     const char *PrevSpec = nullptr;
4663     unsigned DiagID;
4664     if (Record->isUnion()) {
4665       // C++ [class.union]p6:
4666       // C++17 [class.union.anon]p2:
4667       //   Anonymous unions declared in a named namespace or in the
4668       //   global namespace shall be declared static.
4669       DeclContext *OwnerScope = Owner->getRedeclContext();
4670       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4671           (OwnerScope->isTranslationUnit() ||
4672            (OwnerScope->isNamespace() &&
4673             !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4674         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4675           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4676 
4677         // Recover by adding 'static'.
4678         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4679                                PrevSpec, DiagID, Policy);
4680       }
4681       // C++ [class.union]p6:
4682       //   A storage class is not allowed in a declaration of an
4683       //   anonymous union in a class scope.
4684       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4685                isa<RecordDecl>(Owner)) {
4686         Diag(DS.getStorageClassSpecLoc(),
4687              diag::err_anonymous_union_with_storage_spec)
4688           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4689 
4690         // Recover by removing the storage specifier.
4691         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4692                                SourceLocation(),
4693                                PrevSpec, DiagID, Context.getPrintingPolicy());
4694       }
4695     }
4696 
4697     // Ignore const/volatile/restrict qualifiers.
4698     if (DS.getTypeQualifiers()) {
4699       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4700         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4701           << Record->isUnion() << "const"
4702           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4703       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4704         Diag(DS.getVolatileSpecLoc(),
4705              diag::ext_anonymous_struct_union_qualified)
4706           << Record->isUnion() << "volatile"
4707           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4708       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4709         Diag(DS.getRestrictSpecLoc(),
4710              diag::ext_anonymous_struct_union_qualified)
4711           << Record->isUnion() << "restrict"
4712           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4713       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4714         Diag(DS.getAtomicSpecLoc(),
4715              diag::ext_anonymous_struct_union_qualified)
4716           << Record->isUnion() << "_Atomic"
4717           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4718       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4719         Diag(DS.getUnalignedSpecLoc(),
4720              diag::ext_anonymous_struct_union_qualified)
4721           << Record->isUnion() << "__unaligned"
4722           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4723 
4724       DS.ClearTypeQualifiers();
4725     }
4726 
4727     // C++ [class.union]p2:
4728     //   The member-specification of an anonymous union shall only
4729     //   define non-static data members. [Note: nested types and
4730     //   functions cannot be declared within an anonymous union. ]
4731     for (auto *Mem : Record->decls()) {
4732       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4733         // C++ [class.union]p3:
4734         //   An anonymous union shall not have private or protected
4735         //   members (clause 11).
4736         assert(FD->getAccess() != AS_none);
4737         if (FD->getAccess() != AS_public) {
4738           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4739             << Record->isUnion() << (FD->getAccess() == AS_protected);
4740           Invalid = true;
4741         }
4742 
4743         // C++ [class.union]p1
4744         //   An object of a class with a non-trivial constructor, a non-trivial
4745         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4746         //   assignment operator cannot be a member of a union, nor can an
4747         //   array of such objects.
4748         if (CheckNontrivialField(FD))
4749           Invalid = true;
4750       } else if (Mem->isImplicit()) {
4751         // Any implicit members are fine.
4752       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4753         // This is a type that showed up in an
4754         // elaborated-type-specifier inside the anonymous struct or
4755         // union, but which actually declares a type outside of the
4756         // anonymous struct or union. It's okay.
4757       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4758         if (!MemRecord->isAnonymousStructOrUnion() &&
4759             MemRecord->getDeclName()) {
4760           // Visual C++ allows type definition in anonymous struct or union.
4761           if (getLangOpts().MicrosoftExt)
4762             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4763               << Record->isUnion();
4764           else {
4765             // This is a nested type declaration.
4766             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4767               << Record->isUnion();
4768             Invalid = true;
4769           }
4770         } else {
4771           // This is an anonymous type definition within another anonymous type.
4772           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4773           // not part of standard C++.
4774           Diag(MemRecord->getLocation(),
4775                diag::ext_anonymous_record_with_anonymous_type)
4776             << Record->isUnion();
4777         }
4778       } else if (isa<AccessSpecDecl>(Mem)) {
4779         // Any access specifier is fine.
4780       } else if (isa<StaticAssertDecl>(Mem)) {
4781         // In C++1z, static_assert declarations are also fine.
4782       } else {
4783         // We have something that isn't a non-static data
4784         // member. Complain about it.
4785         unsigned DK = diag::err_anonymous_record_bad_member;
4786         if (isa<TypeDecl>(Mem))
4787           DK = diag::err_anonymous_record_with_type;
4788         else if (isa<FunctionDecl>(Mem))
4789           DK = diag::err_anonymous_record_with_function;
4790         else if (isa<VarDecl>(Mem))
4791           DK = diag::err_anonymous_record_with_static;
4792 
4793         // Visual C++ allows type definition in anonymous struct or union.
4794         if (getLangOpts().MicrosoftExt &&
4795             DK == diag::err_anonymous_record_with_type)
4796           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4797             << Record->isUnion();
4798         else {
4799           Diag(Mem->getLocation(), DK) << Record->isUnion();
4800           Invalid = true;
4801         }
4802       }
4803     }
4804 
4805     // C++11 [class.union]p8 (DR1460):
4806     //   At most one variant member of a union may have a
4807     //   brace-or-equal-initializer.
4808     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4809         Owner->isRecord())
4810       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4811                                 cast<CXXRecordDecl>(Record));
4812   }
4813 
4814   if (!Record->isUnion() && !Owner->isRecord()) {
4815     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4816       << getLangOpts().CPlusPlus;
4817     Invalid = true;
4818   }
4819 
4820   // Mock up a declarator.
4821   Declarator Dc(DS, DeclaratorContext::MemberContext);
4822   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4823   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4824 
4825   // Create a declaration for this anonymous struct/union.
4826   NamedDecl *Anon = nullptr;
4827   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4828     Anon = FieldDecl::Create(
4829         Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
4830         /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
4831         /*BitWidth=*/nullptr, /*Mutable=*/false,
4832         /*InitStyle=*/ICIS_NoInit);
4833     Anon->setAccess(AS);
4834     if (getLangOpts().CPlusPlus)
4835       FieldCollector->Add(cast<FieldDecl>(Anon));
4836   } else {
4837     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4838     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4839     if (SCSpec == DeclSpec::SCS_mutable) {
4840       // mutable can only appear on non-static class members, so it's always
4841       // an error here
4842       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4843       Invalid = true;
4844       SC = SC_None;
4845     }
4846 
4847     Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
4848                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4849                            Context.getTypeDeclType(Record), TInfo, SC);
4850 
4851     // Default-initialize the implicit variable. This initialization will be
4852     // trivial in almost all cases, except if a union member has an in-class
4853     // initializer:
4854     //   union { int n = 0; };
4855     ActOnUninitializedDecl(Anon);
4856   }
4857   Anon->setImplicit();
4858 
4859   // Mark this as an anonymous struct/union type.
4860   Record->setAnonymousStructOrUnion(true);
4861 
4862   // Add the anonymous struct/union object to the current
4863   // context. We'll be referencing this object when we refer to one of
4864   // its members.
4865   Owner->addDecl(Anon);
4866 
4867   // Inject the members of the anonymous struct/union into the owning
4868   // context and into the identifier resolver chain for name lookup
4869   // purposes.
4870   SmallVector<NamedDecl*, 2> Chain;
4871   Chain.push_back(Anon);
4872 
4873   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4874     Invalid = true;
4875 
4876   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4877     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4878       Decl *ManglingContextDecl;
4879       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4880               NewVD->getDeclContext(), ManglingContextDecl)) {
4881         Context.setManglingNumber(
4882             NewVD, MCtx->getManglingNumber(
4883                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4884         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4885       }
4886     }
4887   }
4888 
4889   if (Invalid)
4890     Anon->setInvalidDecl();
4891 
4892   return Anon;
4893 }
4894 
4895 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4896 /// Microsoft C anonymous structure.
4897 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4898 /// Example:
4899 ///
4900 /// struct A { int a; };
4901 /// struct B { struct A; int b; };
4902 ///
4903 /// void foo() {
4904 ///   B var;
4905 ///   var.a = 3;
4906 /// }
4907 ///
4908 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4909                                            RecordDecl *Record) {
4910   assert(Record && "expected a record!");
4911 
4912   // Mock up a declarator.
4913   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4914   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4915   assert(TInfo && "couldn't build declarator info for anonymous struct");
4916 
4917   auto *ParentDecl = cast<RecordDecl>(CurContext);
4918   QualType RecTy = Context.getTypeDeclType(Record);
4919 
4920   // Create a declaration for this anonymous struct.
4921   NamedDecl *Anon =
4922       FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4923                         /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4924                         /*BitWidth=*/nullptr, /*Mutable=*/false,
4925                         /*InitStyle=*/ICIS_NoInit);
4926   Anon->setImplicit();
4927 
4928   // Add the anonymous struct object to the current context.
4929   CurContext->addDecl(Anon);
4930 
4931   // Inject the members of the anonymous struct into the current
4932   // context and into the identifier resolver chain for name lookup
4933   // purposes.
4934   SmallVector<NamedDecl*, 2> Chain;
4935   Chain.push_back(Anon);
4936 
4937   RecordDecl *RecordDef = Record->getDefinition();
4938   if (RequireCompleteType(Anon->getLocation(), RecTy,
4939                           diag::err_field_incomplete) ||
4940       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4941                                           AS_none, Chain)) {
4942     Anon->setInvalidDecl();
4943     ParentDecl->setInvalidDecl();
4944   }
4945 
4946   return Anon;
4947 }
4948 
4949 /// GetNameForDeclarator - Determine the full declaration name for the
4950 /// given Declarator.
4951 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4952   return GetNameFromUnqualifiedId(D.getName());
4953 }
4954 
4955 /// Retrieves the declaration name from a parsed unqualified-id.
4956 DeclarationNameInfo
4957 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4958   DeclarationNameInfo NameInfo;
4959   NameInfo.setLoc(Name.StartLocation);
4960 
4961   switch (Name.getKind()) {
4962 
4963   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4964   case UnqualifiedIdKind::IK_Identifier:
4965     NameInfo.setName(Name.Identifier);
4966     return NameInfo;
4967 
4968   case UnqualifiedIdKind::IK_DeductionGuideName: {
4969     // C++ [temp.deduct.guide]p3:
4970     //   The simple-template-id shall name a class template specialization.
4971     //   The template-name shall be the same identifier as the template-name
4972     //   of the simple-template-id.
4973     // These together intend to imply that the template-name shall name a
4974     // class template.
4975     // FIXME: template<typename T> struct X {};
4976     //        template<typename T> using Y = X<T>;
4977     //        Y(int) -> Y<int>;
4978     //   satisfies these rules but does not name a class template.
4979     TemplateName TN = Name.TemplateName.get().get();
4980     auto *Template = TN.getAsTemplateDecl();
4981     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4982       Diag(Name.StartLocation,
4983            diag::err_deduction_guide_name_not_class_template)
4984         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4985       if (Template)
4986         Diag(Template->getLocation(), diag::note_template_decl_here);
4987       return DeclarationNameInfo();
4988     }
4989 
4990     NameInfo.setName(
4991         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4992     return NameInfo;
4993   }
4994 
4995   case UnqualifiedIdKind::IK_OperatorFunctionId:
4996     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4997                                            Name.OperatorFunctionId.Operator));
4998     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4999       = Name.OperatorFunctionId.SymbolLocations[0];
5000     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5001       = Name.EndLocation.getRawEncoding();
5002     return NameInfo;
5003 
5004   case UnqualifiedIdKind::IK_LiteralOperatorId:
5005     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5006                                                            Name.Identifier));
5007     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5008     return NameInfo;
5009 
5010   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5011     TypeSourceInfo *TInfo;
5012     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5013     if (Ty.isNull())
5014       return DeclarationNameInfo();
5015     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5016                                                Context.getCanonicalType(Ty)));
5017     NameInfo.setNamedTypeInfo(TInfo);
5018     return NameInfo;
5019   }
5020 
5021   case UnqualifiedIdKind::IK_ConstructorName: {
5022     TypeSourceInfo *TInfo;
5023     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5024     if (Ty.isNull())
5025       return DeclarationNameInfo();
5026     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5027                                               Context.getCanonicalType(Ty)));
5028     NameInfo.setNamedTypeInfo(TInfo);
5029     return NameInfo;
5030   }
5031 
5032   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5033     // In well-formed code, we can only have a constructor
5034     // template-id that refers to the current context, so go there
5035     // to find the actual type being constructed.
5036     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5037     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5038       return DeclarationNameInfo();
5039 
5040     // Determine the type of the class being constructed.
5041     QualType CurClassType = Context.getTypeDeclType(CurClass);
5042 
5043     // FIXME: Check two things: that the template-id names the same type as
5044     // CurClassType, and that the template-id does not occur when the name
5045     // was qualified.
5046 
5047     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5048                                     Context.getCanonicalType(CurClassType)));
5049     // FIXME: should we retrieve TypeSourceInfo?
5050     NameInfo.setNamedTypeInfo(nullptr);
5051     return NameInfo;
5052   }
5053 
5054   case UnqualifiedIdKind::IK_DestructorName: {
5055     TypeSourceInfo *TInfo;
5056     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5057     if (Ty.isNull())
5058       return DeclarationNameInfo();
5059     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5060                                               Context.getCanonicalType(Ty)));
5061     NameInfo.setNamedTypeInfo(TInfo);
5062     return NameInfo;
5063   }
5064 
5065   case UnqualifiedIdKind::IK_TemplateId: {
5066     TemplateName TName = Name.TemplateId->Template.get();
5067     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5068     return Context.getNameForTemplate(TName, TNameLoc);
5069   }
5070 
5071   } // switch (Name.getKind())
5072 
5073   llvm_unreachable("Unknown name kind");
5074 }
5075 
5076 static QualType getCoreType(QualType Ty) {
5077   do {
5078     if (Ty->isPointerType() || Ty->isReferenceType())
5079       Ty = Ty->getPointeeType();
5080     else if (Ty->isArrayType())
5081       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5082     else
5083       return Ty.withoutLocalFastQualifiers();
5084   } while (true);
5085 }
5086 
5087 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5088 /// and Definition have "nearly" matching parameters. This heuristic is
5089 /// used to improve diagnostics in the case where an out-of-line function
5090 /// definition doesn't match any declaration within the class or namespace.
5091 /// Also sets Params to the list of indices to the parameters that differ
5092 /// between the declaration and the definition. If hasSimilarParameters
5093 /// returns true and Params is empty, then all of the parameters match.
5094 static bool hasSimilarParameters(ASTContext &Context,
5095                                      FunctionDecl *Declaration,
5096                                      FunctionDecl *Definition,
5097                                      SmallVectorImpl<unsigned> &Params) {
5098   Params.clear();
5099   if (Declaration->param_size() != Definition->param_size())
5100     return false;
5101   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5102     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5103     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5104 
5105     // The parameter types are identical
5106     if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5107       continue;
5108 
5109     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5110     QualType DefParamBaseTy = getCoreType(DefParamTy);
5111     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5112     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5113 
5114     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5115         (DeclTyName && DeclTyName == DefTyName))
5116       Params.push_back(Idx);
5117     else  // The two parameters aren't even close
5118       return false;
5119   }
5120 
5121   return true;
5122 }
5123 
5124 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5125 /// declarator needs to be rebuilt in the current instantiation.
5126 /// Any bits of declarator which appear before the name are valid for
5127 /// consideration here.  That's specifically the type in the decl spec
5128 /// and the base type in any member-pointer chunks.
5129 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5130                                                     DeclarationName Name) {
5131   // The types we specifically need to rebuild are:
5132   //   - typenames, typeofs, and decltypes
5133   //   - types which will become injected class names
5134   // Of course, we also need to rebuild any type referencing such a
5135   // type.  It's safest to just say "dependent", but we call out a
5136   // few cases here.
5137 
5138   DeclSpec &DS = D.getMutableDeclSpec();
5139   switch (DS.getTypeSpecType()) {
5140   case DeclSpec::TST_typename:
5141   case DeclSpec::TST_typeofType:
5142   case DeclSpec::TST_underlyingType:
5143   case DeclSpec::TST_atomic: {
5144     // Grab the type from the parser.
5145     TypeSourceInfo *TSI = nullptr;
5146     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5147     if (T.isNull() || !T->isDependentType()) break;
5148 
5149     // Make sure there's a type source info.  This isn't really much
5150     // of a waste; most dependent types should have type source info
5151     // attached already.
5152     if (!TSI)
5153       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5154 
5155     // Rebuild the type in the current instantiation.
5156     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5157     if (!TSI) return true;
5158 
5159     // Store the new type back in the decl spec.
5160     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5161     DS.UpdateTypeRep(LocType);
5162     break;
5163   }
5164 
5165   case DeclSpec::TST_decltype:
5166   case DeclSpec::TST_typeofExpr: {
5167     Expr *E = DS.getRepAsExpr();
5168     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5169     if (Result.isInvalid()) return true;
5170     DS.UpdateExprRep(Result.get());
5171     break;
5172   }
5173 
5174   default:
5175     // Nothing to do for these decl specs.
5176     break;
5177   }
5178 
5179   // It doesn't matter what order we do this in.
5180   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5181     DeclaratorChunk &Chunk = D.getTypeObject(I);
5182 
5183     // The only type information in the declarator which can come
5184     // before the declaration name is the base type of a member
5185     // pointer.
5186     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5187       continue;
5188 
5189     // Rebuild the scope specifier in-place.
5190     CXXScopeSpec &SS = Chunk.Mem.Scope();
5191     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5192       return true;
5193   }
5194 
5195   return false;
5196 }
5197 
5198 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5199   D.setFunctionDefinitionKind(FDK_Declaration);
5200   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5201 
5202   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5203       Dcl && Dcl->getDeclContext()->isFileContext())
5204     Dcl->setTopLevelDeclInObjCContainer();
5205 
5206   if (getLangOpts().OpenCL)
5207     setCurrentOpenCLExtensionForDecl(Dcl);
5208 
5209   return Dcl;
5210 }
5211 
5212 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5213 ///   If T is the name of a class, then each of the following shall have a
5214 ///   name different from T:
5215 ///     - every static data member of class T;
5216 ///     - every member function of class T
5217 ///     - every member of class T that is itself a type;
5218 /// \returns true if the declaration name violates these rules.
5219 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5220                                    DeclarationNameInfo NameInfo) {
5221   DeclarationName Name = NameInfo.getName();
5222 
5223   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5224   while (Record && Record->isAnonymousStructOrUnion())
5225     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5226   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5227     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5228     return true;
5229   }
5230 
5231   return false;
5232 }
5233 
5234 /// Diagnose a declaration whose declarator-id has the given
5235 /// nested-name-specifier.
5236 ///
5237 /// \param SS The nested-name-specifier of the declarator-id.
5238 ///
5239 /// \param DC The declaration context to which the nested-name-specifier
5240 /// resolves.
5241 ///
5242 /// \param Name The name of the entity being declared.
5243 ///
5244 /// \param Loc The location of the name of the entity being declared.
5245 ///
5246 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5247 /// we're declaring an explicit / partial specialization / instantiation.
5248 ///
5249 /// \returns true if we cannot safely recover from this error, false otherwise.
5250 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5251                                         DeclarationName Name,
5252                                         SourceLocation Loc, bool IsTemplateId) {
5253   DeclContext *Cur = CurContext;
5254   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5255     Cur = Cur->getParent();
5256 
5257   // If the user provided a superfluous scope specifier that refers back to the
5258   // class in which the entity is already declared, diagnose and ignore it.
5259   //
5260   // class X {
5261   //   void X::f();
5262   // };
5263   //
5264   // Note, it was once ill-formed to give redundant qualification in all
5265   // contexts, but that rule was removed by DR482.
5266   if (Cur->Equals(DC)) {
5267     if (Cur->isRecord()) {
5268       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5269                                       : diag::err_member_extra_qualification)
5270         << Name << FixItHint::CreateRemoval(SS.getRange());
5271       SS.clear();
5272     } else {
5273       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5274     }
5275     return false;
5276   }
5277 
5278   // Check whether the qualifying scope encloses the scope of the original
5279   // declaration. For a template-id, we perform the checks in
5280   // CheckTemplateSpecializationScope.
5281   if (!Cur->Encloses(DC) && !IsTemplateId) {
5282     if (Cur->isRecord())
5283       Diag(Loc, diag::err_member_qualification)
5284         << Name << SS.getRange();
5285     else if (isa<TranslationUnitDecl>(DC))
5286       Diag(Loc, diag::err_invalid_declarator_global_scope)
5287         << Name << SS.getRange();
5288     else if (isa<FunctionDecl>(Cur))
5289       Diag(Loc, diag::err_invalid_declarator_in_function)
5290         << Name << SS.getRange();
5291     else if (isa<BlockDecl>(Cur))
5292       Diag(Loc, diag::err_invalid_declarator_in_block)
5293         << Name << SS.getRange();
5294     else
5295       Diag(Loc, diag::err_invalid_declarator_scope)
5296       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5297 
5298     return true;
5299   }
5300 
5301   if (Cur->isRecord()) {
5302     // Cannot qualify members within a class.
5303     Diag(Loc, diag::err_member_qualification)
5304       << Name << SS.getRange();
5305     SS.clear();
5306 
5307     // C++ constructors and destructors with incorrect scopes can break
5308     // our AST invariants by having the wrong underlying types. If
5309     // that's the case, then drop this declaration entirely.
5310     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5311          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5312         !Context.hasSameType(Name.getCXXNameType(),
5313                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5314       return true;
5315 
5316     return false;
5317   }
5318 
5319   // C++11 [dcl.meaning]p1:
5320   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5321   //   not begin with a decltype-specifer"
5322   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5323   while (SpecLoc.getPrefix())
5324     SpecLoc = SpecLoc.getPrefix();
5325   if (dyn_cast_or_null<DecltypeType>(
5326         SpecLoc.getNestedNameSpecifier()->getAsType()))
5327     Diag(Loc, diag::err_decltype_in_declarator)
5328       << SpecLoc.getTypeLoc().getSourceRange();
5329 
5330   return false;
5331 }
5332 
5333 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5334                                   MultiTemplateParamsArg TemplateParamLists) {
5335   // TODO: consider using NameInfo for diagnostic.
5336   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5337   DeclarationName Name = NameInfo.getName();
5338 
5339   // All of these full declarators require an identifier.  If it doesn't have
5340   // one, the ParsedFreeStandingDeclSpec action should be used.
5341   if (D.isDecompositionDeclarator()) {
5342     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5343   } else if (!Name) {
5344     if (!D.isInvalidType())  // Reject this if we think it is valid.
5345       Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5346           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5347     return nullptr;
5348   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5349     return nullptr;
5350 
5351   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5352   // we find one that is.
5353   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5354          (S->getFlags() & Scope::TemplateParamScope) != 0)
5355     S = S->getParent();
5356 
5357   DeclContext *DC = CurContext;
5358   if (D.getCXXScopeSpec().isInvalid())
5359     D.setInvalidType();
5360   else if (D.getCXXScopeSpec().isSet()) {
5361     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5362                                         UPPC_DeclarationQualifier))
5363       return nullptr;
5364 
5365     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5366     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5367     if (!DC || isa<EnumDecl>(DC)) {
5368       // If we could not compute the declaration context, it's because the
5369       // declaration context is dependent but does not refer to a class,
5370       // class template, or class template partial specialization. Complain
5371       // and return early, to avoid the coming semantic disaster.
5372       Diag(D.getIdentifierLoc(),
5373            diag::err_template_qualified_declarator_no_match)
5374         << D.getCXXScopeSpec().getScopeRep()
5375         << D.getCXXScopeSpec().getRange();
5376       return nullptr;
5377     }
5378     bool IsDependentContext = DC->isDependentContext();
5379 
5380     if (!IsDependentContext &&
5381         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5382       return nullptr;
5383 
5384     // If a class is incomplete, do not parse entities inside it.
5385     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5386       Diag(D.getIdentifierLoc(),
5387            diag::err_member_def_undefined_record)
5388         << Name << DC << D.getCXXScopeSpec().getRange();
5389       return nullptr;
5390     }
5391     if (!D.getDeclSpec().isFriendSpecified()) {
5392       if (diagnoseQualifiedDeclaration(
5393               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5394               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5395         if (DC->isRecord())
5396           return nullptr;
5397 
5398         D.setInvalidType();
5399       }
5400     }
5401 
5402     // Check whether we need to rebuild the type of the given
5403     // declaration in the current instantiation.
5404     if (EnteringContext && IsDependentContext &&
5405         TemplateParamLists.size() != 0) {
5406       ContextRAII SavedContext(*this, DC);
5407       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5408         D.setInvalidType();
5409     }
5410   }
5411 
5412   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5413   QualType R = TInfo->getType();
5414 
5415   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5416                                       UPPC_DeclarationType))
5417     D.setInvalidType();
5418 
5419   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5420                         forRedeclarationInCurContext());
5421 
5422   // See if this is a redefinition of a variable in the same scope.
5423   if (!D.getCXXScopeSpec().isSet()) {
5424     bool IsLinkageLookup = false;
5425     bool CreateBuiltins = false;
5426 
5427     // If the declaration we're planning to build will be a function
5428     // or object with linkage, then look for another declaration with
5429     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5430     //
5431     // If the declaration we're planning to build will be declared with
5432     // external linkage in the translation unit, create any builtin with
5433     // the same name.
5434     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5435       /* Do nothing*/;
5436     else if (CurContext->isFunctionOrMethod() &&
5437              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5438               R->isFunctionType())) {
5439       IsLinkageLookup = true;
5440       CreateBuiltins =
5441           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5442     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5443                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5444       CreateBuiltins = true;
5445 
5446     if (IsLinkageLookup) {
5447       Previous.clear(LookupRedeclarationWithLinkage);
5448       Previous.setRedeclarationKind(ForExternalRedeclaration);
5449     }
5450 
5451     LookupName(Previous, S, CreateBuiltins);
5452   } else { // Something like "int foo::x;"
5453     LookupQualifiedName(Previous, DC);
5454 
5455     // C++ [dcl.meaning]p1:
5456     //   When the declarator-id is qualified, the declaration shall refer to a
5457     //  previously declared member of the class or namespace to which the
5458     //  qualifier refers (or, in the case of a namespace, of an element of the
5459     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5460     //  thereof; [...]
5461     //
5462     // Note that we already checked the context above, and that we do not have
5463     // enough information to make sure that Previous contains the declaration
5464     // we want to match. For example, given:
5465     //
5466     //   class X {
5467     //     void f();
5468     //     void f(float);
5469     //   };
5470     //
5471     //   void X::f(int) { } // ill-formed
5472     //
5473     // In this case, Previous will point to the overload set
5474     // containing the two f's declared in X, but neither of them
5475     // matches.
5476 
5477     // C++ [dcl.meaning]p1:
5478     //   [...] the member shall not merely have been introduced by a
5479     //   using-declaration in the scope of the class or namespace nominated by
5480     //   the nested-name-specifier of the declarator-id.
5481     RemoveUsingDecls(Previous);
5482   }
5483 
5484   if (Previous.isSingleResult() &&
5485       Previous.getFoundDecl()->isTemplateParameter()) {
5486     // Maybe we will complain about the shadowed template parameter.
5487     if (!D.isInvalidType())
5488       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5489                                       Previous.getFoundDecl());
5490 
5491     // Just pretend that we didn't see the previous declaration.
5492     Previous.clear();
5493   }
5494 
5495   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5496     // Forget that the previous declaration is the injected-class-name.
5497     Previous.clear();
5498 
5499   // In C++, the previous declaration we find might be a tag type
5500   // (class or enum). In this case, the new declaration will hide the
5501   // tag type. Note that this applies to functions, function templates, and
5502   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5503   if (Previous.isSingleTagDecl() &&
5504       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5505       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5506     Previous.clear();
5507 
5508   // Check that there are no default arguments other than in the parameters
5509   // of a function declaration (C++ only).
5510   if (getLangOpts().CPlusPlus)
5511     CheckExtraCXXDefaultArguments(D);
5512 
5513   NamedDecl *New;
5514 
5515   bool AddToScope = true;
5516   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5517     if (TemplateParamLists.size()) {
5518       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5519       return nullptr;
5520     }
5521 
5522     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5523   } else if (R->isFunctionType()) {
5524     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5525                                   TemplateParamLists,
5526                                   AddToScope);
5527   } else {
5528     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5529                                   AddToScope);
5530   }
5531 
5532   if (!New)
5533     return nullptr;
5534 
5535   // If this has an identifier and is not a function template specialization,
5536   // add it to the scope stack.
5537   if (New->getDeclName() && AddToScope)
5538     PushOnScopeChains(New, S);
5539 
5540   if (isInOpenMPDeclareTargetContext())
5541     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5542 
5543   return New;
5544 }
5545 
5546 /// Helper method to turn variable array types into constant array
5547 /// types in certain situations which would otherwise be errors (for
5548 /// GCC compatibility).
5549 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5550                                                     ASTContext &Context,
5551                                                     bool &SizeIsNegative,
5552                                                     llvm::APSInt &Oversized) {
5553   // This method tries to turn a variable array into a constant
5554   // array even when the size isn't an ICE.  This is necessary
5555   // for compatibility with code that depends on gcc's buggy
5556   // constant expression folding, like struct {char x[(int)(char*)2];}
5557   SizeIsNegative = false;
5558   Oversized = 0;
5559 
5560   if (T->isDependentType())
5561     return QualType();
5562 
5563   QualifierCollector Qs;
5564   const Type *Ty = Qs.strip(T);
5565 
5566   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5567     QualType Pointee = PTy->getPointeeType();
5568     QualType FixedType =
5569         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5570                                             Oversized);
5571     if (FixedType.isNull()) return FixedType;
5572     FixedType = Context.getPointerType(FixedType);
5573     return Qs.apply(Context, FixedType);
5574   }
5575   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5576     QualType Inner = PTy->getInnerType();
5577     QualType FixedType =
5578         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5579                                             Oversized);
5580     if (FixedType.isNull()) return FixedType;
5581     FixedType = Context.getParenType(FixedType);
5582     return Qs.apply(Context, FixedType);
5583   }
5584 
5585   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5586   if (!VLATy)
5587     return QualType();
5588   // FIXME: We should probably handle this case
5589   if (VLATy->getElementType()->isVariablyModifiedType())
5590     return QualType();
5591 
5592   Expr::EvalResult Result;
5593   if (!VLATy->getSizeExpr() ||
5594       !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5595     return QualType();
5596 
5597   llvm::APSInt Res = Result.Val.getInt();
5598 
5599   // Check whether the array size is negative.
5600   if (Res.isSigned() && Res.isNegative()) {
5601     SizeIsNegative = true;
5602     return QualType();
5603   }
5604 
5605   // Check whether the array is too large to be addressed.
5606   unsigned ActiveSizeBits
5607     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5608                                               Res);
5609   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5610     Oversized = Res;
5611     return QualType();
5612   }
5613 
5614   return Context.getConstantArrayType(VLATy->getElementType(),
5615                                       Res, ArrayType::Normal, 0);
5616 }
5617 
5618 static void
5619 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5620   SrcTL = SrcTL.getUnqualifiedLoc();
5621   DstTL = DstTL.getUnqualifiedLoc();
5622   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5623     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5624     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5625                                       DstPTL.getPointeeLoc());
5626     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5627     return;
5628   }
5629   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5630     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5631     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5632                                       DstPTL.getInnerLoc());
5633     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5634     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5635     return;
5636   }
5637   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5638   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5639   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5640   TypeLoc DstElemTL = DstATL.getElementLoc();
5641   DstElemTL.initializeFullCopy(SrcElemTL);
5642   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5643   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5644   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5645 }
5646 
5647 /// Helper method to turn variable array types into constant array
5648 /// types in certain situations which would otherwise be errors (for
5649 /// GCC compatibility).
5650 static TypeSourceInfo*
5651 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5652                                               ASTContext &Context,
5653                                               bool &SizeIsNegative,
5654                                               llvm::APSInt &Oversized) {
5655   QualType FixedTy
5656     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5657                                           SizeIsNegative, Oversized);
5658   if (FixedTy.isNull())
5659     return nullptr;
5660   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5661   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5662                                     FixedTInfo->getTypeLoc());
5663   return FixedTInfo;
5664 }
5665 
5666 /// Register the given locally-scoped extern "C" declaration so
5667 /// that it can be found later for redeclarations. We include any extern "C"
5668 /// declaration that is not visible in the translation unit here, not just
5669 /// function-scope declarations.
5670 void
5671 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5672   if (!getLangOpts().CPlusPlus &&
5673       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5674     // Don't need to track declarations in the TU in C.
5675     return;
5676 
5677   // Note that we have a locally-scoped external with this name.
5678   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5679 }
5680 
5681 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5682   // FIXME: We can have multiple results via __attribute__((overloadable)).
5683   auto Result = Context.getExternCContextDecl()->lookup(Name);
5684   return Result.empty() ? nullptr : *Result.begin();
5685 }
5686 
5687 /// Diagnose function specifiers on a declaration of an identifier that
5688 /// does not identify a function.
5689 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5690   // FIXME: We should probably indicate the identifier in question to avoid
5691   // confusion for constructs like "virtual int a(), b;"
5692   if (DS.isVirtualSpecified())
5693     Diag(DS.getVirtualSpecLoc(),
5694          diag::err_virtual_non_function);
5695 
5696   if (DS.isExplicitSpecified())
5697     Diag(DS.getExplicitSpecLoc(),
5698          diag::err_explicit_non_function);
5699 
5700   if (DS.isNoreturnSpecified())
5701     Diag(DS.getNoreturnSpecLoc(),
5702          diag::err_noreturn_non_function);
5703 }
5704 
5705 NamedDecl*
5706 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5707                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5708   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5709   if (D.getCXXScopeSpec().isSet()) {
5710     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5711       << D.getCXXScopeSpec().getRange();
5712     D.setInvalidType();
5713     // Pretend we didn't see the scope specifier.
5714     DC = CurContext;
5715     Previous.clear();
5716   }
5717 
5718   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5719 
5720   if (D.getDeclSpec().isInlineSpecified())
5721     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5722         << getLangOpts().CPlusPlus17;
5723   if (D.getDeclSpec().isConstexprSpecified())
5724     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5725       << 1;
5726 
5727   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5728     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5729       Diag(D.getName().StartLocation,
5730            diag::err_deduction_guide_invalid_specifier)
5731           << "typedef";
5732     else
5733       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5734           << D.getName().getSourceRange();
5735     return nullptr;
5736   }
5737 
5738   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5739   if (!NewTD) return nullptr;
5740 
5741   // Handle attributes prior to checking for duplicates in MergeVarDecl
5742   ProcessDeclAttributes(S, NewTD, D);
5743 
5744   CheckTypedefForVariablyModifiedType(S, NewTD);
5745 
5746   bool Redeclaration = D.isRedeclaration();
5747   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5748   D.setRedeclaration(Redeclaration);
5749   return ND;
5750 }
5751 
5752 void
5753 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5754   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5755   // then it shall have block scope.
5756   // Note that variably modified types must be fixed before merging the decl so
5757   // that redeclarations will match.
5758   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5759   QualType T = TInfo->getType();
5760   if (T->isVariablyModifiedType()) {
5761     setFunctionHasBranchProtectedScope();
5762 
5763     if (S->getFnParent() == nullptr) {
5764       bool SizeIsNegative;
5765       llvm::APSInt Oversized;
5766       TypeSourceInfo *FixedTInfo =
5767         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5768                                                       SizeIsNegative,
5769                                                       Oversized);
5770       if (FixedTInfo) {
5771         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5772         NewTD->setTypeSourceInfo(FixedTInfo);
5773       } else {
5774         if (SizeIsNegative)
5775           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5776         else if (T->isVariableArrayType())
5777           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5778         else if (Oversized.getBoolValue())
5779           Diag(NewTD->getLocation(), diag::err_array_too_large)
5780             << Oversized.toString(10);
5781         else
5782           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5783         NewTD->setInvalidDecl();
5784       }
5785     }
5786   }
5787 }
5788 
5789 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5790 /// declares a typedef-name, either using the 'typedef' type specifier or via
5791 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5792 NamedDecl*
5793 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5794                            LookupResult &Previous, bool &Redeclaration) {
5795 
5796   // Find the shadowed declaration before filtering for scope.
5797   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5798 
5799   // Merge the decl with the existing one if appropriate. If the decl is
5800   // in an outer scope, it isn't the same thing.
5801   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5802                        /*AllowInlineNamespace*/false);
5803   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5804   if (!Previous.empty()) {
5805     Redeclaration = true;
5806     MergeTypedefNameDecl(S, NewTD, Previous);
5807   }
5808 
5809   if (ShadowedDecl && !Redeclaration)
5810     CheckShadow(NewTD, ShadowedDecl, Previous);
5811 
5812   // If this is the C FILE type, notify the AST context.
5813   if (IdentifierInfo *II = NewTD->getIdentifier())
5814     if (!NewTD->isInvalidDecl() &&
5815         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5816       if (II->isStr("FILE"))
5817         Context.setFILEDecl(NewTD);
5818       else if (II->isStr("jmp_buf"))
5819         Context.setjmp_bufDecl(NewTD);
5820       else if (II->isStr("sigjmp_buf"))
5821         Context.setsigjmp_bufDecl(NewTD);
5822       else if (II->isStr("ucontext_t"))
5823         Context.setucontext_tDecl(NewTD);
5824     }
5825 
5826   return NewTD;
5827 }
5828 
5829 /// Determines whether the given declaration is an out-of-scope
5830 /// previous declaration.
5831 ///
5832 /// This routine should be invoked when name lookup has found a
5833 /// previous declaration (PrevDecl) that is not in the scope where a
5834 /// new declaration by the same name is being introduced. If the new
5835 /// declaration occurs in a local scope, previous declarations with
5836 /// linkage may still be considered previous declarations (C99
5837 /// 6.2.2p4-5, C++ [basic.link]p6).
5838 ///
5839 /// \param PrevDecl the previous declaration found by name
5840 /// lookup
5841 ///
5842 /// \param DC the context in which the new declaration is being
5843 /// declared.
5844 ///
5845 /// \returns true if PrevDecl is an out-of-scope previous declaration
5846 /// for a new delcaration with the same name.
5847 static bool
5848 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5849                                 ASTContext &Context) {
5850   if (!PrevDecl)
5851     return false;
5852 
5853   if (!PrevDecl->hasLinkage())
5854     return false;
5855 
5856   if (Context.getLangOpts().CPlusPlus) {
5857     // C++ [basic.link]p6:
5858     //   If there is a visible declaration of an entity with linkage
5859     //   having the same name and type, ignoring entities declared
5860     //   outside the innermost enclosing namespace scope, the block
5861     //   scope declaration declares that same entity and receives the
5862     //   linkage of the previous declaration.
5863     DeclContext *OuterContext = DC->getRedeclContext();
5864     if (!OuterContext->isFunctionOrMethod())
5865       // This rule only applies to block-scope declarations.
5866       return false;
5867 
5868     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5869     if (PrevOuterContext->isRecord())
5870       // We found a member function: ignore it.
5871       return false;
5872 
5873     // Find the innermost enclosing namespace for the new and
5874     // previous declarations.
5875     OuterContext = OuterContext->getEnclosingNamespaceContext();
5876     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5877 
5878     // The previous declaration is in a different namespace, so it
5879     // isn't the same function.
5880     if (!OuterContext->Equals(PrevOuterContext))
5881       return false;
5882   }
5883 
5884   return true;
5885 }
5886 
5887 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
5888   CXXScopeSpec &SS = D.getCXXScopeSpec();
5889   if (!SS.isSet()) return;
5890   DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5891 }
5892 
5893 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5894   QualType type = decl->getType();
5895   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5896   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5897     // Various kinds of declaration aren't allowed to be __autoreleasing.
5898     unsigned kind = -1U;
5899     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5900       if (var->hasAttr<BlocksAttr>())
5901         kind = 0; // __block
5902       else if (!var->hasLocalStorage())
5903         kind = 1; // global
5904     } else if (isa<ObjCIvarDecl>(decl)) {
5905       kind = 3; // ivar
5906     } else if (isa<FieldDecl>(decl)) {
5907       kind = 2; // field
5908     }
5909 
5910     if (kind != -1U) {
5911       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5912         << kind;
5913     }
5914   } else if (lifetime == Qualifiers::OCL_None) {
5915     // Try to infer lifetime.
5916     if (!type->isObjCLifetimeType())
5917       return false;
5918 
5919     lifetime = type->getObjCARCImplicitLifetime();
5920     type = Context.getLifetimeQualifiedType(type, lifetime);
5921     decl->setType(type);
5922   }
5923 
5924   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5925     // Thread-local variables cannot have lifetime.
5926     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5927         var->getTLSKind()) {
5928       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5929         << var->getType();
5930       return true;
5931     }
5932   }
5933 
5934   return false;
5935 }
5936 
5937 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5938   // Ensure that an auto decl is deduced otherwise the checks below might cache
5939   // the wrong linkage.
5940   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5941 
5942   // 'weak' only applies to declarations with external linkage.
5943   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5944     if (!ND.isExternallyVisible()) {
5945       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5946       ND.dropAttr<WeakAttr>();
5947     }
5948   }
5949   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5950     if (ND.isExternallyVisible()) {
5951       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5952       ND.dropAttr<WeakRefAttr>();
5953       ND.dropAttr<AliasAttr>();
5954     }
5955   }
5956 
5957   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5958     if (VD->hasInit()) {
5959       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5960         assert(VD->isThisDeclarationADefinition() &&
5961                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5962         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5963         VD->dropAttr<AliasAttr>();
5964       }
5965     }
5966   }
5967 
5968   // 'selectany' only applies to externally visible variable declarations.
5969   // It does not apply to functions.
5970   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5971     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5972       S.Diag(Attr->getLocation(),
5973              diag::err_attribute_selectany_non_extern_data);
5974       ND.dropAttr<SelectAnyAttr>();
5975     }
5976   }
5977 
5978   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5979     auto *VD = dyn_cast<VarDecl>(&ND);
5980     bool IsAnonymousNS = false;
5981     bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5982     if (VD) {
5983       const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
5984       while (NS && !IsAnonymousNS) {
5985         IsAnonymousNS = NS->isAnonymousNamespace();
5986         NS = dyn_cast<NamespaceDecl>(NS->getParent());
5987       }
5988     }
5989     // dll attributes require external linkage. Static locals may have external
5990     // linkage but still cannot be explicitly imported or exported.
5991     // In Microsoft mode, a variable defined in anonymous namespace must have
5992     // external linkage in order to be exported.
5993     bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
5994     if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
5995         (!AnonNSInMicrosoftMode &&
5996          (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
5997       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5998         << &ND << Attr;
5999       ND.setInvalidDecl();
6000     }
6001   }
6002 
6003   // Virtual functions cannot be marked as 'notail'.
6004   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6005     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6006       if (MD->isVirtual()) {
6007         S.Diag(ND.getLocation(),
6008                diag::err_invalid_attribute_on_virtual_function)
6009             << Attr;
6010         ND.dropAttr<NotTailCalledAttr>();
6011       }
6012 
6013   // Check the attributes on the function type, if any.
6014   if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6015     // Don't declare this variable in the second operand of the for-statement;
6016     // GCC miscompiles that by ending its lifetime before evaluating the
6017     // third operand. See gcc.gnu.org/PR86769.
6018     AttributedTypeLoc ATL;
6019     for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6020          (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6021          TL = ATL.getModifiedLoc()) {
6022       // The [[lifetimebound]] attribute can be applied to the implicit object
6023       // parameter of a non-static member function (other than a ctor or dtor)
6024       // by applying it to the function type.
6025       if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6026         const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6027         if (!MD || MD->isStatic()) {
6028           S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6029               << !MD << A->getRange();
6030         } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6031           S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6032               << isa<CXXDestructorDecl>(MD) << A->getRange();
6033         }
6034       }
6035     }
6036   }
6037 }
6038 
6039 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6040                                            NamedDecl *NewDecl,
6041                                            bool IsSpecialization,
6042                                            bool IsDefinition) {
6043   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6044     return;
6045 
6046   bool IsTemplate = false;
6047   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6048     OldDecl = OldTD->getTemplatedDecl();
6049     IsTemplate = true;
6050     if (!IsSpecialization)
6051       IsDefinition = false;
6052   }
6053   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6054     NewDecl = NewTD->getTemplatedDecl();
6055     IsTemplate = true;
6056   }
6057 
6058   if (!OldDecl || !NewDecl)
6059     return;
6060 
6061   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6062   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6063   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6064   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6065 
6066   // dllimport and dllexport are inheritable attributes so we have to exclude
6067   // inherited attribute instances.
6068   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6069                     (NewExportAttr && !NewExportAttr->isInherited());
6070 
6071   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6072   // the only exception being explicit specializations.
6073   // Implicitly generated declarations are also excluded for now because there
6074   // is no other way to switch these to use dllimport or dllexport.
6075   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6076 
6077   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6078     // Allow with a warning for free functions and global variables.
6079     bool JustWarn = false;
6080     if (!OldDecl->isCXXClassMember()) {
6081       auto *VD = dyn_cast<VarDecl>(OldDecl);
6082       if (VD && !VD->getDescribedVarTemplate())
6083         JustWarn = true;
6084       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6085       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6086         JustWarn = true;
6087     }
6088 
6089     // We cannot change a declaration that's been used because IR has already
6090     // been emitted. Dllimported functions will still work though (modulo
6091     // address equality) as they can use the thunk.
6092     if (OldDecl->isUsed())
6093       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6094         JustWarn = false;
6095 
6096     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6097                                : diag::err_attribute_dll_redeclaration;
6098     S.Diag(NewDecl->getLocation(), DiagID)
6099         << NewDecl
6100         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6101     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6102     if (!JustWarn) {
6103       NewDecl->setInvalidDecl();
6104       return;
6105     }
6106   }
6107 
6108   // A redeclaration is not allowed to drop a dllimport attribute, the only
6109   // exceptions being inline function definitions (except for function
6110   // templates), local extern declarations, qualified friend declarations or
6111   // special MSVC extension: in the last case, the declaration is treated as if
6112   // it were marked dllexport.
6113   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6114   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6115   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6116     // Ignore static data because out-of-line definitions are diagnosed
6117     // separately.
6118     IsStaticDataMember = VD->isStaticDataMember();
6119     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6120                    VarDecl::DeclarationOnly;
6121   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6122     IsInline = FD->isInlined();
6123     IsQualifiedFriend = FD->getQualifier() &&
6124                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6125   }
6126 
6127   if (OldImportAttr && !HasNewAttr &&
6128       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6129       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6130     if (IsMicrosoft && IsDefinition) {
6131       S.Diag(NewDecl->getLocation(),
6132              diag::warn_redeclaration_without_import_attribute)
6133           << NewDecl;
6134       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6135       NewDecl->dropAttr<DLLImportAttr>();
6136       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6137           NewImportAttr->getRange(), S.Context,
6138           NewImportAttr->getSpellingListIndex()));
6139     } else {
6140       S.Diag(NewDecl->getLocation(),
6141              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6142           << NewDecl << OldImportAttr;
6143       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6144       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6145       OldDecl->dropAttr<DLLImportAttr>();
6146       NewDecl->dropAttr<DLLImportAttr>();
6147     }
6148   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6149     // In MinGW, seeing a function declared inline drops the dllimport
6150     // attribute.
6151     OldDecl->dropAttr<DLLImportAttr>();
6152     NewDecl->dropAttr<DLLImportAttr>();
6153     S.Diag(NewDecl->getLocation(),
6154            diag::warn_dllimport_dropped_from_inline_function)
6155         << NewDecl << OldImportAttr;
6156   }
6157 
6158   // A specialization of a class template member function is processed here
6159   // since it's a redeclaration. If the parent class is dllexport, the
6160   // specialization inherits that attribute. This doesn't happen automatically
6161   // since the parent class isn't instantiated until later.
6162   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6163     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6164         !NewImportAttr && !NewExportAttr) {
6165       if (const DLLExportAttr *ParentExportAttr =
6166               MD->getParent()->getAttr<DLLExportAttr>()) {
6167         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6168         NewAttr->setInherited(true);
6169         NewDecl->addAttr(NewAttr);
6170       }
6171     }
6172   }
6173 }
6174 
6175 /// Given that we are within the definition of the given function,
6176 /// will that definition behave like C99's 'inline', where the
6177 /// definition is discarded except for optimization purposes?
6178 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6179   // Try to avoid calling GetGVALinkageForFunction.
6180 
6181   // All cases of this require the 'inline' keyword.
6182   if (!FD->isInlined()) return false;
6183 
6184   // This is only possible in C++ with the gnu_inline attribute.
6185   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6186     return false;
6187 
6188   // Okay, go ahead and call the relatively-more-expensive function.
6189   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6190 }
6191 
6192 /// Determine whether a variable is extern "C" prior to attaching
6193 /// an initializer. We can't just call isExternC() here, because that
6194 /// will also compute and cache whether the declaration is externally
6195 /// visible, which might change when we attach the initializer.
6196 ///
6197 /// This can only be used if the declaration is known to not be a
6198 /// redeclaration of an internal linkage declaration.
6199 ///
6200 /// For instance:
6201 ///
6202 ///   auto x = []{};
6203 ///
6204 /// Attaching the initializer here makes this declaration not externally
6205 /// visible, because its type has internal linkage.
6206 ///
6207 /// FIXME: This is a hack.
6208 template<typename T>
6209 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6210   if (S.getLangOpts().CPlusPlus) {
6211     // In C++, the overloadable attribute negates the effects of extern "C".
6212     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6213       return false;
6214 
6215     // So do CUDA's host/device attributes.
6216     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6217                                  D->template hasAttr<CUDAHostAttr>()))
6218       return false;
6219   }
6220   return D->isExternC();
6221 }
6222 
6223 static bool shouldConsiderLinkage(const VarDecl *VD) {
6224   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6225   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6226       isa<OMPDeclareMapperDecl>(DC))
6227     return VD->hasExternalStorage();
6228   if (DC->isFileContext())
6229     return true;
6230   if (DC->isRecord())
6231     return false;
6232   llvm_unreachable("Unexpected context");
6233 }
6234 
6235 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6236   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6237   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6238       isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6239     return true;
6240   if (DC->isRecord())
6241     return false;
6242   llvm_unreachable("Unexpected context");
6243 }
6244 
6245 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6246                           ParsedAttr::Kind Kind) {
6247   // Check decl attributes on the DeclSpec.
6248   if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6249     return true;
6250 
6251   // Walk the declarator structure, checking decl attributes that were in a type
6252   // position to the decl itself.
6253   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6254     if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6255       return true;
6256   }
6257 
6258   // Finally, check attributes on the decl itself.
6259   return PD.getAttributes().hasAttribute(Kind);
6260 }
6261 
6262 /// Adjust the \c DeclContext for a function or variable that might be a
6263 /// function-local external declaration.
6264 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6265   if (!DC->isFunctionOrMethod())
6266     return false;
6267 
6268   // If this is a local extern function or variable declared within a function
6269   // template, don't add it into the enclosing namespace scope until it is
6270   // instantiated; it might have a dependent type right now.
6271   if (DC->isDependentContext())
6272     return true;
6273 
6274   // C++11 [basic.link]p7:
6275   //   When a block scope declaration of an entity with linkage is not found to
6276   //   refer to some other declaration, then that entity is a member of the
6277   //   innermost enclosing namespace.
6278   //
6279   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6280   // semantically-enclosing namespace, not a lexically-enclosing one.
6281   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6282     DC = DC->getParent();
6283   return true;
6284 }
6285 
6286 /// Returns true if given declaration has external C language linkage.
6287 static bool isDeclExternC(const Decl *D) {
6288   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6289     return FD->isExternC();
6290   if (const auto *VD = dyn_cast<VarDecl>(D))
6291     return VD->isExternC();
6292 
6293   llvm_unreachable("Unknown type of decl!");
6294 }
6295 
6296 NamedDecl *Sema::ActOnVariableDeclarator(
6297     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6298     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6299     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6300   QualType R = TInfo->getType();
6301   DeclarationName Name = GetNameForDeclarator(D).getName();
6302 
6303   IdentifierInfo *II = Name.getAsIdentifierInfo();
6304 
6305   if (D.isDecompositionDeclarator()) {
6306     // Take the name of the first declarator as our name for diagnostic
6307     // purposes.
6308     auto &Decomp = D.getDecompositionDeclarator();
6309     if (!Decomp.bindings().empty()) {
6310       II = Decomp.bindings()[0].Name;
6311       Name = II;
6312     }
6313   } else if (!II) {
6314     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6315     return nullptr;
6316   }
6317 
6318   if (getLangOpts().OpenCL) {
6319     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6320     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6321     // argument.
6322     if (R->isImageType() || R->isPipeType()) {
6323       Diag(D.getIdentifierLoc(),
6324            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6325           << R;
6326       D.setInvalidType();
6327       return nullptr;
6328     }
6329 
6330     // OpenCL v1.2 s6.9.r:
6331     // The event type cannot be used to declare a program scope variable.
6332     // OpenCL v2.0 s6.9.q:
6333     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6334     if (NULL == S->getParent()) {
6335       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6336         Diag(D.getIdentifierLoc(),
6337              diag::err_invalid_type_for_program_scope_var) << R;
6338         D.setInvalidType();
6339         return nullptr;
6340       }
6341     }
6342 
6343     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6344     QualType NR = R;
6345     while (NR->isPointerType()) {
6346       if (NR->isFunctionPointerType()) {
6347         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6348         D.setInvalidType();
6349         break;
6350       }
6351       NR = NR->getPointeeType();
6352     }
6353 
6354     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6355       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6356       // half array type (unless the cl_khr_fp16 extension is enabled).
6357       if (Context.getBaseElementType(R)->isHalfType()) {
6358         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6359         D.setInvalidType();
6360       }
6361     }
6362 
6363     if (R->isSamplerT()) {
6364       // OpenCL v1.2 s6.9.b p4:
6365       // The sampler type cannot be used with the __local and __global address
6366       // space qualifiers.
6367       if (R.getAddressSpace() == LangAS::opencl_local ||
6368           R.getAddressSpace() == LangAS::opencl_global) {
6369         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6370       }
6371 
6372       // OpenCL v1.2 s6.12.14.1:
6373       // A global sampler must be declared with either the constant address
6374       // space qualifier or with the const qualifier.
6375       if (DC->isTranslationUnit() &&
6376           !(R.getAddressSpace() == LangAS::opencl_constant ||
6377           R.isConstQualified())) {
6378         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6379         D.setInvalidType();
6380       }
6381     }
6382 
6383     // OpenCL v1.2 s6.9.r:
6384     // The event type cannot be used with the __local, __constant and __global
6385     // address space qualifiers.
6386     if (R->isEventT()) {
6387       if (R.getAddressSpace() != LangAS::opencl_private) {
6388         Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6389         D.setInvalidType();
6390       }
6391     }
6392 
6393     // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6394     // supported.  OpenCL C does not support thread_local either, and
6395     // also reject all other thread storage class specifiers.
6396     DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6397     if (TSC != TSCS_unspecified) {
6398       bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6399       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6400            diag::err_opencl_unknown_type_specifier)
6401           << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6402           << DeclSpec::getSpecifierName(TSC) << 1;
6403       D.setInvalidType();
6404       return nullptr;
6405     }
6406   }
6407 
6408   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6409   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6410 
6411   // dllimport globals without explicit storage class are treated as extern. We
6412   // have to change the storage class this early to get the right DeclContext.
6413   if (SC == SC_None && !DC->isRecord() &&
6414       hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6415       !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6416     SC = SC_Extern;
6417 
6418   DeclContext *OriginalDC = DC;
6419   bool IsLocalExternDecl = SC == SC_Extern &&
6420                            adjustContextForLocalExternDecl(DC);
6421 
6422   if (SCSpec == DeclSpec::SCS_mutable) {
6423     // mutable can only appear on non-static class members, so it's always
6424     // an error here
6425     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6426     D.setInvalidType();
6427     SC = SC_None;
6428   }
6429 
6430   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6431       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6432                               D.getDeclSpec().getStorageClassSpecLoc())) {
6433     // In C++11, the 'register' storage class specifier is deprecated.
6434     // Suppress the warning in system macros, it's used in macros in some
6435     // popular C system headers, such as in glibc's htonl() macro.
6436     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6437          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6438                                    : diag::warn_deprecated_register)
6439       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6440   }
6441 
6442   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6443 
6444   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6445     // C99 6.9p2: The storage-class specifiers auto and register shall not
6446     // appear in the declaration specifiers in an external declaration.
6447     // Global Register+Asm is a GNU extension we support.
6448     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6449       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6450       D.setInvalidType();
6451     }
6452   }
6453 
6454   bool IsMemberSpecialization = false;
6455   bool IsVariableTemplateSpecialization = false;
6456   bool IsPartialSpecialization = false;
6457   bool IsVariableTemplate = false;
6458   VarDecl *NewVD = nullptr;
6459   VarTemplateDecl *NewTemplate = nullptr;
6460   TemplateParameterList *TemplateParams = nullptr;
6461   if (!getLangOpts().CPlusPlus) {
6462     NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6463                             II, R, TInfo, SC);
6464 
6465     if (R->getContainedDeducedType())
6466       ParsingInitForAutoVars.insert(NewVD);
6467 
6468     if (D.isInvalidType())
6469       NewVD->setInvalidDecl();
6470   } else {
6471     bool Invalid = false;
6472 
6473     if (DC->isRecord() && !CurContext->isRecord()) {
6474       // This is an out-of-line definition of a static data member.
6475       switch (SC) {
6476       case SC_None:
6477         break;
6478       case SC_Static:
6479         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6480              diag::err_static_out_of_line)
6481           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6482         break;
6483       case SC_Auto:
6484       case SC_Register:
6485       case SC_Extern:
6486         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6487         // to names of variables declared in a block or to function parameters.
6488         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6489         // of class members
6490 
6491         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6492              diag::err_storage_class_for_static_member)
6493           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6494         break;
6495       case SC_PrivateExtern:
6496         llvm_unreachable("C storage class in c++!");
6497       }
6498     }
6499 
6500     if (SC == SC_Static && CurContext->isRecord()) {
6501       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6502         if (RD->isLocalClass())
6503           Diag(D.getIdentifierLoc(),
6504                diag::err_static_data_member_not_allowed_in_local_class)
6505             << Name << RD->getDeclName();
6506 
6507         // C++98 [class.union]p1: If a union contains a static data member,
6508         // the program is ill-formed. C++11 drops this restriction.
6509         if (RD->isUnion())
6510           Diag(D.getIdentifierLoc(),
6511                getLangOpts().CPlusPlus11
6512                  ? diag::warn_cxx98_compat_static_data_member_in_union
6513                  : diag::ext_static_data_member_in_union) << Name;
6514         // We conservatively disallow static data members in anonymous structs.
6515         else if (!RD->getDeclName())
6516           Diag(D.getIdentifierLoc(),
6517                diag::err_static_data_member_not_allowed_in_anon_struct)
6518             << Name << RD->isUnion();
6519       }
6520     }
6521 
6522     // Match up the template parameter lists with the scope specifier, then
6523     // determine whether we have a template or a template specialization.
6524     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6525         D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6526         D.getCXXScopeSpec(),
6527         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6528             ? D.getName().TemplateId
6529             : nullptr,
6530         TemplateParamLists,
6531         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6532 
6533     if (TemplateParams) {
6534       if (!TemplateParams->size() &&
6535           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6536         // There is an extraneous 'template<>' for this variable. Complain
6537         // about it, but allow the declaration of the variable.
6538         Diag(TemplateParams->getTemplateLoc(),
6539              diag::err_template_variable_noparams)
6540           << II
6541           << SourceRange(TemplateParams->getTemplateLoc(),
6542                          TemplateParams->getRAngleLoc());
6543         TemplateParams = nullptr;
6544       } else {
6545         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6546           // This is an explicit specialization or a partial specialization.
6547           // FIXME: Check that we can declare a specialization here.
6548           IsVariableTemplateSpecialization = true;
6549           IsPartialSpecialization = TemplateParams->size() > 0;
6550         } else { // if (TemplateParams->size() > 0)
6551           // This is a template declaration.
6552           IsVariableTemplate = true;
6553 
6554           // Check that we can declare a template here.
6555           if (CheckTemplateDeclScope(S, TemplateParams))
6556             return nullptr;
6557 
6558           // Only C++1y supports variable templates (N3651).
6559           Diag(D.getIdentifierLoc(),
6560                getLangOpts().CPlusPlus14
6561                    ? diag::warn_cxx11_compat_variable_template
6562                    : diag::ext_variable_template);
6563         }
6564       }
6565     } else {
6566       assert((Invalid ||
6567               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6568              "should have a 'template<>' for this decl");
6569     }
6570 
6571     if (IsVariableTemplateSpecialization) {
6572       SourceLocation TemplateKWLoc =
6573           TemplateParamLists.size() > 0
6574               ? TemplateParamLists[0]->getTemplateLoc()
6575               : SourceLocation();
6576       DeclResult Res = ActOnVarTemplateSpecialization(
6577           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6578           IsPartialSpecialization);
6579       if (Res.isInvalid())
6580         return nullptr;
6581       NewVD = cast<VarDecl>(Res.get());
6582       AddToScope = false;
6583     } else if (D.isDecompositionDeclarator()) {
6584       NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6585                                         D.getIdentifierLoc(), R, TInfo, SC,
6586                                         Bindings);
6587     } else
6588       NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
6589                               D.getIdentifierLoc(), II, R, TInfo, SC);
6590 
6591     // If this is supposed to be a variable template, create it as such.
6592     if (IsVariableTemplate) {
6593       NewTemplate =
6594           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6595                                   TemplateParams, NewVD);
6596       NewVD->setDescribedVarTemplate(NewTemplate);
6597     }
6598 
6599     // If this decl has an auto type in need of deduction, make a note of the
6600     // Decl so we can diagnose uses of it in its own initializer.
6601     if (R->getContainedDeducedType())
6602       ParsingInitForAutoVars.insert(NewVD);
6603 
6604     if (D.isInvalidType() || Invalid) {
6605       NewVD->setInvalidDecl();
6606       if (NewTemplate)
6607         NewTemplate->setInvalidDecl();
6608     }
6609 
6610     SetNestedNameSpecifier(*this, NewVD, D);
6611 
6612     // If we have any template parameter lists that don't directly belong to
6613     // the variable (matching the scope specifier), store them.
6614     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6615     if (TemplateParamLists.size() > VDTemplateParamLists)
6616       NewVD->setTemplateParameterListsInfo(
6617           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6618 
6619     if (D.getDeclSpec().isConstexprSpecified()) {
6620       NewVD->setConstexpr(true);
6621       // C++1z [dcl.spec.constexpr]p1:
6622       //   A static data member declared with the constexpr specifier is
6623       //   implicitly an inline variable.
6624       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6625         NewVD->setImplicitlyInline();
6626     }
6627   }
6628 
6629   if (D.getDeclSpec().isInlineSpecified()) {
6630     if (!getLangOpts().CPlusPlus) {
6631       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6632           << 0;
6633     } else if (CurContext->isFunctionOrMethod()) {
6634       // 'inline' is not allowed on block scope variable declaration.
6635       Diag(D.getDeclSpec().getInlineSpecLoc(),
6636            diag::err_inline_declaration_block_scope) << Name
6637         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6638     } else {
6639       Diag(D.getDeclSpec().getInlineSpecLoc(),
6640            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6641                                      : diag::ext_inline_variable);
6642       NewVD->setInlineSpecified();
6643     }
6644   }
6645 
6646   // Set the lexical context. If the declarator has a C++ scope specifier, the
6647   // lexical context will be different from the semantic context.
6648   NewVD->setLexicalDeclContext(CurContext);
6649   if (NewTemplate)
6650     NewTemplate->setLexicalDeclContext(CurContext);
6651 
6652   if (IsLocalExternDecl) {
6653     if (D.isDecompositionDeclarator())
6654       for (auto *B : Bindings)
6655         B->setLocalExternDecl();
6656     else
6657       NewVD->setLocalExternDecl();
6658   }
6659 
6660   bool EmitTLSUnsupportedError = false;
6661   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6662     // C++11 [dcl.stc]p4:
6663     //   When thread_local is applied to a variable of block scope the
6664     //   storage-class-specifier static is implied if it does not appear
6665     //   explicitly.
6666     // Core issue: 'static' is not implied if the variable is declared
6667     //   'extern'.
6668     if (NewVD->hasLocalStorage() &&
6669         (SCSpec != DeclSpec::SCS_unspecified ||
6670          TSCS != DeclSpec::TSCS_thread_local ||
6671          !DC->isFunctionOrMethod()))
6672       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6673            diag::err_thread_non_global)
6674         << DeclSpec::getSpecifierName(TSCS);
6675     else if (!Context.getTargetInfo().isTLSSupported()) {
6676       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6677         // Postpone error emission until we've collected attributes required to
6678         // figure out whether it's a host or device variable and whether the
6679         // error should be ignored.
6680         EmitTLSUnsupportedError = true;
6681         // We still need to mark the variable as TLS so it shows up in AST with
6682         // proper storage class for other tools to use even if we're not going
6683         // to emit any code for it.
6684         NewVD->setTSCSpec(TSCS);
6685       } else
6686         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6687              diag::err_thread_unsupported);
6688     } else
6689       NewVD->setTSCSpec(TSCS);
6690   }
6691 
6692   // C99 6.7.4p3
6693   //   An inline definition of a function with external linkage shall
6694   //   not contain a definition of a modifiable object with static or
6695   //   thread storage duration...
6696   // We only apply this when the function is required to be defined
6697   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6698   // that a local variable with thread storage duration still has to
6699   // be marked 'static'.  Also note that it's possible to get these
6700   // semantics in C++ using __attribute__((gnu_inline)).
6701   if (SC == SC_Static && S->getFnParent() != nullptr &&
6702       !NewVD->getType().isConstQualified()) {
6703     FunctionDecl *CurFD = getCurFunctionDecl();
6704     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6705       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6706            diag::warn_static_local_in_extern_inline);
6707       MaybeSuggestAddingStaticToDecl(CurFD);
6708     }
6709   }
6710 
6711   if (D.getDeclSpec().isModulePrivateSpecified()) {
6712     if (IsVariableTemplateSpecialization)
6713       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6714           << (IsPartialSpecialization ? 1 : 0)
6715           << FixItHint::CreateRemoval(
6716                  D.getDeclSpec().getModulePrivateSpecLoc());
6717     else if (IsMemberSpecialization)
6718       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6719         << 2
6720         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6721     else if (NewVD->hasLocalStorage())
6722       Diag(NewVD->getLocation(), diag::err_module_private_local)
6723         << 0 << NewVD->getDeclName()
6724         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6725         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6726     else {
6727       NewVD->setModulePrivate();
6728       if (NewTemplate)
6729         NewTemplate->setModulePrivate();
6730       for (auto *B : Bindings)
6731         B->setModulePrivate();
6732     }
6733   }
6734 
6735   // Handle attributes prior to checking for duplicates in MergeVarDecl
6736   ProcessDeclAttributes(S, NewVD, D);
6737 
6738   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6739     if (EmitTLSUnsupportedError &&
6740         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6741          (getLangOpts().OpenMPIsDevice &&
6742           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6743       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6744            diag::err_thread_unsupported);
6745     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6746     // storage [duration]."
6747     if (SC == SC_None && S->getFnParent() != nullptr &&
6748         (NewVD->hasAttr<CUDASharedAttr>() ||
6749          NewVD->hasAttr<CUDAConstantAttr>())) {
6750       NewVD->setStorageClass(SC_Static);
6751     }
6752   }
6753 
6754   // Ensure that dllimport globals without explicit storage class are treated as
6755   // extern. The storage class is set above using parsed attributes. Now we can
6756   // check the VarDecl itself.
6757   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6758          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6759          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6760 
6761   // In auto-retain/release, infer strong retension for variables of
6762   // retainable type.
6763   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6764     NewVD->setInvalidDecl();
6765 
6766   // Handle GNU asm-label extension (encoded as an attribute).
6767   if (Expr *E = (Expr*)D.getAsmLabel()) {
6768     // The parser guarantees this is a string.
6769     StringLiteral *SE = cast<StringLiteral>(E);
6770     StringRef Label = SE->getString();
6771     if (S->getFnParent() != nullptr) {
6772       switch (SC) {
6773       case SC_None:
6774       case SC_Auto:
6775         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6776         break;
6777       case SC_Register:
6778         // Local Named register
6779         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6780             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6781           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6782         break;
6783       case SC_Static:
6784       case SC_Extern:
6785       case SC_PrivateExtern:
6786         break;
6787       }
6788     } else if (SC == SC_Register) {
6789       // Global Named register
6790       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6791         const auto &TI = Context.getTargetInfo();
6792         bool HasSizeMismatch;
6793 
6794         if (!TI.isValidGCCRegisterName(Label))
6795           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6796         else if (!TI.validateGlobalRegisterVariable(Label,
6797                                                     Context.getTypeSize(R),
6798                                                     HasSizeMismatch))
6799           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6800         else if (HasSizeMismatch)
6801           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6802       }
6803 
6804       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6805         Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6806         NewVD->setInvalidDecl(true);
6807       }
6808     }
6809 
6810     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6811                                                 Context, Label, 0));
6812   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6813     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6814       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6815     if (I != ExtnameUndeclaredIdentifiers.end()) {
6816       if (isDeclExternC(NewVD)) {
6817         NewVD->addAttr(I->second);
6818         ExtnameUndeclaredIdentifiers.erase(I);
6819       } else
6820         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6821             << /*Variable*/1 << NewVD;
6822     }
6823   }
6824 
6825   // Find the shadowed declaration before filtering for scope.
6826   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6827                                 ? getShadowedDeclaration(NewVD, Previous)
6828                                 : nullptr;
6829 
6830   // Don't consider existing declarations that are in a different
6831   // scope and are out-of-semantic-context declarations (if the new
6832   // declaration has linkage).
6833   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6834                        D.getCXXScopeSpec().isNotEmpty() ||
6835                        IsMemberSpecialization ||
6836                        IsVariableTemplateSpecialization);
6837 
6838   // Check whether the previous declaration is in the same block scope. This
6839   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6840   if (getLangOpts().CPlusPlus &&
6841       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6842     NewVD->setPreviousDeclInSameBlockScope(
6843         Previous.isSingleResult() && !Previous.isShadowed() &&
6844         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6845 
6846   if (!getLangOpts().CPlusPlus) {
6847     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6848   } else {
6849     // If this is an explicit specialization of a static data member, check it.
6850     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6851         CheckMemberSpecialization(NewVD, Previous))
6852       NewVD->setInvalidDecl();
6853 
6854     // Merge the decl with the existing one if appropriate.
6855     if (!Previous.empty()) {
6856       if (Previous.isSingleResult() &&
6857           isa<FieldDecl>(Previous.getFoundDecl()) &&
6858           D.getCXXScopeSpec().isSet()) {
6859         // The user tried to define a non-static data member
6860         // out-of-line (C++ [dcl.meaning]p1).
6861         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6862           << D.getCXXScopeSpec().getRange();
6863         Previous.clear();
6864         NewVD->setInvalidDecl();
6865       }
6866     } else if (D.getCXXScopeSpec().isSet()) {
6867       // No previous declaration in the qualifying scope.
6868       Diag(D.getIdentifierLoc(), diag::err_no_member)
6869         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6870         << D.getCXXScopeSpec().getRange();
6871       NewVD->setInvalidDecl();
6872     }
6873 
6874     if (!IsVariableTemplateSpecialization)
6875       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6876 
6877     if (NewTemplate) {
6878       VarTemplateDecl *PrevVarTemplate =
6879           NewVD->getPreviousDecl()
6880               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6881               : nullptr;
6882 
6883       // Check the template parameter list of this declaration, possibly
6884       // merging in the template parameter list from the previous variable
6885       // template declaration.
6886       if (CheckTemplateParameterList(
6887               TemplateParams,
6888               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6889                               : nullptr,
6890               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6891                DC->isDependentContext())
6892                   ? TPC_ClassTemplateMember
6893                   : TPC_VarTemplate))
6894         NewVD->setInvalidDecl();
6895 
6896       // If we are providing an explicit specialization of a static variable
6897       // template, make a note of that.
6898       if (PrevVarTemplate &&
6899           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6900         PrevVarTemplate->setMemberSpecialization();
6901     }
6902   }
6903 
6904   // Diagnose shadowed variables iff this isn't a redeclaration.
6905   if (ShadowedDecl && !D.isRedeclaration())
6906     CheckShadow(NewVD, ShadowedDecl, Previous);
6907 
6908   ProcessPragmaWeak(S, NewVD);
6909 
6910   // If this is the first declaration of an extern C variable, update
6911   // the map of such variables.
6912   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6913       isIncompleteDeclExternC(*this, NewVD))
6914     RegisterLocallyScopedExternCDecl(NewVD, S);
6915 
6916   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6917     Decl *ManglingContextDecl;
6918     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6919             NewVD->getDeclContext(), ManglingContextDecl)) {
6920       Context.setManglingNumber(
6921           NewVD, MCtx->getManglingNumber(
6922                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6923       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6924     }
6925   }
6926 
6927   // Special handling of variable named 'main'.
6928   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6929       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6930       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6931 
6932     // C++ [basic.start.main]p3
6933     // A program that declares a variable main at global scope is ill-formed.
6934     if (getLangOpts().CPlusPlus)
6935       Diag(D.getBeginLoc(), diag::err_main_global_variable);
6936 
6937     // In C, and external-linkage variable named main results in undefined
6938     // behavior.
6939     else if (NewVD->hasExternalFormalLinkage())
6940       Diag(D.getBeginLoc(), diag::warn_main_redefined);
6941   }
6942 
6943   if (D.isRedeclaration() && !Previous.empty()) {
6944     NamedDecl *Prev = Previous.getRepresentativeDecl();
6945     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6946                                    D.isFunctionDefinition());
6947   }
6948 
6949   if (NewTemplate) {
6950     if (NewVD->isInvalidDecl())
6951       NewTemplate->setInvalidDecl();
6952     ActOnDocumentableDecl(NewTemplate);
6953     return NewTemplate;
6954   }
6955 
6956   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6957     CompleteMemberSpecialization(NewVD, Previous);
6958 
6959   return NewVD;
6960 }
6961 
6962 /// Enum describing the %select options in diag::warn_decl_shadow.
6963 enum ShadowedDeclKind {
6964   SDK_Local,
6965   SDK_Global,
6966   SDK_StaticMember,
6967   SDK_Field,
6968   SDK_Typedef,
6969   SDK_Using
6970 };
6971 
6972 /// Determine what kind of declaration we're shadowing.
6973 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6974                                                 const DeclContext *OldDC) {
6975   if (isa<TypeAliasDecl>(ShadowedDecl))
6976     return SDK_Using;
6977   else if (isa<TypedefDecl>(ShadowedDecl))
6978     return SDK_Typedef;
6979   else if (isa<RecordDecl>(OldDC))
6980     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6981 
6982   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6983 }
6984 
6985 /// Return the location of the capture if the given lambda captures the given
6986 /// variable \p VD, or an invalid source location otherwise.
6987 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6988                                          const VarDecl *VD) {
6989   for (const Capture &Capture : LSI->Captures) {
6990     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6991       return Capture.getLocation();
6992   }
6993   return SourceLocation();
6994 }
6995 
6996 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6997                                      const LookupResult &R) {
6998   // Only diagnose if we're shadowing an unambiguous field or variable.
6999   if (R.getResultKind() != LookupResult::Found)
7000     return false;
7001 
7002   // Return false if warning is ignored.
7003   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7004 }
7005 
7006 /// Return the declaration shadowed by the given variable \p D, or null
7007 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7008 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7009                                         const LookupResult &R) {
7010   if (!shouldWarnIfShadowedDecl(Diags, R))
7011     return nullptr;
7012 
7013   // Don't diagnose declarations at file scope.
7014   if (D->hasGlobalStorage())
7015     return nullptr;
7016 
7017   NamedDecl *ShadowedDecl = R.getFoundDecl();
7018   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7019              ? ShadowedDecl
7020              : nullptr;
7021 }
7022 
7023 /// Return the declaration shadowed by the given typedef \p D, or null
7024 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7025 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7026                                         const LookupResult &R) {
7027   // Don't warn if typedef declaration is part of a class
7028   if (D->getDeclContext()->isRecord())
7029     return nullptr;
7030 
7031   if (!shouldWarnIfShadowedDecl(Diags, R))
7032     return nullptr;
7033 
7034   NamedDecl *ShadowedDecl = R.getFoundDecl();
7035   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7036 }
7037 
7038 /// Diagnose variable or built-in function shadowing.  Implements
7039 /// -Wshadow.
7040 ///
7041 /// This method is called whenever a VarDecl is added to a "useful"
7042 /// scope.
7043 ///
7044 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7045 /// \param R the lookup of the name
7046 ///
7047 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7048                        const LookupResult &R) {
7049   DeclContext *NewDC = D->getDeclContext();
7050 
7051   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7052     // Fields are not shadowed by variables in C++ static methods.
7053     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7054       if (MD->isStatic())
7055         return;
7056 
7057     // Fields shadowed by constructor parameters are a special case. Usually
7058     // the constructor initializes the field with the parameter.
7059     if (isa<CXXConstructorDecl>(NewDC))
7060       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7061         // Remember that this was shadowed so we can either warn about its
7062         // modification or its existence depending on warning settings.
7063         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7064         return;
7065       }
7066   }
7067 
7068   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7069     if (shadowedVar->isExternC()) {
7070       // For shadowing external vars, make sure that we point to the global
7071       // declaration, not a locally scoped extern declaration.
7072       for (auto I : shadowedVar->redecls())
7073         if (I->isFileVarDecl()) {
7074           ShadowedDecl = I;
7075           break;
7076         }
7077     }
7078 
7079   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7080 
7081   unsigned WarningDiag = diag::warn_decl_shadow;
7082   SourceLocation CaptureLoc;
7083   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7084       isa<CXXMethodDecl>(NewDC)) {
7085     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7086       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7087         if (RD->getLambdaCaptureDefault() == LCD_None) {
7088           // Try to avoid warnings for lambdas with an explicit capture list.
7089           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7090           // Warn only when the lambda captures the shadowed decl explicitly.
7091           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7092           if (CaptureLoc.isInvalid())
7093             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7094         } else {
7095           // Remember that this was shadowed so we can avoid the warning if the
7096           // shadowed decl isn't captured and the warning settings allow it.
7097           cast<LambdaScopeInfo>(getCurFunction())
7098               ->ShadowingDecls.push_back(
7099                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7100           return;
7101         }
7102       }
7103 
7104       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7105         // A variable can't shadow a local variable in an enclosing scope, if
7106         // they are separated by a non-capturing declaration context.
7107         for (DeclContext *ParentDC = NewDC;
7108              ParentDC && !ParentDC->Equals(OldDC);
7109              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7110           // Only block literals, captured statements, and lambda expressions
7111           // can capture; other scopes don't.
7112           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7113               !isLambdaCallOperator(ParentDC)) {
7114             return;
7115           }
7116         }
7117       }
7118     }
7119   }
7120 
7121   // Only warn about certain kinds of shadowing for class members.
7122   if (NewDC && NewDC->isRecord()) {
7123     // In particular, don't warn about shadowing non-class members.
7124     if (!OldDC->isRecord())
7125       return;
7126 
7127     // TODO: should we warn about static data members shadowing
7128     // static data members from base classes?
7129 
7130     // TODO: don't diagnose for inaccessible shadowed members.
7131     // This is hard to do perfectly because we might friend the
7132     // shadowing context, but that's just a false negative.
7133   }
7134 
7135 
7136   DeclarationName Name = R.getLookupName();
7137 
7138   // Emit warning and note.
7139   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7140     return;
7141   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7142   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7143   if (!CaptureLoc.isInvalid())
7144     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7145         << Name << /*explicitly*/ 1;
7146   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7147 }
7148 
7149 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7150 /// when these variables are captured by the lambda.
7151 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7152   for (const auto &Shadow : LSI->ShadowingDecls) {
7153     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7154     // Try to avoid the warning when the shadowed decl isn't captured.
7155     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7156     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7157     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7158                                        ? diag::warn_decl_shadow_uncaptured_local
7159                                        : diag::warn_decl_shadow)
7160         << Shadow.VD->getDeclName()
7161         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7162     if (!CaptureLoc.isInvalid())
7163       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7164           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7165     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7166   }
7167 }
7168 
7169 /// Check -Wshadow without the advantage of a previous lookup.
7170 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7171   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7172     return;
7173 
7174   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7175                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7176   LookupName(R, S);
7177   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7178     CheckShadow(D, ShadowedDecl, R);
7179 }
7180 
7181 /// Check if 'E', which is an expression that is about to be modified, refers
7182 /// to a constructor parameter that shadows a field.
7183 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7184   // Quickly ignore expressions that can't be shadowing ctor parameters.
7185   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7186     return;
7187   E = E->IgnoreParenImpCasts();
7188   auto *DRE = dyn_cast<DeclRefExpr>(E);
7189   if (!DRE)
7190     return;
7191   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7192   auto I = ShadowingDecls.find(D);
7193   if (I == ShadowingDecls.end())
7194     return;
7195   const NamedDecl *ShadowedDecl = I->second;
7196   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7197   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7198   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7199   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7200 
7201   // Avoid issuing multiple warnings about the same decl.
7202   ShadowingDecls.erase(I);
7203 }
7204 
7205 /// Check for conflict between this global or extern "C" declaration and
7206 /// previous global or extern "C" declarations. This is only used in C++.
7207 template<typename T>
7208 static bool checkGlobalOrExternCConflict(
7209     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7210   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7211   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7212 
7213   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7214     // The common case: this global doesn't conflict with any extern "C"
7215     // declaration.
7216     return false;
7217   }
7218 
7219   if (Prev) {
7220     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7221       // Both the old and new declarations have C language linkage. This is a
7222       // redeclaration.
7223       Previous.clear();
7224       Previous.addDecl(Prev);
7225       return true;
7226     }
7227 
7228     // This is a global, non-extern "C" declaration, and there is a previous
7229     // non-global extern "C" declaration. Diagnose if this is a variable
7230     // declaration.
7231     if (!isa<VarDecl>(ND))
7232       return false;
7233   } else {
7234     // The declaration is extern "C". Check for any declaration in the
7235     // translation unit which might conflict.
7236     if (IsGlobal) {
7237       // We have already performed the lookup into the translation unit.
7238       IsGlobal = false;
7239       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7240            I != E; ++I) {
7241         if (isa<VarDecl>(*I)) {
7242           Prev = *I;
7243           break;
7244         }
7245       }
7246     } else {
7247       DeclContext::lookup_result R =
7248           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7249       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7250            I != E; ++I) {
7251         if (isa<VarDecl>(*I)) {
7252           Prev = *I;
7253           break;
7254         }
7255         // FIXME: If we have any other entity with this name in global scope,
7256         // the declaration is ill-formed, but that is a defect: it breaks the
7257         // 'stat' hack, for instance. Only variables can have mangled name
7258         // clashes with extern "C" declarations, so only they deserve a
7259         // diagnostic.
7260       }
7261     }
7262 
7263     if (!Prev)
7264       return false;
7265   }
7266 
7267   // Use the first declaration's location to ensure we point at something which
7268   // is lexically inside an extern "C" linkage-spec.
7269   assert(Prev && "should have found a previous declaration to diagnose");
7270   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7271     Prev = FD->getFirstDecl();
7272   else
7273     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7274 
7275   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7276     << IsGlobal << ND;
7277   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7278     << IsGlobal;
7279   return false;
7280 }
7281 
7282 /// Apply special rules for handling extern "C" declarations. Returns \c true
7283 /// if we have found that this is a redeclaration of some prior entity.
7284 ///
7285 /// Per C++ [dcl.link]p6:
7286 ///   Two declarations [for a function or variable] with C language linkage
7287 ///   with the same name that appear in different scopes refer to the same
7288 ///   [entity]. An entity with C language linkage shall not be declared with
7289 ///   the same name as an entity in global scope.
7290 template<typename T>
7291 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7292                                                   LookupResult &Previous) {
7293   if (!S.getLangOpts().CPlusPlus) {
7294     // In C, when declaring a global variable, look for a corresponding 'extern'
7295     // variable declared in function scope. We don't need this in C++, because
7296     // we find local extern decls in the surrounding file-scope DeclContext.
7297     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7298       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7299         Previous.clear();
7300         Previous.addDecl(Prev);
7301         return true;
7302       }
7303     }
7304     return false;
7305   }
7306 
7307   // A declaration in the translation unit can conflict with an extern "C"
7308   // declaration.
7309   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7310     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7311 
7312   // An extern "C" declaration can conflict with a declaration in the
7313   // translation unit or can be a redeclaration of an extern "C" declaration
7314   // in another scope.
7315   if (isIncompleteDeclExternC(S,ND))
7316     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7317 
7318   // Neither global nor extern "C": nothing to do.
7319   return false;
7320 }
7321 
7322 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7323   // If the decl is already known invalid, don't check it.
7324   if (NewVD->isInvalidDecl())
7325     return;
7326 
7327   QualType T = NewVD->getType();
7328 
7329   // Defer checking an 'auto' type until its initializer is attached.
7330   if (T->isUndeducedType())
7331     return;
7332 
7333   if (NewVD->hasAttrs())
7334     CheckAlignasUnderalignment(NewVD);
7335 
7336   if (T->isObjCObjectType()) {
7337     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7338       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7339     T = Context.getObjCObjectPointerType(T);
7340     NewVD->setType(T);
7341   }
7342 
7343   // Emit an error if an address space was applied to decl with local storage.
7344   // This includes arrays of objects with address space qualifiers, but not
7345   // automatic variables that point to other address spaces.
7346   // ISO/IEC TR 18037 S5.1.2
7347   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7348       T.getAddressSpace() != LangAS::Default) {
7349     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7350     NewVD->setInvalidDecl();
7351     return;
7352   }
7353 
7354   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7355   // scope.
7356   if (getLangOpts().OpenCLVersion == 120 &&
7357       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7358       NewVD->isStaticLocal()) {
7359     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7360     NewVD->setInvalidDecl();
7361     return;
7362   }
7363 
7364   if (getLangOpts().OpenCL) {
7365     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7366     if (NewVD->hasAttr<BlocksAttr>()) {
7367       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7368       return;
7369     }
7370 
7371     if (T->isBlockPointerType()) {
7372       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7373       // can't use 'extern' storage class.
7374       if (!T.isConstQualified()) {
7375         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7376             << 0 /*const*/;
7377         NewVD->setInvalidDecl();
7378         return;
7379       }
7380       if (NewVD->hasExternalStorage()) {
7381         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7382         NewVD->setInvalidDecl();
7383         return;
7384       }
7385     }
7386     // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7387     // __constant address space.
7388     // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7389     // variables inside a function can also be declared in the global
7390     // address space.
7391     // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7392     // address space additionally.
7393     // FIXME: Add local AS for OpenCL C++.
7394     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7395         NewVD->hasExternalStorage()) {
7396       if (!T->isSamplerT() &&
7397           !(T.getAddressSpace() == LangAS::opencl_constant ||
7398             (T.getAddressSpace() == LangAS::opencl_global &&
7399              (getLangOpts().OpenCLVersion == 200 ||
7400               getLangOpts().OpenCLCPlusPlus)))) {
7401         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7402         if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7403           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7404               << Scope << "global or constant";
7405         else
7406           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7407               << Scope << "constant";
7408         NewVD->setInvalidDecl();
7409         return;
7410       }
7411     } else {
7412       if (T.getAddressSpace() == LangAS::opencl_global) {
7413         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7414             << 1 /*is any function*/ << "global";
7415         NewVD->setInvalidDecl();
7416         return;
7417       }
7418       if (T.getAddressSpace() == LangAS::opencl_constant ||
7419           T.getAddressSpace() == LangAS::opencl_local) {
7420         FunctionDecl *FD = getCurFunctionDecl();
7421         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7422         // in functions.
7423         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7424           if (T.getAddressSpace() == LangAS::opencl_constant)
7425             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7426                 << 0 /*non-kernel only*/ << "constant";
7427           else
7428             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7429                 << 0 /*non-kernel only*/ << "local";
7430           NewVD->setInvalidDecl();
7431           return;
7432         }
7433         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7434         // in the outermost scope of a kernel function.
7435         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7436           if (!getCurScope()->isFunctionScope()) {
7437             if (T.getAddressSpace() == LangAS::opencl_constant)
7438               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7439                   << "constant";
7440             else
7441               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7442                   << "local";
7443             NewVD->setInvalidDecl();
7444             return;
7445           }
7446         }
7447       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7448         // Do not allow other address spaces on automatic variable.
7449         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7450         NewVD->setInvalidDecl();
7451         return;
7452       }
7453     }
7454   }
7455 
7456   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7457       && !NewVD->hasAttr<BlocksAttr>()) {
7458     if (getLangOpts().getGC() != LangOptions::NonGC)
7459       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7460     else {
7461       assert(!getLangOpts().ObjCAutoRefCount);
7462       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7463     }
7464   }
7465 
7466   bool isVM = T->isVariablyModifiedType();
7467   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7468       NewVD->hasAttr<BlocksAttr>())
7469     setFunctionHasBranchProtectedScope();
7470 
7471   if ((isVM && NewVD->hasLinkage()) ||
7472       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7473     bool SizeIsNegative;
7474     llvm::APSInt Oversized;
7475     TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7476         NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7477     QualType FixedT;
7478     if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7479       FixedT = FixedTInfo->getType();
7480     else if (FixedTInfo) {
7481       // Type and type-as-written are canonically different. We need to fix up
7482       // both types separately.
7483       FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7484                                                    Oversized);
7485     }
7486     if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7487       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7488       // FIXME: This won't give the correct result for
7489       // int a[10][n];
7490       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7491 
7492       if (NewVD->isFileVarDecl())
7493         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7494         << SizeRange;
7495       else if (NewVD->isStaticLocal())
7496         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7497         << SizeRange;
7498       else
7499         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7500         << SizeRange;
7501       NewVD->setInvalidDecl();
7502       return;
7503     }
7504 
7505     if (!FixedTInfo) {
7506       if (NewVD->isFileVarDecl())
7507         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7508       else
7509         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7510       NewVD->setInvalidDecl();
7511       return;
7512     }
7513 
7514     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7515     NewVD->setType(FixedT);
7516     NewVD->setTypeSourceInfo(FixedTInfo);
7517   }
7518 
7519   if (T->isVoidType()) {
7520     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7521     //                    of objects and functions.
7522     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7523       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7524         << T;
7525       NewVD->setInvalidDecl();
7526       return;
7527     }
7528   }
7529 
7530   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7531     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7532     NewVD->setInvalidDecl();
7533     return;
7534   }
7535 
7536   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7537     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7538     NewVD->setInvalidDecl();
7539     return;
7540   }
7541 
7542   if (NewVD->isConstexpr() && !T->isDependentType() &&
7543       RequireLiteralType(NewVD->getLocation(), T,
7544                          diag::err_constexpr_var_non_literal)) {
7545     NewVD->setInvalidDecl();
7546     return;
7547   }
7548 }
7549 
7550 /// Perform semantic checking on a newly-created variable
7551 /// declaration.
7552 ///
7553 /// This routine performs all of the type-checking required for a
7554 /// variable declaration once it has been built. It is used both to
7555 /// check variables after they have been parsed and their declarators
7556 /// have been translated into a declaration, and to check variables
7557 /// that have been instantiated from a template.
7558 ///
7559 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7560 ///
7561 /// Returns true if the variable declaration is a redeclaration.
7562 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7563   CheckVariableDeclarationType(NewVD);
7564 
7565   // If the decl is already known invalid, don't check it.
7566   if (NewVD->isInvalidDecl())
7567     return false;
7568 
7569   // If we did not find anything by this name, look for a non-visible
7570   // extern "C" declaration with the same name.
7571   if (Previous.empty() &&
7572       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7573     Previous.setShadowed();
7574 
7575   if (!Previous.empty()) {
7576     MergeVarDecl(NewVD, Previous);
7577     return true;
7578   }
7579   return false;
7580 }
7581 
7582 namespace {
7583 struct FindOverriddenMethod {
7584   Sema *S;
7585   CXXMethodDecl *Method;
7586 
7587   /// Member lookup function that determines whether a given C++
7588   /// method overrides a method in a base class, to be used with
7589   /// CXXRecordDecl::lookupInBases().
7590   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7591     RecordDecl *BaseRecord =
7592         Specifier->getType()->getAs<RecordType>()->getDecl();
7593 
7594     DeclarationName Name = Method->getDeclName();
7595 
7596     // FIXME: Do we care about other names here too?
7597     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7598       // We really want to find the base class destructor here.
7599       QualType T = S->Context.getTypeDeclType(BaseRecord);
7600       CanQualType CT = S->Context.getCanonicalType(T);
7601 
7602       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7603     }
7604 
7605     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7606          Path.Decls = Path.Decls.slice(1)) {
7607       NamedDecl *D = Path.Decls.front();
7608       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7609         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7610           return true;
7611       }
7612     }
7613 
7614     return false;
7615   }
7616 };
7617 
7618 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7619 } // end anonymous namespace
7620 
7621 /// Report an error regarding overriding, along with any relevant
7622 /// overridden methods.
7623 ///
7624 /// \param DiagID the primary error to report.
7625 /// \param MD the overriding method.
7626 /// \param OEK which overrides to include as notes.
7627 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7628                             OverrideErrorKind OEK = OEK_All) {
7629   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7630   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7631     // This check (& the OEK parameter) could be replaced by a predicate, but
7632     // without lambdas that would be overkill. This is still nicer than writing
7633     // out the diag loop 3 times.
7634     if ((OEK == OEK_All) ||
7635         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7636         (OEK == OEK_Deleted && O->isDeleted()))
7637       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7638   }
7639 }
7640 
7641 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7642 /// and if so, check that it's a valid override and remember it.
7643 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7644   // Look for methods in base classes that this method might override.
7645   CXXBasePaths Paths;
7646   FindOverriddenMethod FOM;
7647   FOM.Method = MD;
7648   FOM.S = this;
7649   bool hasDeletedOverridenMethods = false;
7650   bool hasNonDeletedOverridenMethods = false;
7651   bool AddedAny = false;
7652   if (DC->lookupInBases(FOM, Paths)) {
7653     for (auto *I : Paths.found_decls()) {
7654       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7655         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7656         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7657             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7658             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7659             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7660           hasDeletedOverridenMethods |= OldMD->isDeleted();
7661           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7662           AddedAny = true;
7663         }
7664       }
7665     }
7666   }
7667 
7668   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7669     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7670   }
7671   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7672     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7673   }
7674 
7675   return AddedAny;
7676 }
7677 
7678 namespace {
7679   // Struct for holding all of the extra arguments needed by
7680   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7681   struct ActOnFDArgs {
7682     Scope *S;
7683     Declarator &D;
7684     MultiTemplateParamsArg TemplateParamLists;
7685     bool AddToScope;
7686   };
7687 } // end anonymous namespace
7688 
7689 namespace {
7690 
7691 // Callback to only accept typo corrections that have a non-zero edit distance.
7692 // Also only accept corrections that have the same parent decl.
7693 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7694  public:
7695   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7696                             CXXRecordDecl *Parent)
7697       : Context(Context), OriginalFD(TypoFD),
7698         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7699 
7700   bool ValidateCandidate(const TypoCorrection &candidate) override {
7701     if (candidate.getEditDistance() == 0)
7702       return false;
7703 
7704     SmallVector<unsigned, 1> MismatchedParams;
7705     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7706                                           CDeclEnd = candidate.end();
7707          CDecl != CDeclEnd; ++CDecl) {
7708       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7709 
7710       if (FD && !FD->hasBody() &&
7711           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7712         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7713           CXXRecordDecl *Parent = MD->getParent();
7714           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7715             return true;
7716         } else if (!ExpectedParent) {
7717           return true;
7718         }
7719       }
7720     }
7721 
7722     return false;
7723   }
7724 
7725   std::unique_ptr<CorrectionCandidateCallback> clone() override {
7726     return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7727   }
7728 
7729  private:
7730   ASTContext &Context;
7731   FunctionDecl *OriginalFD;
7732   CXXRecordDecl *ExpectedParent;
7733 };
7734 
7735 } // end anonymous namespace
7736 
7737 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7738   TypoCorrectedFunctionDefinitions.insert(F);
7739 }
7740 
7741 /// Generate diagnostics for an invalid function redeclaration.
7742 ///
7743 /// This routine handles generating the diagnostic messages for an invalid
7744 /// function redeclaration, including finding possible similar declarations
7745 /// or performing typo correction if there are no previous declarations with
7746 /// the same name.
7747 ///
7748 /// Returns a NamedDecl iff typo correction was performed and substituting in
7749 /// the new declaration name does not cause new errors.
7750 static NamedDecl *DiagnoseInvalidRedeclaration(
7751     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7752     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7753   DeclarationName Name = NewFD->getDeclName();
7754   DeclContext *NewDC = NewFD->getDeclContext();
7755   SmallVector<unsigned, 1> MismatchedParams;
7756   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7757   TypoCorrection Correction;
7758   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7759   unsigned DiagMsg =
7760     IsLocalFriend ? diag::err_no_matching_local_friend :
7761     NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7762     diag::err_member_decl_does_not_match;
7763   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7764                     IsLocalFriend ? Sema::LookupLocalFriendName
7765                                   : Sema::LookupOrdinaryName,
7766                     Sema::ForVisibleRedeclaration);
7767 
7768   NewFD->setInvalidDecl();
7769   if (IsLocalFriend)
7770     SemaRef.LookupName(Prev, S);
7771   else
7772     SemaRef.LookupQualifiedName(Prev, NewDC);
7773   assert(!Prev.isAmbiguous() &&
7774          "Cannot have an ambiguity in previous-declaration lookup");
7775   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7776   DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
7777                                 MD ? MD->getParent() : nullptr);
7778   if (!Prev.empty()) {
7779     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7780          Func != FuncEnd; ++Func) {
7781       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7782       if (FD &&
7783           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7784         // Add 1 to the index so that 0 can mean the mismatch didn't
7785         // involve a parameter
7786         unsigned ParamNum =
7787             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7788         NearMatches.push_back(std::make_pair(FD, ParamNum));
7789       }
7790     }
7791   // If the qualified name lookup yielded nothing, try typo correction
7792   } else if ((Correction = SemaRef.CorrectTypo(
7793                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7794                   &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
7795                   IsLocalFriend ? nullptr : NewDC))) {
7796     // Set up everything for the call to ActOnFunctionDeclarator
7797     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7798                               ExtraArgs.D.getIdentifierLoc());
7799     Previous.clear();
7800     Previous.setLookupName(Correction.getCorrection());
7801     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7802                                     CDeclEnd = Correction.end();
7803          CDecl != CDeclEnd; ++CDecl) {
7804       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7805       if (FD && !FD->hasBody() &&
7806           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7807         Previous.addDecl(FD);
7808       }
7809     }
7810     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7811 
7812     NamedDecl *Result;
7813     // Retry building the function declaration with the new previous
7814     // declarations, and with errors suppressed.
7815     {
7816       // Trap errors.
7817       Sema::SFINAETrap Trap(SemaRef);
7818 
7819       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7820       // pieces need to verify the typo-corrected C++ declaration and hopefully
7821       // eliminate the need for the parameter pack ExtraArgs.
7822       Result = SemaRef.ActOnFunctionDeclarator(
7823           ExtraArgs.S, ExtraArgs.D,
7824           Correction.getCorrectionDecl()->getDeclContext(),
7825           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7826           ExtraArgs.AddToScope);
7827 
7828       if (Trap.hasErrorOccurred())
7829         Result = nullptr;
7830     }
7831 
7832     if (Result) {
7833       // Determine which correction we picked.
7834       Decl *Canonical = Result->getCanonicalDecl();
7835       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7836            I != E; ++I)
7837         if ((*I)->getCanonicalDecl() == Canonical)
7838           Correction.setCorrectionDecl(*I);
7839 
7840       // Let Sema know about the correction.
7841       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7842       SemaRef.diagnoseTypo(
7843           Correction,
7844           SemaRef.PDiag(IsLocalFriend
7845                           ? diag::err_no_matching_local_friend_suggest
7846                           : diag::err_member_decl_does_not_match_suggest)
7847             << Name << NewDC << IsDefinition);
7848       return Result;
7849     }
7850 
7851     // Pretend the typo correction never occurred
7852     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7853                               ExtraArgs.D.getIdentifierLoc());
7854     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7855     Previous.clear();
7856     Previous.setLookupName(Name);
7857   }
7858 
7859   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7860       << Name << NewDC << IsDefinition << NewFD->getLocation();
7861 
7862   bool NewFDisConst = false;
7863   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7864     NewFDisConst = NewMD->isConst();
7865 
7866   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7867        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7868        NearMatch != NearMatchEnd; ++NearMatch) {
7869     FunctionDecl *FD = NearMatch->first;
7870     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7871     bool FDisConst = MD && MD->isConst();
7872     bool IsMember = MD || !IsLocalFriend;
7873 
7874     // FIXME: These notes are poorly worded for the local friend case.
7875     if (unsigned Idx = NearMatch->second) {
7876       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7877       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7878       if (Loc.isInvalid()) Loc = FD->getLocation();
7879       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7880                                  : diag::note_local_decl_close_param_match)
7881         << Idx << FDParam->getType()
7882         << NewFD->getParamDecl(Idx - 1)->getType();
7883     } else if (FDisConst != NewFDisConst) {
7884       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7885           << NewFDisConst << FD->getSourceRange().getEnd();
7886     } else
7887       SemaRef.Diag(FD->getLocation(),
7888                    IsMember ? diag::note_member_def_close_match
7889                             : diag::note_local_decl_close_match);
7890   }
7891   return nullptr;
7892 }
7893 
7894 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7895   switch (D.getDeclSpec().getStorageClassSpec()) {
7896   default: llvm_unreachable("Unknown storage class!");
7897   case DeclSpec::SCS_auto:
7898   case DeclSpec::SCS_register:
7899   case DeclSpec::SCS_mutable:
7900     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7901                  diag::err_typecheck_sclass_func);
7902     D.getMutableDeclSpec().ClearStorageClassSpecs();
7903     D.setInvalidType();
7904     break;
7905   case DeclSpec::SCS_unspecified: break;
7906   case DeclSpec::SCS_extern:
7907     if (D.getDeclSpec().isExternInLinkageSpec())
7908       return SC_None;
7909     return SC_Extern;
7910   case DeclSpec::SCS_static: {
7911     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7912       // C99 6.7.1p5:
7913       //   The declaration of an identifier for a function that has
7914       //   block scope shall have no explicit storage-class specifier
7915       //   other than extern
7916       // See also (C++ [dcl.stc]p4).
7917       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7918                    diag::err_static_block_func);
7919       break;
7920     } else
7921       return SC_Static;
7922   }
7923   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7924   }
7925 
7926   // No explicit storage class has already been returned
7927   return SC_None;
7928 }
7929 
7930 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7931                                            DeclContext *DC, QualType &R,
7932                                            TypeSourceInfo *TInfo,
7933                                            StorageClass SC,
7934                                            bool &IsVirtualOkay) {
7935   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7936   DeclarationName Name = NameInfo.getName();
7937 
7938   FunctionDecl *NewFD = nullptr;
7939   bool isInline = D.getDeclSpec().isInlineSpecified();
7940 
7941   if (!SemaRef.getLangOpts().CPlusPlus) {
7942     // Determine whether the function was written with a
7943     // prototype. This true when:
7944     //   - there is a prototype in the declarator, or
7945     //   - the type R of the function is some kind of typedef or other non-
7946     //     attributed reference to a type name (which eventually refers to a
7947     //     function type).
7948     bool HasPrototype =
7949       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7950       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7951 
7952     NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
7953                                  R, TInfo, SC, isInline, HasPrototype, false);
7954     if (D.isInvalidType())
7955       NewFD->setInvalidDecl();
7956 
7957     return NewFD;
7958   }
7959 
7960   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7961   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7962 
7963   // Check that the return type is not an abstract class type.
7964   // For record types, this is done by the AbstractClassUsageDiagnoser once
7965   // the class has been completely parsed.
7966   if (!DC->isRecord() &&
7967       SemaRef.RequireNonAbstractType(
7968           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7969           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7970     D.setInvalidType();
7971 
7972   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7973     // This is a C++ constructor declaration.
7974     assert(DC->isRecord() &&
7975            "Constructors can only be declared in a member context");
7976 
7977     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7978     return CXXConstructorDecl::Create(
7979         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
7980         TInfo, isExplicit, isInline,
7981         /*isImplicitlyDeclared=*/false, isConstexpr);
7982 
7983   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7984     // This is a C++ destructor declaration.
7985     if (DC->isRecord()) {
7986       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7987       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7988       CXXDestructorDecl *NewDD =
7989           CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(),
7990                                     NameInfo, R, TInfo, isInline,
7991                                     /*isImplicitlyDeclared=*/false);
7992 
7993       // If the destructor needs an implicit exception specification, set it
7994       // now. FIXME: It'd be nice to be able to create the right type to start
7995       // with, but the type needs to reference the destructor declaration.
7996       if (SemaRef.getLangOpts().CPlusPlus11)
7997         SemaRef.AdjustDestructorExceptionSpec(NewDD);
7998 
7999       IsVirtualOkay = true;
8000       return NewDD;
8001 
8002     } else {
8003       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8004       D.setInvalidType();
8005 
8006       // Create a FunctionDecl to satisfy the function definition parsing
8007       // code path.
8008       return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8009                                   D.getIdentifierLoc(), Name, R, TInfo, SC,
8010                                   isInline,
8011                                   /*hasPrototype=*/true, isConstexpr);
8012     }
8013 
8014   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8015     if (!DC->isRecord()) {
8016       SemaRef.Diag(D.getIdentifierLoc(),
8017            diag::err_conv_function_not_member);
8018       return nullptr;
8019     }
8020 
8021     SemaRef.CheckConversionDeclarator(D, R, SC);
8022     IsVirtualOkay = true;
8023     return CXXConversionDecl::Create(
8024         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8025         TInfo, isInline, isExplicit, isConstexpr, SourceLocation());
8026 
8027   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8028     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8029 
8030     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8031                                          isExplicit, NameInfo, R, TInfo,
8032                                          D.getEndLoc());
8033   } else if (DC->isRecord()) {
8034     // If the name of the function is the same as the name of the record,
8035     // then this must be an invalid constructor that has a return type.
8036     // (The parser checks for a return type and makes the declarator a
8037     // constructor if it has no return type).
8038     if (Name.getAsIdentifierInfo() &&
8039         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8040       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8041         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8042         << SourceRange(D.getIdentifierLoc());
8043       return nullptr;
8044     }
8045 
8046     // This is a C++ method declaration.
8047     CXXMethodDecl *Ret = CXXMethodDecl::Create(
8048         SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8049         TInfo, SC, isInline, isConstexpr, SourceLocation());
8050     IsVirtualOkay = !Ret->isStatic();
8051     return Ret;
8052   } else {
8053     bool isFriend =
8054         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8055     if (!isFriend && SemaRef.CurContext->isRecord())
8056       return nullptr;
8057 
8058     // Determine whether the function was written with a
8059     // prototype. This true when:
8060     //   - we're in C++ (where every function has a prototype),
8061     return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8062                                 R, TInfo, SC, isInline, true /*HasPrototype*/,
8063                                 isConstexpr);
8064   }
8065 }
8066 
8067 enum OpenCLParamType {
8068   ValidKernelParam,
8069   PtrPtrKernelParam,
8070   PtrKernelParam,
8071   InvalidAddrSpacePtrKernelParam,
8072   InvalidKernelParam,
8073   RecordKernelParam
8074 };
8075 
8076 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8077   // Size dependent types are just typedefs to normal integer types
8078   // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8079   // integers other than by their names.
8080   StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8081 
8082   // Remove typedefs one by one until we reach a typedef
8083   // for a size dependent type.
8084   QualType DesugaredTy = Ty;
8085   do {
8086     ArrayRef<StringRef> Names(SizeTypeNames);
8087     auto Match = llvm::find(Names, DesugaredTy.getAsString());
8088     if (Names.end() != Match)
8089       return true;
8090 
8091     Ty = DesugaredTy;
8092     DesugaredTy = Ty.getSingleStepDesugaredType(C);
8093   } while (DesugaredTy != Ty);
8094 
8095   return false;
8096 }
8097 
8098 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8099   if (PT->isPointerType()) {
8100     QualType PointeeType = PT->getPointeeType();
8101     if (PointeeType->isPointerType())
8102       return PtrPtrKernelParam;
8103     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8104         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8105         PointeeType.getAddressSpace() == LangAS::Default)
8106       return InvalidAddrSpacePtrKernelParam;
8107     return PtrKernelParam;
8108   }
8109 
8110   // OpenCL v1.2 s6.9.k:
8111   // Arguments to kernel functions in a program cannot be declared with the
8112   // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8113   // uintptr_t or a struct and/or union that contain fields declared to be one
8114   // of these built-in scalar types.
8115   if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8116     return InvalidKernelParam;
8117 
8118   if (PT->isImageType())
8119     return PtrKernelParam;
8120 
8121   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8122     return InvalidKernelParam;
8123 
8124   // OpenCL extension spec v1.2 s9.5:
8125   // This extension adds support for half scalar and vector types as built-in
8126   // types that can be used for arithmetic operations, conversions etc.
8127   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8128     return InvalidKernelParam;
8129 
8130   if (PT->isRecordType())
8131     return RecordKernelParam;
8132 
8133   // Look into an array argument to check if it has a forbidden type.
8134   if (PT->isArrayType()) {
8135     const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8136     // Call ourself to check an underlying type of an array. Since the
8137     // getPointeeOrArrayElementType returns an innermost type which is not an
8138     // array, this recursive call only happens once.
8139     return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8140   }
8141 
8142   return ValidKernelParam;
8143 }
8144 
8145 static void checkIsValidOpenCLKernelParameter(
8146   Sema &S,
8147   Declarator &D,
8148   ParmVarDecl *Param,
8149   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8150   QualType PT = Param->getType();
8151 
8152   // Cache the valid types we encounter to avoid rechecking structs that are
8153   // used again
8154   if (ValidTypes.count(PT.getTypePtr()))
8155     return;
8156 
8157   switch (getOpenCLKernelParameterType(S, PT)) {
8158   case PtrPtrKernelParam:
8159     // OpenCL v1.2 s6.9.a:
8160     // A kernel function argument cannot be declared as a
8161     // pointer to a pointer type.
8162     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8163     D.setInvalidType();
8164     return;
8165 
8166   case InvalidAddrSpacePtrKernelParam:
8167     // OpenCL v1.0 s6.5:
8168     // __kernel function arguments declared to be a pointer of a type can point
8169     // to one of the following address spaces only : __global, __local or
8170     // __constant.
8171     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8172     D.setInvalidType();
8173     return;
8174 
8175     // OpenCL v1.2 s6.9.k:
8176     // Arguments to kernel functions in a program cannot be declared with the
8177     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8178     // uintptr_t or a struct and/or union that contain fields declared to be
8179     // one of these built-in scalar types.
8180 
8181   case InvalidKernelParam:
8182     // OpenCL v1.2 s6.8 n:
8183     // A kernel function argument cannot be declared
8184     // of event_t type.
8185     // Do not diagnose half type since it is diagnosed as invalid argument
8186     // type for any function elsewhere.
8187     if (!PT->isHalfType()) {
8188       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8189 
8190       // Explain what typedefs are involved.
8191       const TypedefType *Typedef = nullptr;
8192       while ((Typedef = PT->getAs<TypedefType>())) {
8193         SourceLocation Loc = Typedef->getDecl()->getLocation();
8194         // SourceLocation may be invalid for a built-in type.
8195         if (Loc.isValid())
8196           S.Diag(Loc, diag::note_entity_declared_at) << PT;
8197         PT = Typedef->desugar();
8198       }
8199     }
8200 
8201     D.setInvalidType();
8202     return;
8203 
8204   case PtrKernelParam:
8205   case ValidKernelParam:
8206     ValidTypes.insert(PT.getTypePtr());
8207     return;
8208 
8209   case RecordKernelParam:
8210     break;
8211   }
8212 
8213   // Track nested structs we will inspect
8214   SmallVector<const Decl *, 4> VisitStack;
8215 
8216   // Track where we are in the nested structs. Items will migrate from
8217   // VisitStack to HistoryStack as we do the DFS for bad field.
8218   SmallVector<const FieldDecl *, 4> HistoryStack;
8219   HistoryStack.push_back(nullptr);
8220 
8221   // At this point we already handled everything except of a RecordType or
8222   // an ArrayType of a RecordType.
8223   assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8224   const RecordType *RecTy =
8225       PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8226   const RecordDecl *OrigRecDecl = RecTy->getDecl();
8227 
8228   VisitStack.push_back(RecTy->getDecl());
8229   assert(VisitStack.back() && "First decl null?");
8230 
8231   do {
8232     const Decl *Next = VisitStack.pop_back_val();
8233     if (!Next) {
8234       assert(!HistoryStack.empty());
8235       // Found a marker, we have gone up a level
8236       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8237         ValidTypes.insert(Hist->getType().getTypePtr());
8238 
8239       continue;
8240     }
8241 
8242     // Adds everything except the original parameter declaration (which is not a
8243     // field itself) to the history stack.
8244     const RecordDecl *RD;
8245     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8246       HistoryStack.push_back(Field);
8247 
8248       QualType FieldTy = Field->getType();
8249       // Other field types (known to be valid or invalid) are handled while we
8250       // walk around RecordDecl::fields().
8251       assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8252              "Unexpected type.");
8253       const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8254 
8255       RD = FieldRecTy->castAs<RecordType>()->getDecl();
8256     } else {
8257       RD = cast<RecordDecl>(Next);
8258     }
8259 
8260     // Add a null marker so we know when we've gone back up a level
8261     VisitStack.push_back(nullptr);
8262 
8263     for (const auto *FD : RD->fields()) {
8264       QualType QT = FD->getType();
8265 
8266       if (ValidTypes.count(QT.getTypePtr()))
8267         continue;
8268 
8269       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8270       if (ParamType == ValidKernelParam)
8271         continue;
8272 
8273       if (ParamType == RecordKernelParam) {
8274         VisitStack.push_back(FD);
8275         continue;
8276       }
8277 
8278       // OpenCL v1.2 s6.9.p:
8279       // Arguments to kernel functions that are declared to be a struct or union
8280       // do not allow OpenCL objects to be passed as elements of the struct or
8281       // union.
8282       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8283           ParamType == InvalidAddrSpacePtrKernelParam) {
8284         S.Diag(Param->getLocation(),
8285                diag::err_record_with_pointers_kernel_param)
8286           << PT->isUnionType()
8287           << PT;
8288       } else {
8289         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8290       }
8291 
8292       S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8293           << OrigRecDecl->getDeclName();
8294 
8295       // We have an error, now let's go back up through history and show where
8296       // the offending field came from
8297       for (ArrayRef<const FieldDecl *>::const_iterator
8298                I = HistoryStack.begin() + 1,
8299                E = HistoryStack.end();
8300            I != E; ++I) {
8301         const FieldDecl *OuterField = *I;
8302         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8303           << OuterField->getType();
8304       }
8305 
8306       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8307         << QT->isPointerType()
8308         << QT;
8309       D.setInvalidType();
8310       return;
8311     }
8312   } while (!VisitStack.empty());
8313 }
8314 
8315 /// Find the DeclContext in which a tag is implicitly declared if we see an
8316 /// elaborated type specifier in the specified context, and lookup finds
8317 /// nothing.
8318 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8319   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8320     DC = DC->getParent();
8321   return DC;
8322 }
8323 
8324 /// Find the Scope in which a tag is implicitly declared if we see an
8325 /// elaborated type specifier in the specified context, and lookup finds
8326 /// nothing.
8327 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8328   while (S->isClassScope() ||
8329          (LangOpts.CPlusPlus &&
8330           S->isFunctionPrototypeScope()) ||
8331          ((S->getFlags() & Scope::DeclScope) == 0) ||
8332          (S->getEntity() && S->getEntity()->isTransparentContext()))
8333     S = S->getParent();
8334   return S;
8335 }
8336 
8337 NamedDecl*
8338 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8339                               TypeSourceInfo *TInfo, LookupResult &Previous,
8340                               MultiTemplateParamsArg TemplateParamLists,
8341                               bool &AddToScope) {
8342   QualType R = TInfo->getType();
8343 
8344   assert(R->isFunctionType());
8345 
8346   // TODO: consider using NameInfo for diagnostic.
8347   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8348   DeclarationName Name = NameInfo.getName();
8349   StorageClass SC = getFunctionStorageClass(*this, D);
8350 
8351   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8352     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8353          diag::err_invalid_thread)
8354       << DeclSpec::getSpecifierName(TSCS);
8355 
8356   if (D.isFirstDeclarationOfMember())
8357     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8358                            D.getIdentifierLoc());
8359 
8360   bool isFriend = false;
8361   FunctionTemplateDecl *FunctionTemplate = nullptr;
8362   bool isMemberSpecialization = false;
8363   bool isFunctionTemplateSpecialization = false;
8364 
8365   bool isDependentClassScopeExplicitSpecialization = false;
8366   bool HasExplicitTemplateArgs = false;
8367   TemplateArgumentListInfo TemplateArgs;
8368 
8369   bool isVirtualOkay = false;
8370 
8371   DeclContext *OriginalDC = DC;
8372   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8373 
8374   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8375                                               isVirtualOkay);
8376   if (!NewFD) return nullptr;
8377 
8378   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8379     NewFD->setTopLevelDeclInObjCContainer();
8380 
8381   // Set the lexical context. If this is a function-scope declaration, or has a
8382   // C++ scope specifier, or is the object of a friend declaration, the lexical
8383   // context will be different from the semantic context.
8384   NewFD->setLexicalDeclContext(CurContext);
8385 
8386   if (IsLocalExternDecl)
8387     NewFD->setLocalExternDecl();
8388 
8389   if (getLangOpts().CPlusPlus) {
8390     bool isInline = D.getDeclSpec().isInlineSpecified();
8391     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8392     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8393     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8394     isFriend = D.getDeclSpec().isFriendSpecified();
8395     if (isFriend && !isInline && D.isFunctionDefinition()) {
8396       // C++ [class.friend]p5
8397       //   A function can be defined in a friend declaration of a
8398       //   class . . . . Such a function is implicitly inline.
8399       NewFD->setImplicitlyInline();
8400     }
8401 
8402     // If this is a method defined in an __interface, and is not a constructor
8403     // or an overloaded operator, then set the pure flag (isVirtual will already
8404     // return true).
8405     if (const CXXRecordDecl *Parent =
8406           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8407       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8408         NewFD->setPure(true);
8409 
8410       // C++ [class.union]p2
8411       //   A union can have member functions, but not virtual functions.
8412       if (isVirtual && Parent->isUnion())
8413         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8414     }
8415 
8416     SetNestedNameSpecifier(*this, NewFD, D);
8417     isMemberSpecialization = false;
8418     isFunctionTemplateSpecialization = false;
8419     if (D.isInvalidType())
8420       NewFD->setInvalidDecl();
8421 
8422     // Match up the template parameter lists with the scope specifier, then
8423     // determine whether we have a template or a template specialization.
8424     bool Invalid = false;
8425     if (TemplateParameterList *TemplateParams =
8426             MatchTemplateParametersToScopeSpecifier(
8427                 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8428                 D.getCXXScopeSpec(),
8429                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8430                     ? D.getName().TemplateId
8431                     : nullptr,
8432                 TemplateParamLists, isFriend, isMemberSpecialization,
8433                 Invalid)) {
8434       if (TemplateParams->size() > 0) {
8435         // This is a function template
8436 
8437         // Check that we can declare a template here.
8438         if (CheckTemplateDeclScope(S, TemplateParams))
8439           NewFD->setInvalidDecl();
8440 
8441         // A destructor cannot be a template.
8442         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8443           Diag(NewFD->getLocation(), diag::err_destructor_template);
8444           NewFD->setInvalidDecl();
8445         }
8446 
8447         // If we're adding a template to a dependent context, we may need to
8448         // rebuilding some of the types used within the template parameter list,
8449         // now that we know what the current instantiation is.
8450         if (DC->isDependentContext()) {
8451           ContextRAII SavedContext(*this, DC);
8452           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8453             Invalid = true;
8454         }
8455 
8456         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8457                                                         NewFD->getLocation(),
8458                                                         Name, TemplateParams,
8459                                                         NewFD);
8460         FunctionTemplate->setLexicalDeclContext(CurContext);
8461         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8462 
8463         // For source fidelity, store the other template param lists.
8464         if (TemplateParamLists.size() > 1) {
8465           NewFD->setTemplateParameterListsInfo(Context,
8466                                                TemplateParamLists.drop_back(1));
8467         }
8468       } else {
8469         // This is a function template specialization.
8470         isFunctionTemplateSpecialization = true;
8471         // For source fidelity, store all the template param lists.
8472         if (TemplateParamLists.size() > 0)
8473           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8474 
8475         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8476         if (isFriend) {
8477           // We want to remove the "template<>", found here.
8478           SourceRange RemoveRange = TemplateParams->getSourceRange();
8479 
8480           // If we remove the template<> and the name is not a
8481           // template-id, we're actually silently creating a problem:
8482           // the friend declaration will refer to an untemplated decl,
8483           // and clearly the user wants a template specialization.  So
8484           // we need to insert '<>' after the name.
8485           SourceLocation InsertLoc;
8486           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8487             InsertLoc = D.getName().getSourceRange().getEnd();
8488             InsertLoc = getLocForEndOfToken(InsertLoc);
8489           }
8490 
8491           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8492             << Name << RemoveRange
8493             << FixItHint::CreateRemoval(RemoveRange)
8494             << FixItHint::CreateInsertion(InsertLoc, "<>");
8495         }
8496       }
8497     } else {
8498       // All template param lists were matched against the scope specifier:
8499       // this is NOT (an explicit specialization of) a template.
8500       if (TemplateParamLists.size() > 0)
8501         // For source fidelity, store all the template param lists.
8502         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8503     }
8504 
8505     if (Invalid) {
8506       NewFD->setInvalidDecl();
8507       if (FunctionTemplate)
8508         FunctionTemplate->setInvalidDecl();
8509     }
8510 
8511     // C++ [dcl.fct.spec]p5:
8512     //   The virtual specifier shall only be used in declarations of
8513     //   nonstatic class member functions that appear within a
8514     //   member-specification of a class declaration; see 10.3.
8515     //
8516     if (isVirtual && !NewFD->isInvalidDecl()) {
8517       if (!isVirtualOkay) {
8518         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8519              diag::err_virtual_non_function);
8520       } else if (!CurContext->isRecord()) {
8521         // 'virtual' was specified outside of the class.
8522         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8523              diag::err_virtual_out_of_class)
8524           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8525       } else if (NewFD->getDescribedFunctionTemplate()) {
8526         // C++ [temp.mem]p3:
8527         //  A member function template shall not be virtual.
8528         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8529              diag::err_virtual_member_function_template)
8530           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8531       } else {
8532         // Okay: Add virtual to the method.
8533         NewFD->setVirtualAsWritten(true);
8534       }
8535 
8536       if (getLangOpts().CPlusPlus14 &&
8537           NewFD->getReturnType()->isUndeducedType())
8538         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8539     }
8540 
8541     if (getLangOpts().CPlusPlus14 &&
8542         (NewFD->isDependentContext() ||
8543          (isFriend && CurContext->isDependentContext())) &&
8544         NewFD->getReturnType()->isUndeducedType()) {
8545       // If the function template is referenced directly (for instance, as a
8546       // member of the current instantiation), pretend it has a dependent type.
8547       // This is not really justified by the standard, but is the only sane
8548       // thing to do.
8549       // FIXME: For a friend function, we have not marked the function as being
8550       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8551       const FunctionProtoType *FPT =
8552           NewFD->getType()->castAs<FunctionProtoType>();
8553       QualType Result =
8554           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8555       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8556                                              FPT->getExtProtoInfo()));
8557     }
8558 
8559     // C++ [dcl.fct.spec]p3:
8560     //  The inline specifier shall not appear on a block scope function
8561     //  declaration.
8562     if (isInline && !NewFD->isInvalidDecl()) {
8563       if (CurContext->isFunctionOrMethod()) {
8564         // 'inline' is not allowed on block scope function declaration.
8565         Diag(D.getDeclSpec().getInlineSpecLoc(),
8566              diag::err_inline_declaration_block_scope) << Name
8567           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8568       }
8569     }
8570 
8571     // C++ [dcl.fct.spec]p6:
8572     //  The explicit specifier shall be used only in the declaration of a
8573     //  constructor or conversion function within its class definition;
8574     //  see 12.3.1 and 12.3.2.
8575     if (isExplicit && !NewFD->isInvalidDecl() &&
8576         !isa<CXXDeductionGuideDecl>(NewFD)) {
8577       if (!CurContext->isRecord()) {
8578         // 'explicit' was specified outside of the class.
8579         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8580              diag::err_explicit_out_of_class)
8581           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8582       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8583                  !isa<CXXConversionDecl>(NewFD)) {
8584         // 'explicit' was specified on a function that wasn't a constructor
8585         // or conversion function.
8586         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8587              diag::err_explicit_non_ctor_or_conv_function)
8588           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8589       }
8590     }
8591 
8592     if (isConstexpr) {
8593       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8594       // are implicitly inline.
8595       NewFD->setImplicitlyInline();
8596 
8597       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8598       // be either constructors or to return a literal type. Therefore,
8599       // destructors cannot be declared constexpr.
8600       if (isa<CXXDestructorDecl>(NewFD))
8601         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8602     }
8603 
8604     // If __module_private__ was specified, mark the function accordingly.
8605     if (D.getDeclSpec().isModulePrivateSpecified()) {
8606       if (isFunctionTemplateSpecialization) {
8607         SourceLocation ModulePrivateLoc
8608           = D.getDeclSpec().getModulePrivateSpecLoc();
8609         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8610           << 0
8611           << FixItHint::CreateRemoval(ModulePrivateLoc);
8612       } else {
8613         NewFD->setModulePrivate();
8614         if (FunctionTemplate)
8615           FunctionTemplate->setModulePrivate();
8616       }
8617     }
8618 
8619     if (isFriend) {
8620       if (FunctionTemplate) {
8621         FunctionTemplate->setObjectOfFriendDecl();
8622         FunctionTemplate->setAccess(AS_public);
8623       }
8624       NewFD->setObjectOfFriendDecl();
8625       NewFD->setAccess(AS_public);
8626     }
8627 
8628     // If a function is defined as defaulted or deleted, mark it as such now.
8629     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8630     // definition kind to FDK_Definition.
8631     switch (D.getFunctionDefinitionKind()) {
8632       case FDK_Declaration:
8633       case FDK_Definition:
8634         break;
8635 
8636       case FDK_Defaulted:
8637         NewFD->setDefaulted();
8638         break;
8639 
8640       case FDK_Deleted:
8641         NewFD->setDeletedAsWritten();
8642         break;
8643     }
8644 
8645     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8646         D.isFunctionDefinition()) {
8647       // C++ [class.mfct]p2:
8648       //   A member function may be defined (8.4) in its class definition, in
8649       //   which case it is an inline member function (7.1.2)
8650       NewFD->setImplicitlyInline();
8651     }
8652 
8653     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8654         !CurContext->isRecord()) {
8655       // C++ [class.static]p1:
8656       //   A data or function member of a class may be declared static
8657       //   in a class definition, in which case it is a static member of
8658       //   the class.
8659 
8660       // Complain about the 'static' specifier if it's on an out-of-line
8661       // member function definition.
8662 
8663       // MSVC permits the use of a 'static' storage specifier on an out-of-line
8664       // member function template declaration, warn about this.
8665       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8666            NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
8667            ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8668         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8669     }
8670 
8671     // C++11 [except.spec]p15:
8672     //   A deallocation function with no exception-specification is treated
8673     //   as if it were specified with noexcept(true).
8674     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8675     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8676          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8677         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8678       NewFD->setType(Context.getFunctionType(
8679           FPT->getReturnType(), FPT->getParamTypes(),
8680           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8681   }
8682 
8683   // Filter out previous declarations that don't match the scope.
8684   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8685                        D.getCXXScopeSpec().isNotEmpty() ||
8686                        isMemberSpecialization ||
8687                        isFunctionTemplateSpecialization);
8688 
8689   // Handle GNU asm-label extension (encoded as an attribute).
8690   if (Expr *E = (Expr*) D.getAsmLabel()) {
8691     // The parser guarantees this is a string.
8692     StringLiteral *SE = cast<StringLiteral>(E);
8693     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8694                                                 SE->getString(), 0));
8695   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8696     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8697       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8698     if (I != ExtnameUndeclaredIdentifiers.end()) {
8699       if (isDeclExternC(NewFD)) {
8700         NewFD->addAttr(I->second);
8701         ExtnameUndeclaredIdentifiers.erase(I);
8702       } else
8703         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8704             << /*Variable*/0 << NewFD;
8705     }
8706   }
8707 
8708   // Copy the parameter declarations from the declarator D to the function
8709   // declaration NewFD, if they are available.  First scavenge them into Params.
8710   SmallVector<ParmVarDecl*, 16> Params;
8711   unsigned FTIIdx;
8712   if (D.isFunctionDeclarator(FTIIdx)) {
8713     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8714 
8715     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8716     // function that takes no arguments, not a function that takes a
8717     // single void argument.
8718     // We let through "const void" here because Sema::GetTypeForDeclarator
8719     // already checks for that case.
8720     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8721       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8722         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8723         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8724         Param->setDeclContext(NewFD);
8725         Params.push_back(Param);
8726 
8727         if (Param->isInvalidDecl())
8728           NewFD->setInvalidDecl();
8729       }
8730     }
8731 
8732     if (!getLangOpts().CPlusPlus) {
8733       // In C, find all the tag declarations from the prototype and move them
8734       // into the function DeclContext. Remove them from the surrounding tag
8735       // injection context of the function, which is typically but not always
8736       // the TU.
8737       DeclContext *PrototypeTagContext =
8738           getTagInjectionContext(NewFD->getLexicalDeclContext());
8739       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8740         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8741 
8742         // We don't want to reparent enumerators. Look at their parent enum
8743         // instead.
8744         if (!TD) {
8745           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8746             TD = cast<EnumDecl>(ECD->getDeclContext());
8747         }
8748         if (!TD)
8749           continue;
8750         DeclContext *TagDC = TD->getLexicalDeclContext();
8751         if (!TagDC->containsDecl(TD))
8752           continue;
8753         TagDC->removeDecl(TD);
8754         TD->setDeclContext(NewFD);
8755         NewFD->addDecl(TD);
8756 
8757         // Preserve the lexical DeclContext if it is not the surrounding tag
8758         // injection context of the FD. In this example, the semantic context of
8759         // E will be f and the lexical context will be S, while both the
8760         // semantic and lexical contexts of S will be f:
8761         //   void f(struct S { enum E { a } f; } s);
8762         if (TagDC != PrototypeTagContext)
8763           TD->setLexicalDeclContext(TagDC);
8764       }
8765     }
8766   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8767     // When we're declaring a function with a typedef, typeof, etc as in the
8768     // following example, we'll need to synthesize (unnamed)
8769     // parameters for use in the declaration.
8770     //
8771     // @code
8772     // typedef void fn(int);
8773     // fn f;
8774     // @endcode
8775 
8776     // Synthesize a parameter for each argument type.
8777     for (const auto &AI : FT->param_types()) {
8778       ParmVarDecl *Param =
8779           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8780       Param->setScopeInfo(0, Params.size());
8781       Params.push_back(Param);
8782     }
8783   } else {
8784     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8785            "Should not need args for typedef of non-prototype fn");
8786   }
8787 
8788   // Finally, we know we have the right number of parameters, install them.
8789   NewFD->setParams(Params);
8790 
8791   if (D.getDeclSpec().isNoreturnSpecified())
8792     NewFD->addAttr(
8793         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8794                                        Context, 0));
8795 
8796   // Functions returning a variably modified type violate C99 6.7.5.2p2
8797   // because all functions have linkage.
8798   if (!NewFD->isInvalidDecl() &&
8799       NewFD->getReturnType()->isVariablyModifiedType()) {
8800     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8801     NewFD->setInvalidDecl();
8802   }
8803 
8804   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8805   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8806       !NewFD->hasAttr<SectionAttr>()) {
8807     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8808                                                  PragmaClangTextSection.SectionName,
8809                                                  PragmaClangTextSection.PragmaLocation));
8810   }
8811 
8812   // Apply an implicit SectionAttr if #pragma code_seg is active.
8813   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8814       !NewFD->hasAttr<SectionAttr>()) {
8815     NewFD->addAttr(
8816         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8817                                     CodeSegStack.CurrentValue->getString(),
8818                                     CodeSegStack.CurrentPragmaLocation));
8819     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8820                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8821                          ASTContext::PSF_Read,
8822                      NewFD))
8823       NewFD->dropAttr<SectionAttr>();
8824   }
8825 
8826   // Apply an implicit CodeSegAttr from class declspec or
8827   // apply an implicit SectionAttr from #pragma code_seg if active.
8828   if (!NewFD->hasAttr<CodeSegAttr>()) {
8829     if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8830                                                                  D.isFunctionDefinition())) {
8831       NewFD->addAttr(SAttr);
8832     }
8833   }
8834 
8835   // Handle attributes.
8836   ProcessDeclAttributes(S, NewFD, D);
8837 
8838   if (getLangOpts().OpenCL) {
8839     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8840     // type declaration will generate a compilation error.
8841     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8842     if (AddressSpace != LangAS::Default) {
8843       Diag(NewFD->getLocation(),
8844            diag::err_opencl_return_value_with_address_space);
8845       NewFD->setInvalidDecl();
8846     }
8847   }
8848 
8849   if (!getLangOpts().CPlusPlus) {
8850     // Perform semantic checking on the function declaration.
8851     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8852       CheckMain(NewFD, D.getDeclSpec());
8853 
8854     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8855       CheckMSVCRTEntryPoint(NewFD);
8856 
8857     if (!NewFD->isInvalidDecl())
8858       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8859                                                   isMemberSpecialization));
8860     else if (!Previous.empty())
8861       // Recover gracefully from an invalid redeclaration.
8862       D.setRedeclaration(true);
8863     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8864             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8865            "previous declaration set still overloaded");
8866 
8867     // Diagnose no-prototype function declarations with calling conventions that
8868     // don't support variadic calls. Only do this in C and do it after merging
8869     // possibly prototyped redeclarations.
8870     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8871     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8872       CallingConv CC = FT->getExtInfo().getCC();
8873       if (!supportsVariadicCall(CC)) {
8874         // Windows system headers sometimes accidentally use stdcall without
8875         // (void) parameters, so we relax this to a warning.
8876         int DiagID =
8877             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8878         Diag(NewFD->getLocation(), DiagID)
8879             << FunctionType::getNameForCallConv(CC);
8880       }
8881     }
8882   } else {
8883     // C++11 [replacement.functions]p3:
8884     //  The program's definitions shall not be specified as inline.
8885     //
8886     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8887     //
8888     // Suppress the diagnostic if the function is __attribute__((used)), since
8889     // that forces an external definition to be emitted.
8890     if (D.getDeclSpec().isInlineSpecified() &&
8891         NewFD->isReplaceableGlobalAllocationFunction() &&
8892         !NewFD->hasAttr<UsedAttr>())
8893       Diag(D.getDeclSpec().getInlineSpecLoc(),
8894            diag::ext_operator_new_delete_declared_inline)
8895         << NewFD->getDeclName();
8896 
8897     // If the declarator is a template-id, translate the parser's template
8898     // argument list into our AST format.
8899     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8900       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8901       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8902       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8903       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8904                                          TemplateId->NumArgs);
8905       translateTemplateArguments(TemplateArgsPtr,
8906                                  TemplateArgs);
8907 
8908       HasExplicitTemplateArgs = true;
8909 
8910       if (NewFD->isInvalidDecl()) {
8911         HasExplicitTemplateArgs = false;
8912       } else if (FunctionTemplate) {
8913         // Function template with explicit template arguments.
8914         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8915           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8916 
8917         HasExplicitTemplateArgs = false;
8918       } else {
8919         assert((isFunctionTemplateSpecialization ||
8920                 D.getDeclSpec().isFriendSpecified()) &&
8921                "should have a 'template<>' for this decl");
8922         // "friend void foo<>(int);" is an implicit specialization decl.
8923         isFunctionTemplateSpecialization = true;
8924       }
8925     } else if (isFriend && isFunctionTemplateSpecialization) {
8926       // This combination is only possible in a recovery case;  the user
8927       // wrote something like:
8928       //   template <> friend void foo(int);
8929       // which we're recovering from as if the user had written:
8930       //   friend void foo<>(int);
8931       // Go ahead and fake up a template id.
8932       HasExplicitTemplateArgs = true;
8933       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8934       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8935     }
8936 
8937     // We do not add HD attributes to specializations here because
8938     // they may have different constexpr-ness compared to their
8939     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8940     // may end up with different effective targets. Instead, a
8941     // specialization inherits its target attributes from its template
8942     // in the CheckFunctionTemplateSpecialization() call below.
8943     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8944       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8945 
8946     // If it's a friend (and only if it's a friend), it's possible
8947     // that either the specialized function type or the specialized
8948     // template is dependent, and therefore matching will fail.  In
8949     // this case, don't check the specialization yet.
8950     bool InstantiationDependent = false;
8951     if (isFunctionTemplateSpecialization && isFriend &&
8952         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8953          TemplateSpecializationType::anyDependentTemplateArguments(
8954             TemplateArgs,
8955             InstantiationDependent))) {
8956       assert(HasExplicitTemplateArgs &&
8957              "friend function specialization without template args");
8958       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8959                                                        Previous))
8960         NewFD->setInvalidDecl();
8961     } else if (isFunctionTemplateSpecialization) {
8962       if (CurContext->isDependentContext() && CurContext->isRecord()
8963           && !isFriend) {
8964         isDependentClassScopeExplicitSpecialization = true;
8965       } else if (!NewFD->isInvalidDecl() &&
8966                  CheckFunctionTemplateSpecialization(
8967                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8968                      Previous))
8969         NewFD->setInvalidDecl();
8970 
8971       // C++ [dcl.stc]p1:
8972       //   A storage-class-specifier shall not be specified in an explicit
8973       //   specialization (14.7.3)
8974       FunctionTemplateSpecializationInfo *Info =
8975           NewFD->getTemplateSpecializationInfo();
8976       if (Info && SC != SC_None) {
8977         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8978           Diag(NewFD->getLocation(),
8979                diag::err_explicit_specialization_inconsistent_storage_class)
8980             << SC
8981             << FixItHint::CreateRemoval(
8982                                       D.getDeclSpec().getStorageClassSpecLoc());
8983 
8984         else
8985           Diag(NewFD->getLocation(),
8986                diag::ext_explicit_specialization_storage_class)
8987             << FixItHint::CreateRemoval(
8988                                       D.getDeclSpec().getStorageClassSpecLoc());
8989       }
8990     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8991       if (CheckMemberSpecialization(NewFD, Previous))
8992           NewFD->setInvalidDecl();
8993     }
8994 
8995     // Perform semantic checking on the function declaration.
8996     if (!isDependentClassScopeExplicitSpecialization) {
8997       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8998         CheckMain(NewFD, D.getDeclSpec());
8999 
9000       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9001         CheckMSVCRTEntryPoint(NewFD);
9002 
9003       if (!NewFD->isInvalidDecl())
9004         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9005                                                     isMemberSpecialization));
9006       else if (!Previous.empty())
9007         // Recover gracefully from an invalid redeclaration.
9008         D.setRedeclaration(true);
9009     }
9010 
9011     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9012             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9013            "previous declaration set still overloaded");
9014 
9015     NamedDecl *PrincipalDecl = (FunctionTemplate
9016                                 ? cast<NamedDecl>(FunctionTemplate)
9017                                 : NewFD);
9018 
9019     if (isFriend && NewFD->getPreviousDecl()) {
9020       AccessSpecifier Access = AS_public;
9021       if (!NewFD->isInvalidDecl())
9022         Access = NewFD->getPreviousDecl()->getAccess();
9023 
9024       NewFD->setAccess(Access);
9025       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9026     }
9027 
9028     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9029         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9030       PrincipalDecl->setNonMemberOperator();
9031 
9032     // If we have a function template, check the template parameter
9033     // list. This will check and merge default template arguments.
9034     if (FunctionTemplate) {
9035       FunctionTemplateDecl *PrevTemplate =
9036                                      FunctionTemplate->getPreviousDecl();
9037       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9038                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9039                                     : nullptr,
9040                             D.getDeclSpec().isFriendSpecified()
9041                               ? (D.isFunctionDefinition()
9042                                    ? TPC_FriendFunctionTemplateDefinition
9043                                    : TPC_FriendFunctionTemplate)
9044                               : (D.getCXXScopeSpec().isSet() &&
9045                                  DC && DC->isRecord() &&
9046                                  DC->isDependentContext())
9047                                   ? TPC_ClassTemplateMember
9048                                   : TPC_FunctionTemplate);
9049     }
9050 
9051     if (NewFD->isInvalidDecl()) {
9052       // Ignore all the rest of this.
9053     } else if (!D.isRedeclaration()) {
9054       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9055                                        AddToScope };
9056       // Fake up an access specifier if it's supposed to be a class member.
9057       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9058         NewFD->setAccess(AS_public);
9059 
9060       // Qualified decls generally require a previous declaration.
9061       if (D.getCXXScopeSpec().isSet()) {
9062         // ...with the major exception of templated-scope or
9063         // dependent-scope friend declarations.
9064 
9065         // TODO: we currently also suppress this check in dependent
9066         // contexts because (1) the parameter depth will be off when
9067         // matching friend templates and (2) we might actually be
9068         // selecting a friend based on a dependent factor.  But there
9069         // are situations where these conditions don't apply and we
9070         // can actually do this check immediately.
9071         //
9072         // Unless the scope is dependent, it's always an error if qualified
9073         // redeclaration lookup found nothing at all. Diagnose that now;
9074         // nothing will diagnose that error later.
9075         if (isFriend &&
9076             (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9077              (!Previous.empty() && (TemplateParamLists.size() ||
9078                                     CurContext->isDependentContext())))) {
9079           // ignore these
9080         } else {
9081           // The user tried to provide an out-of-line definition for a
9082           // function that is a member of a class or namespace, but there
9083           // was no such member function declared (C++ [class.mfct]p2,
9084           // C++ [namespace.memdef]p2). For example:
9085           //
9086           // class X {
9087           //   void f() const;
9088           // };
9089           //
9090           // void X::f() { } // ill-formed
9091           //
9092           // Complain about this problem, and attempt to suggest close
9093           // matches (e.g., those that differ only in cv-qualifiers and
9094           // whether the parameter types are references).
9095 
9096           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9097                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9098             AddToScope = ExtraArgs.AddToScope;
9099             return Result;
9100           }
9101         }
9102 
9103         // Unqualified local friend declarations are required to resolve
9104         // to something.
9105       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9106         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9107                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9108           AddToScope = ExtraArgs.AddToScope;
9109           return Result;
9110         }
9111       }
9112     } else if (!D.isFunctionDefinition() &&
9113                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9114                !isFriend && !isFunctionTemplateSpecialization &&
9115                !isMemberSpecialization) {
9116       // An out-of-line member function declaration must also be a
9117       // definition (C++ [class.mfct]p2).
9118       // Note that this is not the case for explicit specializations of
9119       // function templates or member functions of class templates, per
9120       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9121       // extension for compatibility with old SWIG code which likes to
9122       // generate them.
9123       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9124         << D.getCXXScopeSpec().getRange();
9125     }
9126   }
9127 
9128   ProcessPragmaWeak(S, NewFD);
9129   checkAttributesAfterMerging(*this, *NewFD);
9130 
9131   AddKnownFunctionAttributes(NewFD);
9132 
9133   if (NewFD->hasAttr<OverloadableAttr>() &&
9134       !NewFD->getType()->getAs<FunctionProtoType>()) {
9135     Diag(NewFD->getLocation(),
9136          diag::err_attribute_overloadable_no_prototype)
9137       << NewFD;
9138 
9139     // Turn this into a variadic function with no parameters.
9140     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9141     FunctionProtoType::ExtProtoInfo EPI(
9142         Context.getDefaultCallingConvention(true, false));
9143     EPI.Variadic = true;
9144     EPI.ExtInfo = FT->getExtInfo();
9145 
9146     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9147     NewFD->setType(R);
9148   }
9149 
9150   // If there's a #pragma GCC visibility in scope, and this isn't a class
9151   // member, set the visibility of this function.
9152   if (!DC->isRecord() && NewFD->isExternallyVisible())
9153     AddPushedVisibilityAttribute(NewFD);
9154 
9155   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9156   // marking the function.
9157   AddCFAuditedAttribute(NewFD);
9158 
9159   // If this is a function definition, check if we have to apply optnone due to
9160   // a pragma.
9161   if(D.isFunctionDefinition())
9162     AddRangeBasedOptnone(NewFD);
9163 
9164   // If this is the first declaration of an extern C variable, update
9165   // the map of such variables.
9166   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9167       isIncompleteDeclExternC(*this, NewFD))
9168     RegisterLocallyScopedExternCDecl(NewFD, S);
9169 
9170   // Set this FunctionDecl's range up to the right paren.
9171   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9172 
9173   if (D.isRedeclaration() && !Previous.empty()) {
9174     NamedDecl *Prev = Previous.getRepresentativeDecl();
9175     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9176                                    isMemberSpecialization ||
9177                                        isFunctionTemplateSpecialization,
9178                                    D.isFunctionDefinition());
9179   }
9180 
9181   if (getLangOpts().CUDA) {
9182     IdentifierInfo *II = NewFD->getIdentifier();
9183     if (II && II->isStr(getCudaConfigureFuncName()) &&
9184         !NewFD->isInvalidDecl() &&
9185         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9186       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9187         Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9188             << getCudaConfigureFuncName();
9189       Context.setcudaConfigureCallDecl(NewFD);
9190     }
9191 
9192     // Variadic functions, other than a *declaration* of printf, are not allowed
9193     // in device-side CUDA code, unless someone passed
9194     // -fcuda-allow-variadic-functions.
9195     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9196         (NewFD->hasAttr<CUDADeviceAttr>() ||
9197          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9198         !(II && II->isStr("printf") && NewFD->isExternC() &&
9199           !D.isFunctionDefinition())) {
9200       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9201     }
9202   }
9203 
9204   MarkUnusedFileScopedDecl(NewFD);
9205 
9206   if (getLangOpts().CPlusPlus) {
9207     if (FunctionTemplate) {
9208       if (NewFD->isInvalidDecl())
9209         FunctionTemplate->setInvalidDecl();
9210       return FunctionTemplate;
9211     }
9212 
9213     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9214       CompleteMemberSpecialization(NewFD, Previous);
9215   }
9216 
9217   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9218     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9219     if ((getLangOpts().OpenCLVersion >= 120)
9220         && (SC == SC_Static)) {
9221       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9222       D.setInvalidType();
9223     }
9224 
9225     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9226     if (!NewFD->getReturnType()->isVoidType()) {
9227       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9228       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9229           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9230                                 : FixItHint());
9231       D.setInvalidType();
9232     }
9233 
9234     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9235     for (auto Param : NewFD->parameters())
9236       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9237   }
9238   for (const ParmVarDecl *Param : NewFD->parameters()) {
9239     QualType PT = Param->getType();
9240 
9241     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9242     // types.
9243     if (getLangOpts().OpenCLVersion >= 200) {
9244       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9245         QualType ElemTy = PipeTy->getElementType();
9246           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9247             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9248             D.setInvalidType();
9249           }
9250       }
9251     }
9252   }
9253 
9254   // Here we have an function template explicit specialization at class scope.
9255   // The actual specialization will be postponed to template instatiation
9256   // time via the ClassScopeFunctionSpecializationDecl node.
9257   if (isDependentClassScopeExplicitSpecialization) {
9258     ClassScopeFunctionSpecializationDecl *NewSpec =
9259                          ClassScopeFunctionSpecializationDecl::Create(
9260                                 Context, CurContext, NewFD->getLocation(),
9261                                 cast<CXXMethodDecl>(NewFD),
9262                                 HasExplicitTemplateArgs, TemplateArgs);
9263     CurContext->addDecl(NewSpec);
9264     AddToScope = false;
9265   }
9266 
9267   // Diagnose availability attributes. Availability cannot be used on functions
9268   // that are run during load/unload.
9269   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9270     if (NewFD->hasAttr<ConstructorAttr>()) {
9271       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9272           << 1;
9273       NewFD->dropAttr<AvailabilityAttr>();
9274     }
9275     if (NewFD->hasAttr<DestructorAttr>()) {
9276       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9277           << 2;
9278       NewFD->dropAttr<AvailabilityAttr>();
9279     }
9280   }
9281 
9282   return NewFD;
9283 }
9284 
9285 /// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9286 /// when __declspec(code_seg) "is applied to a class, all member functions of
9287 /// the class and nested classes -- this includes compiler-generated special
9288 /// member functions -- are put in the specified segment."
9289 /// The actual behavior is a little more complicated. The Microsoft compiler
9290 /// won't check outer classes if there is an active value from #pragma code_seg.
9291 /// The CodeSeg is always applied from the direct parent but only from outer
9292 /// classes when the #pragma code_seg stack is empty. See:
9293 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9294 /// available since MS has removed the page.
9295 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9296   const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9297   if (!Method)
9298     return nullptr;
9299   const CXXRecordDecl *Parent = Method->getParent();
9300   if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9301     Attr *NewAttr = SAttr->clone(S.getASTContext());
9302     NewAttr->setImplicit(true);
9303     return NewAttr;
9304   }
9305 
9306   // The Microsoft compiler won't check outer classes for the CodeSeg
9307   // when the #pragma code_seg stack is active.
9308   if (S.CodeSegStack.CurrentValue)
9309    return nullptr;
9310 
9311   while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9312     if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9313       Attr *NewAttr = SAttr->clone(S.getASTContext());
9314       NewAttr->setImplicit(true);
9315       return NewAttr;
9316     }
9317   }
9318   return nullptr;
9319 }
9320 
9321 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9322 /// containing class. Otherwise it will return implicit SectionAttr if the
9323 /// function is a definition and there is an active value on CodeSegStack
9324 /// (from the current #pragma code-seg value).
9325 ///
9326 /// \param FD Function being declared.
9327 /// \param IsDefinition Whether it is a definition or just a declarartion.
9328 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
9329 ///          nullptr if no attribute should be added.
9330 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9331                                                        bool IsDefinition) {
9332   if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9333     return A;
9334   if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9335       CodeSegStack.CurrentValue) {
9336     return SectionAttr::CreateImplicit(getASTContext(),
9337                                        SectionAttr::Declspec_allocate,
9338                                        CodeSegStack.CurrentValue->getString(),
9339                                        CodeSegStack.CurrentPragmaLocation);
9340   }
9341   return nullptr;
9342 }
9343 
9344 /// Determines if we can perform a correct type check for \p D as a
9345 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
9346 /// best-effort check.
9347 ///
9348 /// \param NewD The new declaration.
9349 /// \param OldD The old declaration.
9350 /// \param NewT The portion of the type of the new declaration to check.
9351 /// \param OldT The portion of the type of the old declaration to check.
9352 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9353                                           QualType NewT, QualType OldT) {
9354   if (!NewD->getLexicalDeclContext()->isDependentContext())
9355     return true;
9356 
9357   // For dependently-typed local extern declarations and friends, we can't
9358   // perform a correct type check in general until instantiation:
9359   //
9360   //   int f();
9361   //   template<typename T> void g() { T f(); }
9362   //
9363   // (valid if g() is only instantiated with T = int).
9364   if (NewT->isDependentType() &&
9365       (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9366     return false;
9367 
9368   // Similarly, if the previous declaration was a dependent local extern
9369   // declaration, we don't really know its type yet.
9370   if (OldT->isDependentType() && OldD->isLocalExternDecl())
9371     return false;
9372 
9373   return true;
9374 }
9375 
9376 /// Checks if the new declaration declared in dependent context must be
9377 /// put in the same redeclaration chain as the specified declaration.
9378 ///
9379 /// \param D Declaration that is checked.
9380 /// \param PrevDecl Previous declaration found with proper lookup method for the
9381 ///                 same declaration name.
9382 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9383 ///          belongs to.
9384 ///
9385 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9386   if (!D->getLexicalDeclContext()->isDependentContext())
9387     return true;
9388 
9389   // Don't chain dependent friend function definitions until instantiation, to
9390   // permit cases like
9391   //
9392   //   void func();
9393   //   template<typename T> class C1 { friend void func() {} };
9394   //   template<typename T> class C2 { friend void func() {} };
9395   //
9396   // ... which is valid if only one of C1 and C2 is ever instantiated.
9397   //
9398   // FIXME: This need only apply to function definitions. For now, we proxy
9399   // this by checking for a file-scope function. We do not want this to apply
9400   // to friend declarations nominating member functions, because that gets in
9401   // the way of access checks.
9402   if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9403     return false;
9404 
9405   auto *VD = dyn_cast<ValueDecl>(D);
9406   auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9407   return !VD || !PrevVD ||
9408          canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9409                                         PrevVD->getType());
9410 }
9411 
9412 /// Check the target attribute of the function for MultiVersion
9413 /// validity.
9414 ///
9415 /// Returns true if there was an error, false otherwise.
9416 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9417   const auto *TA = FD->getAttr<TargetAttr>();
9418   assert(TA && "MultiVersion Candidate requires a target attribute");
9419   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9420   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9421   enum ErrType { Feature = 0, Architecture = 1 };
9422 
9423   if (!ParseInfo.Architecture.empty() &&
9424       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9425     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9426         << Architecture << ParseInfo.Architecture;
9427     return true;
9428   }
9429 
9430   for (const auto &Feat : ParseInfo.Features) {
9431     auto BareFeat = StringRef{Feat}.substr(1);
9432     if (Feat[0] == '-') {
9433       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9434           << Feature << ("no-" + BareFeat).str();
9435       return true;
9436     }
9437 
9438     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9439         !TargetInfo.isValidFeatureName(BareFeat)) {
9440       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9441           << Feature << BareFeat;
9442       return true;
9443     }
9444   }
9445   return false;
9446 }
9447 
9448 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9449                                          MultiVersionKind MVType) {
9450   for (const Attr *A : FD->attrs()) {
9451     switch (A->getKind()) {
9452     case attr::CPUDispatch:
9453     case attr::CPUSpecific:
9454       if (MVType != MultiVersionKind::CPUDispatch &&
9455           MVType != MultiVersionKind::CPUSpecific)
9456         return true;
9457       break;
9458     case attr::Target:
9459       if (MVType != MultiVersionKind::Target)
9460         return true;
9461       break;
9462     default:
9463       return true;
9464     }
9465   }
9466   return false;
9467 }
9468 
9469 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9470                                              const FunctionDecl *NewFD,
9471                                              bool CausesMV,
9472                                              MultiVersionKind MVType) {
9473   enum DoesntSupport {
9474     FuncTemplates = 0,
9475     VirtFuncs = 1,
9476     DeducedReturn = 2,
9477     Constructors = 3,
9478     Destructors = 4,
9479     DeletedFuncs = 5,
9480     DefaultedFuncs = 6,
9481     ConstexprFuncs = 7,
9482   };
9483   enum Different {
9484     CallingConv = 0,
9485     ReturnType = 1,
9486     ConstexprSpec = 2,
9487     InlineSpec = 3,
9488     StorageClass = 4,
9489     Linkage = 5
9490   };
9491 
9492   bool IsCPUSpecificCPUDispatchMVType =
9493       MVType == MultiVersionKind::CPUDispatch ||
9494       MVType == MultiVersionKind::CPUSpecific;
9495 
9496   if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9497     S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9498     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9499     return true;
9500   }
9501 
9502   if (!NewFD->getType()->getAs<FunctionProtoType>())
9503     return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9504 
9505   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9506     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9507     if (OldFD)
9508       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9509     return true;
9510   }
9511 
9512   // For now, disallow all other attributes.  These should be opt-in, but
9513   // an analysis of all of them is a future FIXME.
9514   if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) {
9515     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9516         << IsCPUSpecificCPUDispatchMVType;
9517     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9518     return true;
9519   }
9520 
9521   if (HasNonMultiVersionAttributes(NewFD, MVType))
9522     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9523            << IsCPUSpecificCPUDispatchMVType;
9524 
9525   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9526     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9527            << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9528 
9529   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9530     if (NewCXXFD->isVirtual())
9531       return S.Diag(NewCXXFD->getLocation(),
9532                     diag::err_multiversion_doesnt_support)
9533              << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9534 
9535     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9536       return S.Diag(NewCXXCtor->getLocation(),
9537                     diag::err_multiversion_doesnt_support)
9538              << IsCPUSpecificCPUDispatchMVType << Constructors;
9539 
9540     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9541       return S.Diag(NewCXXDtor->getLocation(),
9542                     diag::err_multiversion_doesnt_support)
9543              << IsCPUSpecificCPUDispatchMVType << Destructors;
9544   }
9545 
9546   if (NewFD->isDeleted())
9547     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9548            << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9549 
9550   if (NewFD->isDefaulted())
9551     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9552            << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9553 
9554   if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9555                                MVType == MultiVersionKind::CPUSpecific))
9556     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9557            << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9558 
9559   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9560   const auto *NewType = cast<FunctionType>(NewQType);
9561   QualType NewReturnType = NewType->getReturnType();
9562 
9563   if (NewReturnType->isUndeducedType())
9564     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9565            << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9566 
9567   // Only allow transition to MultiVersion if it hasn't been used.
9568   if (OldFD && CausesMV && OldFD->isUsed(false))
9569     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9570 
9571   // Ensure the return type is identical.
9572   if (OldFD) {
9573     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9574     const auto *OldType = cast<FunctionType>(OldQType);
9575     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9576     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9577 
9578     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9579       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9580              << CallingConv;
9581 
9582     QualType OldReturnType = OldType->getReturnType();
9583 
9584     if (OldReturnType != NewReturnType)
9585       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9586              << ReturnType;
9587 
9588     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9589       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9590              << ConstexprSpec;
9591 
9592     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9593       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9594              << InlineSpec;
9595 
9596     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9597       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9598              << StorageClass;
9599 
9600     if (OldFD->isExternC() != NewFD->isExternC())
9601       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9602              << Linkage;
9603 
9604     if (S.CheckEquivalentExceptionSpec(
9605             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9606             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9607       return true;
9608   }
9609   return false;
9610 }
9611 
9612 /// Check the validity of a multiversion function declaration that is the
9613 /// first of its kind. Also sets the multiversion'ness' of the function itself.
9614 ///
9615 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9616 ///
9617 /// Returns true if there was an error, false otherwise.
9618 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
9619                                            MultiVersionKind MVType,
9620                                            const TargetAttr *TA) {
9621   assert(MVType != MultiVersionKind::None &&
9622          "Function lacks multiversion attribute");
9623 
9624   // Target only causes MV if it is default, otherwise this is a normal
9625   // function.
9626   if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9627     return false;
9628 
9629   if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
9630     FD->setInvalidDecl();
9631     return true;
9632   }
9633 
9634   if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
9635     FD->setInvalidDecl();
9636     return true;
9637   }
9638 
9639   FD->setIsMultiVersion();
9640   return false;
9641 }
9642 
9643 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9644   for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
9645     if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9646       return true;
9647   }
9648 
9649   return false;
9650 }
9651 
9652 static bool CheckTargetCausesMultiVersioning(
9653     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
9654     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9655     LookupResult &Previous) {
9656   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9657   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9658   // Sort order doesn't matter, it just needs to be consistent.
9659   llvm::sort(NewParsed.Features);
9660 
9661   // If the old decl is NOT MultiVersioned yet, and we don't cause that
9662   // to change, this is a simple redeclaration.
9663   if (!NewTA->isDefaultVersion() &&
9664       (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9665     return false;
9666 
9667   // Otherwise, this decl causes MultiVersioning.
9668   if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9669     S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9670     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9671     NewFD->setInvalidDecl();
9672     return true;
9673   }
9674 
9675   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
9676                                        MultiVersionKind::Target)) {
9677     NewFD->setInvalidDecl();
9678     return true;
9679   }
9680 
9681   if (CheckMultiVersionValue(S, NewFD)) {
9682     NewFD->setInvalidDecl();
9683     return true;
9684   }
9685 
9686   // If this is 'default', permit the forward declaration.
9687   if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9688     Redeclaration = true;
9689     OldDecl = OldFD;
9690     OldFD->setIsMultiVersion();
9691     NewFD->setIsMultiVersion();
9692     return false;
9693   }
9694 
9695   if (CheckMultiVersionValue(S, OldFD)) {
9696     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9697     NewFD->setInvalidDecl();
9698     return true;
9699   }
9700 
9701   TargetAttr::ParsedTargetAttr OldParsed =
9702       OldTA->parse(std::less<std::string>());
9703 
9704   if (OldParsed == NewParsed) {
9705     S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9706     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9707     NewFD->setInvalidDecl();
9708     return true;
9709   }
9710 
9711   for (const auto *FD : OldFD->redecls()) {
9712     const auto *CurTA = FD->getAttr<TargetAttr>();
9713     // We allow forward declarations before ANY multiversioning attributes, but
9714     // nothing after the fact.
9715     if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9716         (!CurTA || CurTA->isInherited())) {
9717       S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9718           << 0;
9719       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9720       NewFD->setInvalidDecl();
9721       return true;
9722     }
9723   }
9724 
9725   OldFD->setIsMultiVersion();
9726   NewFD->setIsMultiVersion();
9727   Redeclaration = false;
9728   MergeTypeWithPrevious = false;
9729   OldDecl = nullptr;
9730   Previous.clear();
9731   return false;
9732 }
9733 
9734 /// Check the validity of a new function declaration being added to an existing
9735 /// multiversioned declaration collection.
9736 static bool CheckMultiVersionAdditionalDecl(
9737     Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
9738     MultiVersionKind NewMVType, const TargetAttr *NewTA,
9739     const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
9740     bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
9741     LookupResult &Previous) {
9742 
9743   MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9744   // Disallow mixing of multiversioning types.
9745   if ((OldMVType == MultiVersionKind::Target &&
9746        NewMVType != MultiVersionKind::Target) ||
9747       (NewMVType == MultiVersionKind::Target &&
9748        OldMVType != MultiVersionKind::Target)) {
9749     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9750     S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9751     NewFD->setInvalidDecl();
9752     return true;
9753   }
9754 
9755   TargetAttr::ParsedTargetAttr NewParsed;
9756   if (NewTA) {
9757     NewParsed = NewTA->parse();
9758     llvm::sort(NewParsed.Features);
9759   }
9760 
9761   bool UseMemberUsingDeclRules =
9762       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9763 
9764   // Next, check ALL non-overloads to see if this is a redeclaration of a
9765   // previous member of the MultiVersion set.
9766   for (NamedDecl *ND : Previous) {
9767     FunctionDecl *CurFD = ND->getAsFunction();
9768     if (!CurFD)
9769       continue;
9770     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9771       continue;
9772 
9773     if (NewMVType == MultiVersionKind::Target) {
9774       const auto *CurTA = CurFD->getAttr<TargetAttr>();
9775       if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9776         NewFD->setIsMultiVersion();
9777         Redeclaration = true;
9778         OldDecl = ND;
9779         return false;
9780       }
9781 
9782       TargetAttr::ParsedTargetAttr CurParsed =
9783           CurTA->parse(std::less<std::string>());
9784       if (CurParsed == NewParsed) {
9785         S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9786         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9787         NewFD->setInvalidDecl();
9788         return true;
9789       }
9790     } else {
9791       const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9792       const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9793       // Handle CPUDispatch/CPUSpecific versions.
9794       // Only 1 CPUDispatch function is allowed, this will make it go through
9795       // the redeclaration errors.
9796       if (NewMVType == MultiVersionKind::CPUDispatch &&
9797           CurFD->hasAttr<CPUDispatchAttr>()) {
9798         if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9799             std::equal(
9800                 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9801                 NewCPUDisp->cpus_begin(),
9802                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9803                   return Cur->getName() == New->getName();
9804                 })) {
9805           NewFD->setIsMultiVersion();
9806           Redeclaration = true;
9807           OldDecl = ND;
9808           return false;
9809         }
9810 
9811         // If the declarations don't match, this is an error condition.
9812         S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9813         S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9814         NewFD->setInvalidDecl();
9815         return true;
9816       }
9817       if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9818 
9819         if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9820             std::equal(
9821                 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9822                 NewCPUSpec->cpus_begin(),
9823                 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9824                   return Cur->getName() == New->getName();
9825                 })) {
9826           NewFD->setIsMultiVersion();
9827           Redeclaration = true;
9828           OldDecl = ND;
9829           return false;
9830         }
9831 
9832         // Only 1 version of CPUSpecific is allowed for each CPU.
9833         for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9834           for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9835             if (CurII == NewII) {
9836               S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9837                   << NewII;
9838               S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9839               NewFD->setInvalidDecl();
9840               return true;
9841             }
9842           }
9843         }
9844       }
9845       // If the two decls aren't the same MVType, there is no possible error
9846       // condition.
9847     }
9848   }
9849 
9850   // Else, this is simply a non-redecl case.  Checking the 'value' is only
9851   // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9852   // handled in the attribute adding step.
9853   if (NewMVType == MultiVersionKind::Target &&
9854       CheckMultiVersionValue(S, NewFD)) {
9855     NewFD->setInvalidDecl();
9856     return true;
9857   }
9858 
9859   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
9860                                        !OldFD->isMultiVersion(), NewMVType)) {
9861     NewFD->setInvalidDecl();
9862     return true;
9863   }
9864 
9865   // Permit forward declarations in the case where these two are compatible.
9866   if (!OldFD->isMultiVersion()) {
9867     OldFD->setIsMultiVersion();
9868     NewFD->setIsMultiVersion();
9869     Redeclaration = true;
9870     OldDecl = OldFD;
9871     return false;
9872   }
9873 
9874   NewFD->setIsMultiVersion();
9875   Redeclaration = false;
9876   MergeTypeWithPrevious = false;
9877   OldDecl = nullptr;
9878   Previous.clear();
9879   return false;
9880 }
9881 
9882 
9883 /// Check the validity of a mulitversion function declaration.
9884 /// Also sets the multiversion'ness' of the function itself.
9885 ///
9886 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9887 ///
9888 /// Returns true if there was an error, false otherwise.
9889 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9890                                       bool &Redeclaration, NamedDecl *&OldDecl,
9891                                       bool &MergeTypeWithPrevious,
9892                                       LookupResult &Previous) {
9893   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9894   const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9895   const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9896 
9897   // Mixing Multiversioning types is prohibited.
9898   if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9899       (NewCPUDisp && NewCPUSpec)) {
9900     S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9901     NewFD->setInvalidDecl();
9902     return true;
9903   }
9904 
9905   MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9906 
9907   // Main isn't allowed to become a multiversion function, however it IS
9908   // permitted to have 'main' be marked with the 'target' optimization hint.
9909   if (NewFD->isMain()) {
9910     if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9911         MVType == MultiVersionKind::CPUDispatch ||
9912         MVType == MultiVersionKind::CPUSpecific) {
9913       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9914       NewFD->setInvalidDecl();
9915       return true;
9916     }
9917     return false;
9918   }
9919 
9920   if (!OldDecl || !OldDecl->getAsFunction() ||
9921       OldDecl->getDeclContext()->getRedeclContext() !=
9922           NewFD->getDeclContext()->getRedeclContext()) {
9923     // If there's no previous declaration, AND this isn't attempting to cause
9924     // multiversioning, this isn't an error condition.
9925     if (MVType == MultiVersionKind::None)
9926       return false;
9927     return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
9928   }
9929 
9930   FunctionDecl *OldFD = OldDecl->getAsFunction();
9931 
9932   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9933     return false;
9934 
9935   if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9936     S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9937         << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9938     NewFD->setInvalidDecl();
9939     return true;
9940   }
9941 
9942   // Handle the target potentially causes multiversioning case.
9943   if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
9944     return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9945                                             Redeclaration, OldDecl,
9946                                             MergeTypeWithPrevious, Previous);
9947 
9948   // At this point, we have a multiversion function decl (in OldFD) AND an
9949   // appropriate attribute in the current function decl.  Resolve that these are
9950   // still compatible with previous declarations.
9951   return CheckMultiVersionAdditionalDecl(
9952       S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9953       OldDecl, MergeTypeWithPrevious, Previous);
9954 }
9955 
9956 /// Perform semantic checking of a new function declaration.
9957 ///
9958 /// Performs semantic analysis of the new function declaration
9959 /// NewFD. This routine performs all semantic checking that does not
9960 /// require the actual declarator involved in the declaration, and is
9961 /// used both for the declaration of functions as they are parsed
9962 /// (called via ActOnDeclarator) and for the declaration of functions
9963 /// that have been instantiated via C++ template instantiation (called
9964 /// via InstantiateDecl).
9965 ///
9966 /// \param IsMemberSpecialization whether this new function declaration is
9967 /// a member specialization (that replaces any definition provided by the
9968 /// previous declaration).
9969 ///
9970 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9971 ///
9972 /// \returns true if the function declaration is a redeclaration.
9973 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9974                                     LookupResult &Previous,
9975                                     bool IsMemberSpecialization) {
9976   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9977          "Variably modified return types are not handled here");
9978 
9979   // Determine whether the type of this function should be merged with
9980   // a previous visible declaration. This never happens for functions in C++,
9981   // and always happens in C if the previous declaration was visible.
9982   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9983                                !Previous.isShadowed();
9984 
9985   bool Redeclaration = false;
9986   NamedDecl *OldDecl = nullptr;
9987   bool MayNeedOverloadableChecks = false;
9988 
9989   // Merge or overload the declaration with an existing declaration of
9990   // the same name, if appropriate.
9991   if (!Previous.empty()) {
9992     // Determine whether NewFD is an overload of PrevDecl or
9993     // a declaration that requires merging. If it's an overload,
9994     // there's no more work to do here; we'll just add the new
9995     // function to the scope.
9996     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9997       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9998       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9999         Redeclaration = true;
10000         OldDecl = Candidate;
10001       }
10002     } else {
10003       MayNeedOverloadableChecks = true;
10004       switch (CheckOverload(S, NewFD, Previous, OldDecl,
10005                             /*NewIsUsingDecl*/ false)) {
10006       case Ovl_Match:
10007         Redeclaration = true;
10008         break;
10009 
10010       case Ovl_NonFunction:
10011         Redeclaration = true;
10012         break;
10013 
10014       case Ovl_Overload:
10015         Redeclaration = false;
10016         break;
10017       }
10018     }
10019   }
10020 
10021   // Check for a previous extern "C" declaration with this name.
10022   if (!Redeclaration &&
10023       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10024     if (!Previous.empty()) {
10025       // This is an extern "C" declaration with the same name as a previous
10026       // declaration, and thus redeclares that entity...
10027       Redeclaration = true;
10028       OldDecl = Previous.getFoundDecl();
10029       MergeTypeWithPrevious = false;
10030 
10031       // ... except in the presence of __attribute__((overloadable)).
10032       if (OldDecl->hasAttr<OverloadableAttr>() ||
10033           NewFD->hasAttr<OverloadableAttr>()) {
10034         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10035           MayNeedOverloadableChecks = true;
10036           Redeclaration = false;
10037           OldDecl = nullptr;
10038         }
10039       }
10040     }
10041   }
10042 
10043   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10044                                 MergeTypeWithPrevious, Previous))
10045     return Redeclaration;
10046 
10047   // C++11 [dcl.constexpr]p8:
10048   //   A constexpr specifier for a non-static member function that is not
10049   //   a constructor declares that member function to be const.
10050   //
10051   // This needs to be delayed until we know whether this is an out-of-line
10052   // definition of a static member function.
10053   //
10054   // This rule is not present in C++1y, so we produce a backwards
10055   // compatibility warning whenever it happens in C++11.
10056   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10057   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10058       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10059       !MD->getMethodQualifiers().hasConst()) {
10060     CXXMethodDecl *OldMD = nullptr;
10061     if (OldDecl)
10062       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10063     if (!OldMD || !OldMD->isStatic()) {
10064       const FunctionProtoType *FPT =
10065         MD->getType()->castAs<FunctionProtoType>();
10066       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10067       EPI.TypeQuals.addConst();
10068       MD->setType(Context.getFunctionType(FPT->getReturnType(),
10069                                           FPT->getParamTypes(), EPI));
10070 
10071       // Warn that we did this, if we're not performing template instantiation.
10072       // In that case, we'll have warned already when the template was defined.
10073       if (!inTemplateInstantiation()) {
10074         SourceLocation AddConstLoc;
10075         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10076                 .IgnoreParens().getAs<FunctionTypeLoc>())
10077           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10078 
10079         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10080           << FixItHint::CreateInsertion(AddConstLoc, " const");
10081       }
10082     }
10083   }
10084 
10085   if (Redeclaration) {
10086     // NewFD and OldDecl represent declarations that need to be
10087     // merged.
10088     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10089       NewFD->setInvalidDecl();
10090       return Redeclaration;
10091     }
10092 
10093     Previous.clear();
10094     Previous.addDecl(OldDecl);
10095 
10096     if (FunctionTemplateDecl *OldTemplateDecl =
10097             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10098       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10099       FunctionTemplateDecl *NewTemplateDecl
10100         = NewFD->getDescribedFunctionTemplate();
10101       assert(NewTemplateDecl && "Template/non-template mismatch");
10102 
10103       // The call to MergeFunctionDecl above may have created some state in
10104       // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10105       // can add it as a redeclaration.
10106       NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10107 
10108       NewFD->setPreviousDeclaration(OldFD);
10109       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10110       if (NewFD->isCXXClassMember()) {
10111         NewFD->setAccess(OldTemplateDecl->getAccess());
10112         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10113       }
10114 
10115       // If this is an explicit specialization of a member that is a function
10116       // template, mark it as a member specialization.
10117       if (IsMemberSpecialization &&
10118           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10119         NewTemplateDecl->setMemberSpecialization();
10120         assert(OldTemplateDecl->isMemberSpecialization());
10121         // Explicit specializations of a member template do not inherit deleted
10122         // status from the parent member template that they are specializing.
10123         if (OldFD->isDeleted()) {
10124           // FIXME: This assert will not hold in the presence of modules.
10125           assert(OldFD->getCanonicalDecl() == OldFD);
10126           // FIXME: We need an update record for this AST mutation.
10127           OldFD->setDeletedAsWritten(false);
10128         }
10129       }
10130 
10131     } else {
10132       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10133         auto *OldFD = cast<FunctionDecl>(OldDecl);
10134         // This needs to happen first so that 'inline' propagates.
10135         NewFD->setPreviousDeclaration(OldFD);
10136         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10137         if (NewFD->isCXXClassMember())
10138           NewFD->setAccess(OldFD->getAccess());
10139       }
10140     }
10141   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10142              !NewFD->getAttr<OverloadableAttr>()) {
10143     assert((Previous.empty() ||
10144             llvm::any_of(Previous,
10145                          [](const NamedDecl *ND) {
10146                            return ND->hasAttr<OverloadableAttr>();
10147                          })) &&
10148            "Non-redecls shouldn't happen without overloadable present");
10149 
10150     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10151       const auto *FD = dyn_cast<FunctionDecl>(ND);
10152       return FD && !FD->hasAttr<OverloadableAttr>();
10153     });
10154 
10155     if (OtherUnmarkedIter != Previous.end()) {
10156       Diag(NewFD->getLocation(),
10157            diag::err_attribute_overloadable_multiple_unmarked_overloads);
10158       Diag((*OtherUnmarkedIter)->getLocation(),
10159            diag::note_attribute_overloadable_prev_overload)
10160           << false;
10161 
10162       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10163     }
10164   }
10165 
10166   // Semantic checking for this function declaration (in isolation).
10167 
10168   if (getLangOpts().CPlusPlus) {
10169     // C++-specific checks.
10170     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10171       CheckConstructor(Constructor);
10172     } else if (CXXDestructorDecl *Destructor =
10173                 dyn_cast<CXXDestructorDecl>(NewFD)) {
10174       CXXRecordDecl *Record = Destructor->getParent();
10175       QualType ClassType = Context.getTypeDeclType(Record);
10176 
10177       // FIXME: Shouldn't we be able to perform this check even when the class
10178       // type is dependent? Both gcc and edg can handle that.
10179       if (!ClassType->isDependentType()) {
10180         DeclarationName Name
10181           = Context.DeclarationNames.getCXXDestructorName(
10182                                         Context.getCanonicalType(ClassType));
10183         if (NewFD->getDeclName() != Name) {
10184           Diag(NewFD->getLocation(), diag::err_destructor_name);
10185           NewFD->setInvalidDecl();
10186           return Redeclaration;
10187         }
10188       }
10189     } else if (CXXConversionDecl *Conversion
10190                = dyn_cast<CXXConversionDecl>(NewFD)) {
10191       ActOnConversionDeclarator(Conversion);
10192     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10193       if (auto *TD = Guide->getDescribedFunctionTemplate())
10194         CheckDeductionGuideTemplate(TD);
10195 
10196       // A deduction guide is not on the list of entities that can be
10197       // explicitly specialized.
10198       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10199         Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10200             << /*explicit specialization*/ 1;
10201     }
10202 
10203     // Find any virtual functions that this function overrides.
10204     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10205       if (!Method->isFunctionTemplateSpecialization() &&
10206           !Method->getDescribedFunctionTemplate() &&
10207           Method->isCanonicalDecl()) {
10208         if (AddOverriddenMethods(Method->getParent(), Method)) {
10209           // If the function was marked as "static", we have a problem.
10210           if (NewFD->getStorageClass() == SC_Static) {
10211             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10212           }
10213         }
10214       }
10215 
10216       if (Method->isStatic())
10217         checkThisInStaticMemberFunctionType(Method);
10218     }
10219 
10220     // Extra checking for C++ overloaded operators (C++ [over.oper]).
10221     if (NewFD->isOverloadedOperator() &&
10222         CheckOverloadedOperatorDeclaration(NewFD)) {
10223       NewFD->setInvalidDecl();
10224       return Redeclaration;
10225     }
10226 
10227     // Extra checking for C++0x literal operators (C++0x [over.literal]).
10228     if (NewFD->getLiteralIdentifier() &&
10229         CheckLiteralOperatorDeclaration(NewFD)) {
10230       NewFD->setInvalidDecl();
10231       return Redeclaration;
10232     }
10233 
10234     // In C++, check default arguments now that we have merged decls. Unless
10235     // the lexical context is the class, because in this case this is done
10236     // during delayed parsing anyway.
10237     if (!CurContext->isRecord())
10238       CheckCXXDefaultArguments(NewFD);
10239 
10240     // If this function declares a builtin function, check the type of this
10241     // declaration against the expected type for the builtin.
10242     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10243       ASTContext::GetBuiltinTypeError Error;
10244       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10245       QualType T = Context.GetBuiltinType(BuiltinID, Error);
10246       // If the type of the builtin differs only in its exception
10247       // specification, that's OK.
10248       // FIXME: If the types do differ in this way, it would be better to
10249       // retain the 'noexcept' form of the type.
10250       if (!T.isNull() &&
10251           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10252                                                             NewFD->getType()))
10253         // The type of this function differs from the type of the builtin,
10254         // so forget about the builtin entirely.
10255         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10256     }
10257 
10258     // If this function is declared as being extern "C", then check to see if
10259     // the function returns a UDT (class, struct, or union type) that is not C
10260     // compatible, and if it does, warn the user.
10261     // But, issue any diagnostic on the first declaration only.
10262     if (Previous.empty() && NewFD->isExternC()) {
10263       QualType R = NewFD->getReturnType();
10264       if (R->isIncompleteType() && !R->isVoidType())
10265         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10266             << NewFD << R;
10267       else if (!R.isPODType(Context) && !R->isVoidType() &&
10268                !R->isObjCObjectPointerType())
10269         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10270     }
10271 
10272     // C++1z [dcl.fct]p6:
10273     //   [...] whether the function has a non-throwing exception-specification
10274     //   [is] part of the function type
10275     //
10276     // This results in an ABI break between C++14 and C++17 for functions whose
10277     // declared type includes an exception-specification in a parameter or
10278     // return type. (Exception specifications on the function itself are OK in
10279     // most cases, and exception specifications are not permitted in most other
10280     // contexts where they could make it into a mangling.)
10281     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10282       auto HasNoexcept = [&](QualType T) -> bool {
10283         // Strip off declarator chunks that could be between us and a function
10284         // type. We don't need to look far, exception specifications are very
10285         // restricted prior to C++17.
10286         if (auto *RT = T->getAs<ReferenceType>())
10287           T = RT->getPointeeType();
10288         else if (T->isAnyPointerType())
10289           T = T->getPointeeType();
10290         else if (auto *MPT = T->getAs<MemberPointerType>())
10291           T = MPT->getPointeeType();
10292         if (auto *FPT = T->getAs<FunctionProtoType>())
10293           if (FPT->isNothrow())
10294             return true;
10295         return false;
10296       };
10297 
10298       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10299       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10300       for (QualType T : FPT->param_types())
10301         AnyNoexcept |= HasNoexcept(T);
10302       if (AnyNoexcept)
10303         Diag(NewFD->getLocation(),
10304              diag::warn_cxx17_compat_exception_spec_in_signature)
10305             << NewFD;
10306     }
10307 
10308     if (!Redeclaration && LangOpts.CUDA)
10309       checkCUDATargetOverload(NewFD, Previous);
10310   }
10311   return Redeclaration;
10312 }
10313 
10314 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10315   // C++11 [basic.start.main]p3:
10316   //   A program that [...] declares main to be inline, static or
10317   //   constexpr is ill-formed.
10318   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10319   //   appear in a declaration of main.
10320   // static main is not an error under C99, but we should warn about it.
10321   // We accept _Noreturn main as an extension.
10322   if (FD->getStorageClass() == SC_Static)
10323     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10324          ? diag::err_static_main : diag::warn_static_main)
10325       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10326   if (FD->isInlineSpecified())
10327     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10328       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10329   if (DS.isNoreturnSpecified()) {
10330     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10331     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10332     Diag(NoreturnLoc, diag::ext_noreturn_main);
10333     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10334       << FixItHint::CreateRemoval(NoreturnRange);
10335   }
10336   if (FD->isConstexpr()) {
10337     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10338       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10339     FD->setConstexpr(false);
10340   }
10341 
10342   if (getLangOpts().OpenCL) {
10343     Diag(FD->getLocation(), diag::err_opencl_no_main)
10344         << FD->hasAttr<OpenCLKernelAttr>();
10345     FD->setInvalidDecl();
10346     return;
10347   }
10348 
10349   QualType T = FD->getType();
10350   assert(T->isFunctionType() && "function decl is not of function type");
10351   const FunctionType* FT = T->castAs<FunctionType>();
10352 
10353   // Set default calling convention for main()
10354   if (FT->getCallConv() != CC_C) {
10355     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10356     FD->setType(QualType(FT, 0));
10357     T = Context.getCanonicalType(FD->getType());
10358   }
10359 
10360   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10361     // In C with GNU extensions we allow main() to have non-integer return
10362     // type, but we should warn about the extension, and we disable the
10363     // implicit-return-zero rule.
10364 
10365     // GCC in C mode accepts qualified 'int'.
10366     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10367       FD->setHasImplicitReturnZero(true);
10368     else {
10369       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10370       SourceRange RTRange = FD->getReturnTypeSourceRange();
10371       if (RTRange.isValid())
10372         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10373             << FixItHint::CreateReplacement(RTRange, "int");
10374     }
10375   } else {
10376     // In C and C++, main magically returns 0 if you fall off the end;
10377     // set the flag which tells us that.
10378     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10379 
10380     // All the standards say that main() should return 'int'.
10381     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10382       FD->setHasImplicitReturnZero(true);
10383     else {
10384       // Otherwise, this is just a flat-out error.
10385       SourceRange RTRange = FD->getReturnTypeSourceRange();
10386       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10387           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10388                                 : FixItHint());
10389       FD->setInvalidDecl(true);
10390     }
10391   }
10392 
10393   // Treat protoless main() as nullary.
10394   if (isa<FunctionNoProtoType>(FT)) return;
10395 
10396   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
10397   unsigned nparams = FTP->getNumParams();
10398   assert(FD->getNumParams() == nparams);
10399 
10400   bool HasExtraParameters = (nparams > 3);
10401 
10402   if (FTP->isVariadic()) {
10403     Diag(FD->getLocation(), diag::ext_variadic_main);
10404     // FIXME: if we had information about the location of the ellipsis, we
10405     // could add a FixIt hint to remove it as a parameter.
10406   }
10407 
10408   // Darwin passes an undocumented fourth argument of type char**.  If
10409   // other platforms start sprouting these, the logic below will start
10410   // getting shifty.
10411   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10412     HasExtraParameters = false;
10413 
10414   if (HasExtraParameters) {
10415     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10416     FD->setInvalidDecl(true);
10417     nparams = 3;
10418   }
10419 
10420   // FIXME: a lot of the following diagnostics would be improved
10421   // if we had some location information about types.
10422 
10423   QualType CharPP =
10424     Context.getPointerType(Context.getPointerType(Context.CharTy));
10425   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
10426 
10427   for (unsigned i = 0; i < nparams; ++i) {
10428     QualType AT = FTP->getParamType(i);
10429 
10430     bool mismatch = true;
10431 
10432     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
10433       mismatch = false;
10434     else if (Expected[i] == CharPP) {
10435       // As an extension, the following forms are okay:
10436       //   char const **
10437       //   char const * const *
10438       //   char * const *
10439 
10440       QualifierCollector qs;
10441       const PointerType* PT;
10442       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10443           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10444           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10445                               Context.CharTy)) {
10446         qs.removeConst();
10447         mismatch = !qs.empty();
10448       }
10449     }
10450 
10451     if (mismatch) {
10452       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10453       // TODO: suggest replacing given type with expected type
10454       FD->setInvalidDecl(true);
10455     }
10456   }
10457 
10458   if (nparams == 1 && !FD->isInvalidDecl()) {
10459     Diag(FD->getLocation(), diag::warn_main_one_arg);
10460   }
10461 
10462   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10463     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10464     FD->setInvalidDecl();
10465   }
10466 }
10467 
10468 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10469   QualType T = FD->getType();
10470   assert(T->isFunctionType() && "function decl is not of function type");
10471   const FunctionType *FT = T->castAs<FunctionType>();
10472 
10473   // Set an implicit return of 'zero' if the function can return some integral,
10474   // enumeration, pointer or nullptr type.
10475   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10476       FT->getReturnType()->isAnyPointerType() ||
10477       FT->getReturnType()->isNullPtrType())
10478     // DllMain is exempt because a return value of zero means it failed.
10479     if (FD->getName() != "DllMain")
10480       FD->setHasImplicitReturnZero(true);
10481 
10482   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10483     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10484     FD->setInvalidDecl();
10485   }
10486 }
10487 
10488 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10489   // FIXME: Need strict checking.  In C89, we need to check for
10490   // any assignment, increment, decrement, function-calls, or
10491   // commas outside of a sizeof.  In C99, it's the same list,
10492   // except that the aforementioned are allowed in unevaluated
10493   // expressions.  Everything else falls under the
10494   // "may accept other forms of constant expressions" exception.
10495   // (We never end up here for C++, so the constant expression
10496   // rules there don't matter.)
10497   const Expr *Culprit;
10498   if (Init->isConstantInitializer(Context, false, &Culprit))
10499     return false;
10500   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10501     << Culprit->getSourceRange();
10502   return true;
10503 }
10504 
10505 namespace {
10506   // Visits an initialization expression to see if OrigDecl is evaluated in
10507   // its own initialization and throws a warning if it does.
10508   class SelfReferenceChecker
10509       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10510     Sema &S;
10511     Decl *OrigDecl;
10512     bool isRecordType;
10513     bool isPODType;
10514     bool isReferenceType;
10515 
10516     bool isInitList;
10517     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10518 
10519   public:
10520     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10521 
10522     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10523                                                     S(S), OrigDecl(OrigDecl) {
10524       isPODType = false;
10525       isRecordType = false;
10526       isReferenceType = false;
10527       isInitList = false;
10528       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10529         isPODType = VD->getType().isPODType(S.Context);
10530         isRecordType = VD->getType()->isRecordType();
10531         isReferenceType = VD->getType()->isReferenceType();
10532       }
10533     }
10534 
10535     // For most expressions, just call the visitor.  For initializer lists,
10536     // track the index of the field being initialized since fields are
10537     // initialized in order allowing use of previously initialized fields.
10538     void CheckExpr(Expr *E) {
10539       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10540       if (!InitList) {
10541         Visit(E);
10542         return;
10543       }
10544 
10545       // Track and increment the index here.
10546       isInitList = true;
10547       InitFieldIndex.push_back(0);
10548       for (auto Child : InitList->children()) {
10549         CheckExpr(cast<Expr>(Child));
10550         ++InitFieldIndex.back();
10551       }
10552       InitFieldIndex.pop_back();
10553     }
10554 
10555     // Returns true if MemberExpr is checked and no further checking is needed.
10556     // Returns false if additional checking is required.
10557     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10558       llvm::SmallVector<FieldDecl*, 4> Fields;
10559       Expr *Base = E;
10560       bool ReferenceField = false;
10561 
10562       // Get the field members used.
10563       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10564         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10565         if (!FD)
10566           return false;
10567         Fields.push_back(FD);
10568         if (FD->getType()->isReferenceType())
10569           ReferenceField = true;
10570         Base = ME->getBase()->IgnoreParenImpCasts();
10571       }
10572 
10573       // Keep checking only if the base Decl is the same.
10574       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10575       if (!DRE || DRE->getDecl() != OrigDecl)
10576         return false;
10577 
10578       // A reference field can be bound to an unininitialized field.
10579       if (CheckReference && !ReferenceField)
10580         return true;
10581 
10582       // Convert FieldDecls to their index number.
10583       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10584       for (const FieldDecl *I : llvm::reverse(Fields))
10585         UsedFieldIndex.push_back(I->getFieldIndex());
10586 
10587       // See if a warning is needed by checking the first difference in index
10588       // numbers.  If field being used has index less than the field being
10589       // initialized, then the use is safe.
10590       for (auto UsedIter = UsedFieldIndex.begin(),
10591                 UsedEnd = UsedFieldIndex.end(),
10592                 OrigIter = InitFieldIndex.begin(),
10593                 OrigEnd = InitFieldIndex.end();
10594            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10595         if (*UsedIter < *OrigIter)
10596           return true;
10597         if (*UsedIter > *OrigIter)
10598           break;
10599       }
10600 
10601       // TODO: Add a different warning which will print the field names.
10602       HandleDeclRefExpr(DRE);
10603       return true;
10604     }
10605 
10606     // For most expressions, the cast is directly above the DeclRefExpr.
10607     // For conditional operators, the cast can be outside the conditional
10608     // operator if both expressions are DeclRefExpr's.
10609     void HandleValue(Expr *E) {
10610       E = E->IgnoreParens();
10611       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10612         HandleDeclRefExpr(DRE);
10613         return;
10614       }
10615 
10616       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10617         Visit(CO->getCond());
10618         HandleValue(CO->getTrueExpr());
10619         HandleValue(CO->getFalseExpr());
10620         return;
10621       }
10622 
10623       if (BinaryConditionalOperator *BCO =
10624               dyn_cast<BinaryConditionalOperator>(E)) {
10625         Visit(BCO->getCond());
10626         HandleValue(BCO->getFalseExpr());
10627         return;
10628       }
10629 
10630       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10631         HandleValue(OVE->getSourceExpr());
10632         return;
10633       }
10634 
10635       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10636         if (BO->getOpcode() == BO_Comma) {
10637           Visit(BO->getLHS());
10638           HandleValue(BO->getRHS());
10639           return;
10640         }
10641       }
10642 
10643       if (isa<MemberExpr>(E)) {
10644         if (isInitList) {
10645           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10646                                       false /*CheckReference*/))
10647             return;
10648         }
10649 
10650         Expr *Base = E->IgnoreParenImpCasts();
10651         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10652           // Check for static member variables and don't warn on them.
10653           if (!isa<FieldDecl>(ME->getMemberDecl()))
10654             return;
10655           Base = ME->getBase()->IgnoreParenImpCasts();
10656         }
10657         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10658           HandleDeclRefExpr(DRE);
10659         return;
10660       }
10661 
10662       Visit(E);
10663     }
10664 
10665     // Reference types not handled in HandleValue are handled here since all
10666     // uses of references are bad, not just r-value uses.
10667     void VisitDeclRefExpr(DeclRefExpr *E) {
10668       if (isReferenceType)
10669         HandleDeclRefExpr(E);
10670     }
10671 
10672     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10673       if (E->getCastKind() == CK_LValueToRValue) {
10674         HandleValue(E->getSubExpr());
10675         return;
10676       }
10677 
10678       Inherited::VisitImplicitCastExpr(E);
10679     }
10680 
10681     void VisitMemberExpr(MemberExpr *E) {
10682       if (isInitList) {
10683         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10684           return;
10685       }
10686 
10687       // Don't warn on arrays since they can be treated as pointers.
10688       if (E->getType()->canDecayToPointerType()) return;
10689 
10690       // Warn when a non-static method call is followed by non-static member
10691       // field accesses, which is followed by a DeclRefExpr.
10692       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10693       bool Warn = (MD && !MD->isStatic());
10694       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10695       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10696         if (!isa<FieldDecl>(ME->getMemberDecl()))
10697           Warn = false;
10698         Base = ME->getBase()->IgnoreParenImpCasts();
10699       }
10700 
10701       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10702         if (Warn)
10703           HandleDeclRefExpr(DRE);
10704         return;
10705       }
10706 
10707       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10708       // Visit that expression.
10709       Visit(Base);
10710     }
10711 
10712     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10713       Expr *Callee = E->getCallee();
10714 
10715       if (isa<UnresolvedLookupExpr>(Callee))
10716         return Inherited::VisitCXXOperatorCallExpr(E);
10717 
10718       Visit(Callee);
10719       for (auto Arg: E->arguments())
10720         HandleValue(Arg->IgnoreParenImpCasts());
10721     }
10722 
10723     void VisitUnaryOperator(UnaryOperator *E) {
10724       // For POD record types, addresses of its own members are well-defined.
10725       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10726           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10727         if (!isPODType)
10728           HandleValue(E->getSubExpr());
10729         return;
10730       }
10731 
10732       if (E->isIncrementDecrementOp()) {
10733         HandleValue(E->getSubExpr());
10734         return;
10735       }
10736 
10737       Inherited::VisitUnaryOperator(E);
10738     }
10739 
10740     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10741 
10742     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10743       if (E->getConstructor()->isCopyConstructor()) {
10744         Expr *ArgExpr = E->getArg(0);
10745         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10746           if (ILE->getNumInits() == 1)
10747             ArgExpr = ILE->getInit(0);
10748         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10749           if (ICE->getCastKind() == CK_NoOp)
10750             ArgExpr = ICE->getSubExpr();
10751         HandleValue(ArgExpr);
10752         return;
10753       }
10754       Inherited::VisitCXXConstructExpr(E);
10755     }
10756 
10757     void VisitCallExpr(CallExpr *E) {
10758       // Treat std::move as a use.
10759       if (E->isCallToStdMove()) {
10760         HandleValue(E->getArg(0));
10761         return;
10762       }
10763 
10764       Inherited::VisitCallExpr(E);
10765     }
10766 
10767     void VisitBinaryOperator(BinaryOperator *E) {
10768       if (E->isCompoundAssignmentOp()) {
10769         HandleValue(E->getLHS());
10770         Visit(E->getRHS());
10771         return;
10772       }
10773 
10774       Inherited::VisitBinaryOperator(E);
10775     }
10776 
10777     // A custom visitor for BinaryConditionalOperator is needed because the
10778     // regular visitor would check the condition and true expression separately
10779     // but both point to the same place giving duplicate diagnostics.
10780     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10781       Visit(E->getCond());
10782       Visit(E->getFalseExpr());
10783     }
10784 
10785     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10786       Decl* ReferenceDecl = DRE->getDecl();
10787       if (OrigDecl != ReferenceDecl) return;
10788       unsigned diag;
10789       if (isReferenceType) {
10790         diag = diag::warn_uninit_self_reference_in_reference_init;
10791       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10792         diag = diag::warn_static_self_reference_in_init;
10793       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10794                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10795                  DRE->getDecl()->getType()->isRecordType()) {
10796         diag = diag::warn_uninit_self_reference_in_init;
10797       } else {
10798         // Local variables will be handled by the CFG analysis.
10799         return;
10800       }
10801 
10802       S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10803                             S.PDiag(diag)
10804                                 << DRE->getDecl() << OrigDecl->getLocation()
10805                                 << DRE->getSourceRange());
10806     }
10807   };
10808 
10809   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10810   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10811                                  bool DirectInit) {
10812     // Parameters arguments are occassionially constructed with itself,
10813     // for instance, in recursive functions.  Skip them.
10814     if (isa<ParmVarDecl>(OrigDecl))
10815       return;
10816 
10817     E = E->IgnoreParens();
10818 
10819     // Skip checking T a = a where T is not a record or reference type.
10820     // Doing so is a way to silence uninitialized warnings.
10821     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10822       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10823         if (ICE->getCastKind() == CK_LValueToRValue)
10824           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10825             if (DRE->getDecl() == OrigDecl)
10826               return;
10827 
10828     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10829   }
10830 } // end anonymous namespace
10831 
10832 namespace {
10833   // Simple wrapper to add the name of a variable or (if no variable is
10834   // available) a DeclarationName into a diagnostic.
10835   struct VarDeclOrName {
10836     VarDecl *VDecl;
10837     DeclarationName Name;
10838 
10839     friend const Sema::SemaDiagnosticBuilder &
10840     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10841       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10842     }
10843   };
10844 } // end anonymous namespace
10845 
10846 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10847                                             DeclarationName Name, QualType Type,
10848                                             TypeSourceInfo *TSI,
10849                                             SourceRange Range, bool DirectInit,
10850                                             Expr *&Init) {
10851   bool IsInitCapture = !VDecl;
10852   assert((!VDecl || !VDecl->isInitCapture()) &&
10853          "init captures are expected to be deduced prior to initialization");
10854 
10855   VarDeclOrName VN{VDecl, Name};
10856 
10857   DeducedType *Deduced = Type->getContainedDeducedType();
10858   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10859 
10860   // C++11 [dcl.spec.auto]p3
10861   if (!Init) {
10862     assert(VDecl && "no init for init capture deduction?");
10863 
10864     // Except for class argument deduction, and then for an initializing
10865     // declaration only, i.e. no static at class scope or extern.
10866     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10867         VDecl->hasExternalStorage() ||
10868         VDecl->isStaticDataMember()) {
10869       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10870         << VDecl->getDeclName() << Type;
10871       return QualType();
10872     }
10873   }
10874 
10875   ArrayRef<Expr*> DeduceInits;
10876   if (Init)
10877     DeduceInits = Init;
10878 
10879   if (DirectInit) {
10880     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10881       DeduceInits = PL->exprs();
10882   }
10883 
10884   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10885     assert(VDecl && "non-auto type for init capture deduction?");
10886     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10887     InitializationKind Kind = InitializationKind::CreateForInit(
10888         VDecl->getLocation(), DirectInit, Init);
10889     // FIXME: Initialization should not be taking a mutable list of inits.
10890     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10891     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10892                                                        InitsCopy);
10893   }
10894 
10895   if (DirectInit) {
10896     if (auto *IL = dyn_cast<InitListExpr>(Init))
10897       DeduceInits = IL->inits();
10898   }
10899 
10900   // Deduction only works if we have exactly one source expression.
10901   if (DeduceInits.empty()) {
10902     // It isn't possible to write this directly, but it is possible to
10903     // end up in this situation with "auto x(some_pack...);"
10904     Diag(Init->getBeginLoc(), IsInitCapture
10905                                   ? diag::err_init_capture_no_expression
10906                                   : diag::err_auto_var_init_no_expression)
10907         << VN << Type << Range;
10908     return QualType();
10909   }
10910 
10911   if (DeduceInits.size() > 1) {
10912     Diag(DeduceInits[1]->getBeginLoc(),
10913          IsInitCapture ? diag::err_init_capture_multiple_expressions
10914                        : diag::err_auto_var_init_multiple_expressions)
10915         << VN << Type << Range;
10916     return QualType();
10917   }
10918 
10919   Expr *DeduceInit = DeduceInits[0];
10920   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10921     Diag(Init->getBeginLoc(), IsInitCapture
10922                                   ? diag::err_init_capture_paren_braces
10923                                   : diag::err_auto_var_init_paren_braces)
10924         << isa<InitListExpr>(Init) << VN << Type << Range;
10925     return QualType();
10926   }
10927 
10928   // Expressions default to 'id' when we're in a debugger.
10929   bool DefaultedAnyToId = false;
10930   if (getLangOpts().DebuggerCastResultToId &&
10931       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10932     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10933     if (Result.isInvalid()) {
10934       return QualType();
10935     }
10936     Init = Result.get();
10937     DefaultedAnyToId = true;
10938   }
10939 
10940   // C++ [dcl.decomp]p1:
10941   //   If the assignment-expression [...] has array type A and no ref-qualifier
10942   //   is present, e has type cv A
10943   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10944       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10945       DeduceInit->getType()->isConstantArrayType())
10946     return Context.getQualifiedType(DeduceInit->getType(),
10947                                     Type.getQualifiers());
10948 
10949   QualType DeducedType;
10950   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10951     if (!IsInitCapture)
10952       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10953     else if (isa<InitListExpr>(Init))
10954       Diag(Range.getBegin(),
10955            diag::err_init_capture_deduction_failure_from_init_list)
10956           << VN
10957           << (DeduceInit->getType().isNull() ? TSI->getType()
10958                                              : DeduceInit->getType())
10959           << DeduceInit->getSourceRange();
10960     else
10961       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10962           << VN << TSI->getType()
10963           << (DeduceInit->getType().isNull() ? TSI->getType()
10964                                              : DeduceInit->getType())
10965           << DeduceInit->getSourceRange();
10966   } else
10967     Init = DeduceInit;
10968 
10969   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10970   // 'id' instead of a specific object type prevents most of our usual
10971   // checks.
10972   // We only want to warn outside of template instantiations, though:
10973   // inside a template, the 'id' could have come from a parameter.
10974   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10975       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10976     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10977     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10978   }
10979 
10980   return DeducedType;
10981 }
10982 
10983 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10984                                          Expr *&Init) {
10985   QualType DeducedType = deduceVarTypeFromInitializer(
10986       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10987       VDecl->getSourceRange(), DirectInit, Init);
10988   if (DeducedType.isNull()) {
10989     VDecl->setInvalidDecl();
10990     return true;
10991   }
10992 
10993   VDecl->setType(DeducedType);
10994   assert(VDecl->isLinkageValid());
10995 
10996   // In ARC, infer lifetime.
10997   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10998     VDecl->setInvalidDecl();
10999 
11000   // If this is a redeclaration, check that the type we just deduced matches
11001   // the previously declared type.
11002   if (VarDecl *Old = VDecl->getPreviousDecl()) {
11003     // We never need to merge the type, because we cannot form an incomplete
11004     // array of auto, nor deduce such a type.
11005     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11006   }
11007 
11008   // Check the deduced type is valid for a variable declaration.
11009   CheckVariableDeclarationType(VDecl);
11010   return VDecl->isInvalidDecl();
11011 }
11012 
11013 /// AddInitializerToDecl - Adds the initializer Init to the
11014 /// declaration dcl. If DirectInit is true, this is C++ direct
11015 /// initialization rather than copy initialization.
11016 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11017   // If there is no declaration, there was an error parsing it.  Just ignore
11018   // the initializer.
11019   if (!RealDecl || RealDecl->isInvalidDecl()) {
11020     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11021     return;
11022   }
11023 
11024   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11025     // Pure-specifiers are handled in ActOnPureSpecifier.
11026     Diag(Method->getLocation(), diag::err_member_function_initialization)
11027       << Method->getDeclName() << Init->getSourceRange();
11028     Method->setInvalidDecl();
11029     return;
11030   }
11031 
11032   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11033   if (!VDecl) {
11034     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11035     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11036     RealDecl->setInvalidDecl();
11037     return;
11038   }
11039 
11040   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11041   if (VDecl->getType()->isUndeducedType()) {
11042     // Attempt typo correction early so that the type of the init expression can
11043     // be deduced based on the chosen correction if the original init contains a
11044     // TypoExpr.
11045     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11046     if (!Res.isUsable()) {
11047       RealDecl->setInvalidDecl();
11048       return;
11049     }
11050     Init = Res.get();
11051 
11052     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11053       return;
11054   }
11055 
11056   // dllimport cannot be used on variable definitions.
11057   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11058     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11059     VDecl->setInvalidDecl();
11060     return;
11061   }
11062 
11063   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11064     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11065     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11066     VDecl->setInvalidDecl();
11067     return;
11068   }
11069 
11070   if (!VDecl->getType()->isDependentType()) {
11071     // A definition must end up with a complete type, which means it must be
11072     // complete with the restriction that an array type might be completed by
11073     // the initializer; note that later code assumes this restriction.
11074     QualType BaseDeclType = VDecl->getType();
11075     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11076       BaseDeclType = Array->getElementType();
11077     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11078                             diag::err_typecheck_decl_incomplete_type)) {
11079       RealDecl->setInvalidDecl();
11080       return;
11081     }
11082 
11083     // The variable can not have an abstract class type.
11084     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11085                                diag::err_abstract_type_in_decl,
11086                                AbstractVariableType))
11087       VDecl->setInvalidDecl();
11088   }
11089 
11090   // If adding the initializer will turn this declaration into a definition,
11091   // and we already have a definition for this variable, diagnose or otherwise
11092   // handle the situation.
11093   VarDecl *Def;
11094   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11095       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11096       !VDecl->isThisDeclarationADemotedDefinition() &&
11097       checkVarDeclRedefinition(Def, VDecl))
11098     return;
11099 
11100   if (getLangOpts().CPlusPlus) {
11101     // C++ [class.static.data]p4
11102     //   If a static data member is of const integral or const
11103     //   enumeration type, its declaration in the class definition can
11104     //   specify a constant-initializer which shall be an integral
11105     //   constant expression (5.19). In that case, the member can appear
11106     //   in integral constant expressions. The member shall still be
11107     //   defined in a namespace scope if it is used in the program and the
11108     //   namespace scope definition shall not contain an initializer.
11109     //
11110     // We already performed a redefinition check above, but for static
11111     // data members we also need to check whether there was an in-class
11112     // declaration with an initializer.
11113     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11114       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11115           << VDecl->getDeclName();
11116       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11117            diag::note_previous_initializer)
11118           << 0;
11119       return;
11120     }
11121 
11122     if (VDecl->hasLocalStorage())
11123       setFunctionHasBranchProtectedScope();
11124 
11125     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
11126       VDecl->setInvalidDecl();
11127       return;
11128     }
11129   }
11130 
11131   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11132   // a kernel function cannot be initialized."
11133   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11134     Diag(VDecl->getLocation(), diag::err_local_cant_init);
11135     VDecl->setInvalidDecl();
11136     return;
11137   }
11138 
11139   // Get the decls type and save a reference for later, since
11140   // CheckInitializerTypes may change it.
11141   QualType DclT = VDecl->getType(), SavT = DclT;
11142 
11143   // Expressions default to 'id' when we're in a debugger
11144   // and we are assigning it to a variable of Objective-C pointer type.
11145   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11146       Init->getType() == Context.UnknownAnyTy) {
11147     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11148     if (Result.isInvalid()) {
11149       VDecl->setInvalidDecl();
11150       return;
11151     }
11152     Init = Result.get();
11153   }
11154 
11155   // Perform the initialization.
11156   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11157   if (!VDecl->isInvalidDecl()) {
11158     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11159     InitializationKind Kind = InitializationKind::CreateForInit(
11160         VDecl->getLocation(), DirectInit, Init);
11161 
11162     MultiExprArg Args = Init;
11163     if (CXXDirectInit)
11164       Args = MultiExprArg(CXXDirectInit->getExprs(),
11165                           CXXDirectInit->getNumExprs());
11166 
11167     // Try to correct any TypoExprs in the initialization arguments.
11168     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11169       ExprResult Res = CorrectDelayedTyposInExpr(
11170           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11171             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11172             return Init.Failed() ? ExprError() : E;
11173           });
11174       if (Res.isInvalid()) {
11175         VDecl->setInvalidDecl();
11176       } else if (Res.get() != Args[Idx]) {
11177         Args[Idx] = Res.get();
11178       }
11179     }
11180     if (VDecl->isInvalidDecl())
11181       return;
11182 
11183     InitializationSequence InitSeq(*this, Entity, Kind, Args,
11184                                    /*TopLevelOfInitList=*/false,
11185                                    /*TreatUnavailableAsInvalid=*/false);
11186     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11187     if (Result.isInvalid()) {
11188       VDecl->setInvalidDecl();
11189       return;
11190     }
11191 
11192     Init = Result.getAs<Expr>();
11193   }
11194 
11195   // Check for self-references within variable initializers.
11196   // Variables declared within a function/method body (except for references)
11197   // are handled by a dataflow analysis.
11198   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11199       VDecl->getType()->isReferenceType()) {
11200     CheckSelfReference(*this, RealDecl, Init, DirectInit);
11201   }
11202 
11203   // If the type changed, it means we had an incomplete type that was
11204   // completed by the initializer. For example:
11205   //   int ary[] = { 1, 3, 5 };
11206   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11207   if (!VDecl->isInvalidDecl() && (DclT != SavT))
11208     VDecl->setType(DclT);
11209 
11210   if (!VDecl->isInvalidDecl()) {
11211     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11212 
11213     if (VDecl->hasAttr<BlocksAttr>())
11214       checkRetainCycles(VDecl, Init);
11215 
11216     // It is safe to assign a weak reference into a strong variable.
11217     // Although this code can still have problems:
11218     //   id x = self.weakProp;
11219     //   id y = self.weakProp;
11220     // we do not warn to warn spuriously when 'x' and 'y' are on separate
11221     // paths through the function. This should be revisited if
11222     // -Wrepeated-use-of-weak is made flow-sensitive.
11223     if (FunctionScopeInfo *FSI = getCurFunction())
11224       if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11225            VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11226           !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11227                            Init->getBeginLoc()))
11228         FSI->markSafeWeakUse(Init);
11229   }
11230 
11231   // The initialization is usually a full-expression.
11232   //
11233   // FIXME: If this is a braced initialization of an aggregate, it is not
11234   // an expression, and each individual field initializer is a separate
11235   // full-expression. For instance, in:
11236   //
11237   //   struct Temp { ~Temp(); };
11238   //   struct S { S(Temp); };
11239   //   struct T { S a, b; } t = { Temp(), Temp() }
11240   //
11241   // we should destroy the first Temp before constructing the second.
11242   ExprResult Result =
11243       ActOnFinishFullExpr(Init, VDecl->getLocation(),
11244                           /*DiscardedValue*/ false, VDecl->isConstexpr());
11245   if (Result.isInvalid()) {
11246     VDecl->setInvalidDecl();
11247     return;
11248   }
11249   Init = Result.get();
11250 
11251   // Attach the initializer to the decl.
11252   VDecl->setInit(Init);
11253 
11254   if (VDecl->isLocalVarDecl()) {
11255     // Don't check the initializer if the declaration is malformed.
11256     if (VDecl->isInvalidDecl()) {
11257       // do nothing
11258 
11259     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11260     // This is true even in OpenCL C++.
11261     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11262       CheckForConstantInitializer(Init, DclT);
11263 
11264     // Otherwise, C++ does not restrict the initializer.
11265     } else if (getLangOpts().CPlusPlus) {
11266       // do nothing
11267 
11268     // C99 6.7.8p4: All the expressions in an initializer for an object that has
11269     // static storage duration shall be constant expressions or string literals.
11270     } else if (VDecl->getStorageClass() == SC_Static) {
11271       CheckForConstantInitializer(Init, DclT);
11272 
11273     // C89 is stricter than C99 for aggregate initializers.
11274     // C89 6.5.7p3: All the expressions [...] in an initializer list
11275     // for an object that has aggregate or union type shall be
11276     // constant expressions.
11277     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11278                isa<InitListExpr>(Init)) {
11279       const Expr *Culprit;
11280       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
11281         Diag(Culprit->getExprLoc(),
11282              diag::ext_aggregate_init_not_constant)
11283           << Culprit->getSourceRange();
11284       }
11285     }
11286 
11287     if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11288       if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11289         if (VDecl->hasLocalStorage())
11290           BE->getBlockDecl()->setCanAvoidCopyToHeap();
11291   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11292              VDecl->getLexicalDeclContext()->isRecord()) {
11293     // This is an in-class initialization for a static data member, e.g.,
11294     //
11295     // struct S {
11296     //   static const int value = 17;
11297     // };
11298 
11299     // C++ [class.mem]p4:
11300     //   A member-declarator can contain a constant-initializer only
11301     //   if it declares a static member (9.4) of const integral or
11302     //   const enumeration type, see 9.4.2.
11303     //
11304     // C++11 [class.static.data]p3:
11305     //   If a non-volatile non-inline const static data member is of integral
11306     //   or enumeration type, its declaration in the class definition can
11307     //   specify a brace-or-equal-initializer in which every initializer-clause
11308     //   that is an assignment-expression is a constant expression. A static
11309     //   data member of literal type can be declared in the class definition
11310     //   with the constexpr specifier; if so, its declaration shall specify a
11311     //   brace-or-equal-initializer in which every initializer-clause that is
11312     //   an assignment-expression is a constant expression.
11313 
11314     // Do nothing on dependent types.
11315     if (DclT->isDependentType()) {
11316 
11317     // Allow any 'static constexpr' members, whether or not they are of literal
11318     // type. We separately check that every constexpr variable is of literal
11319     // type.
11320     } else if (VDecl->isConstexpr()) {
11321 
11322     // Require constness.
11323     } else if (!DclT.isConstQualified()) {
11324       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11325         << Init->getSourceRange();
11326       VDecl->setInvalidDecl();
11327 
11328     // We allow integer constant expressions in all cases.
11329     } else if (DclT->isIntegralOrEnumerationType()) {
11330       // Check whether the expression is a constant expression.
11331       SourceLocation Loc;
11332       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11333         // In C++11, a non-constexpr const static data member with an
11334         // in-class initializer cannot be volatile.
11335         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11336       else if (Init->isValueDependent())
11337         ; // Nothing to check.
11338       else if (Init->isIntegerConstantExpr(Context, &Loc))
11339         ; // Ok, it's an ICE!
11340       else if (Init->getType()->isScopedEnumeralType() &&
11341                Init->isCXX11ConstantExpr(Context))
11342         ; // Ok, it is a scoped-enum constant expression.
11343       else if (Init->isEvaluatable(Context)) {
11344         // If we can constant fold the initializer through heroics, accept it,
11345         // but report this as a use of an extension for -pedantic.
11346         Diag(Loc, diag::ext_in_class_initializer_non_constant)
11347           << Init->getSourceRange();
11348       } else {
11349         // Otherwise, this is some crazy unknown case.  Report the issue at the
11350         // location provided by the isIntegerConstantExpr failed check.
11351         Diag(Loc, diag::err_in_class_initializer_non_constant)
11352           << Init->getSourceRange();
11353         VDecl->setInvalidDecl();
11354       }
11355 
11356     // We allow foldable floating-point constants as an extension.
11357     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11358       // In C++98, this is a GNU extension. In C++11, it is not, but we support
11359       // it anyway and provide a fixit to add the 'constexpr'.
11360       if (getLangOpts().CPlusPlus11) {
11361         Diag(VDecl->getLocation(),
11362              diag::ext_in_class_initializer_float_type_cxx11)
11363             << DclT << Init->getSourceRange();
11364         Diag(VDecl->getBeginLoc(),
11365              diag::note_in_class_initializer_float_type_cxx11)
11366             << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11367       } else {
11368         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11369           << DclT << Init->getSourceRange();
11370 
11371         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11372           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11373             << Init->getSourceRange();
11374           VDecl->setInvalidDecl();
11375         }
11376       }
11377 
11378     // Suggest adding 'constexpr' in C++11 for literal types.
11379     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11380       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11381           << DclT << Init->getSourceRange()
11382           << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11383       VDecl->setConstexpr(true);
11384 
11385     } else {
11386       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11387         << DclT << Init->getSourceRange();
11388       VDecl->setInvalidDecl();
11389     }
11390   } else if (VDecl->isFileVarDecl()) {
11391     // In C, extern is typically used to avoid tentative definitions when
11392     // declaring variables in headers, but adding an intializer makes it a
11393     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11394     // In C++, extern is often used to give implictly static const variables
11395     // external linkage, so don't warn in that case. If selectany is present,
11396     // this might be header code intended for C and C++ inclusion, so apply the
11397     // C++ rules.
11398     if (VDecl->getStorageClass() == SC_Extern &&
11399         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11400          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11401         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11402         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11403       Diag(VDecl->getLocation(), diag::warn_extern_init);
11404 
11405     // In Microsoft C++ mode, a const variable defined in namespace scope has
11406     // external linkage by default if the variable is declared with
11407     // __declspec(dllexport).
11408     if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11409         getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11410         VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11411       VDecl->setStorageClass(SC_Extern);
11412 
11413     // C99 6.7.8p4. All file scoped initializers need to be constant.
11414     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11415       CheckForConstantInitializer(Init, DclT);
11416   }
11417 
11418   // We will represent direct-initialization similarly to copy-initialization:
11419   //    int x(1);  -as-> int x = 1;
11420   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11421   //
11422   // Clients that want to distinguish between the two forms, can check for
11423   // direct initializer using VarDecl::getInitStyle().
11424   // A major benefit is that clients that don't particularly care about which
11425   // exactly form was it (like the CodeGen) can handle both cases without
11426   // special case code.
11427 
11428   // C++ 8.5p11:
11429   // The form of initialization (using parentheses or '=') is generally
11430   // insignificant, but does matter when the entity being initialized has a
11431   // class type.
11432   if (CXXDirectInit) {
11433     assert(DirectInit && "Call-style initializer must be direct init.");
11434     VDecl->setInitStyle(VarDecl::CallInit);
11435   } else if (DirectInit) {
11436     // This must be list-initialization. No other way is direct-initialization.
11437     VDecl->setInitStyle(VarDecl::ListInit);
11438   }
11439 
11440   CheckCompleteVariableDeclaration(VDecl);
11441 }
11442 
11443 /// ActOnInitializerError - Given that there was an error parsing an
11444 /// initializer for the given declaration, try to return to some form
11445 /// of sanity.
11446 void Sema::ActOnInitializerError(Decl *D) {
11447   // Our main concern here is re-establishing invariants like "a
11448   // variable's type is either dependent or complete".
11449   if (!D || D->isInvalidDecl()) return;
11450 
11451   VarDecl *VD = dyn_cast<VarDecl>(D);
11452   if (!VD) return;
11453 
11454   // Bindings are not usable if we can't make sense of the initializer.
11455   if (auto *DD = dyn_cast<DecompositionDecl>(D))
11456     for (auto *BD : DD->bindings())
11457       BD->setInvalidDecl();
11458 
11459   // Auto types are meaningless if we can't make sense of the initializer.
11460   if (ParsingInitForAutoVars.count(D)) {
11461     D->setInvalidDecl();
11462     return;
11463   }
11464 
11465   QualType Ty = VD->getType();
11466   if (Ty->isDependentType()) return;
11467 
11468   // Require a complete type.
11469   if (RequireCompleteType(VD->getLocation(),
11470                           Context.getBaseElementType(Ty),
11471                           diag::err_typecheck_decl_incomplete_type)) {
11472     VD->setInvalidDecl();
11473     return;
11474   }
11475 
11476   // Require a non-abstract type.
11477   if (RequireNonAbstractType(VD->getLocation(), Ty,
11478                              diag::err_abstract_type_in_decl,
11479                              AbstractVariableType)) {
11480     VD->setInvalidDecl();
11481     return;
11482   }
11483 
11484   // Don't bother complaining about constructors or destructors,
11485   // though.
11486 }
11487 
11488 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11489   // If there is no declaration, there was an error parsing it. Just ignore it.
11490   if (!RealDecl)
11491     return;
11492 
11493   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11494     QualType Type = Var->getType();
11495 
11496     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11497     if (isa<DecompositionDecl>(RealDecl)) {
11498       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11499       Var->setInvalidDecl();
11500       return;
11501     }
11502 
11503     Expr *TmpInit = nullptr;
11504     if (Type->isUndeducedType() &&
11505         DeduceVariableDeclarationType(Var, false, TmpInit))
11506       return;
11507 
11508     // C++11 [class.static.data]p3: A static data member can be declared with
11509     // the constexpr specifier; if so, its declaration shall specify
11510     // a brace-or-equal-initializer.
11511     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11512     // the definition of a variable [...] or the declaration of a static data
11513     // member.
11514     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11515         !Var->isThisDeclarationADemotedDefinition()) {
11516       if (Var->isStaticDataMember()) {
11517         // C++1z removes the relevant rule; the in-class declaration is always
11518         // a definition there.
11519         if (!getLangOpts().CPlusPlus17) {
11520           Diag(Var->getLocation(),
11521                diag::err_constexpr_static_mem_var_requires_init)
11522             << Var->getDeclName();
11523           Var->setInvalidDecl();
11524           return;
11525         }
11526       } else {
11527         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11528         Var->setInvalidDecl();
11529         return;
11530       }
11531     }
11532 
11533     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11534     // be initialized.
11535     if (!Var->isInvalidDecl() &&
11536         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11537         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11538       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11539       Var->setInvalidDecl();
11540       return;
11541     }
11542 
11543     switch (Var->isThisDeclarationADefinition()) {
11544     case VarDecl::Definition:
11545       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11546         break;
11547 
11548       // We have an out-of-line definition of a static data member
11549       // that has an in-class initializer, so we type-check this like
11550       // a declaration.
11551       //
11552       LLVM_FALLTHROUGH;
11553 
11554     case VarDecl::DeclarationOnly:
11555       // It's only a declaration.
11556 
11557       // Block scope. C99 6.7p7: If an identifier for an object is
11558       // declared with no linkage (C99 6.2.2p6), the type for the
11559       // object shall be complete.
11560       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11561           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11562           RequireCompleteType(Var->getLocation(), Type,
11563                               diag::err_typecheck_decl_incomplete_type))
11564         Var->setInvalidDecl();
11565 
11566       // Make sure that the type is not abstract.
11567       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11568           RequireNonAbstractType(Var->getLocation(), Type,
11569                                  diag::err_abstract_type_in_decl,
11570                                  AbstractVariableType))
11571         Var->setInvalidDecl();
11572       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11573           Var->getStorageClass() == SC_PrivateExtern) {
11574         Diag(Var->getLocation(), diag::warn_private_extern);
11575         Diag(Var->getLocation(), diag::note_private_extern);
11576       }
11577 
11578       return;
11579 
11580     case VarDecl::TentativeDefinition:
11581       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11582       // object that has file scope without an initializer, and without a
11583       // storage-class specifier or with the storage-class specifier "static",
11584       // constitutes a tentative definition. Note: A tentative definition with
11585       // external linkage is valid (C99 6.2.2p5).
11586       if (!Var->isInvalidDecl()) {
11587         if (const IncompleteArrayType *ArrayT
11588                                     = Context.getAsIncompleteArrayType(Type)) {
11589           if (RequireCompleteType(Var->getLocation(),
11590                                   ArrayT->getElementType(),
11591                                   diag::err_illegal_decl_array_incomplete_type))
11592             Var->setInvalidDecl();
11593         } else if (Var->getStorageClass() == SC_Static) {
11594           // C99 6.9.2p3: If the declaration of an identifier for an object is
11595           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11596           // declared type shall not be an incomplete type.
11597           // NOTE: code such as the following
11598           //     static struct s;
11599           //     struct s { int a; };
11600           // is accepted by gcc. Hence here we issue a warning instead of
11601           // an error and we do not invalidate the static declaration.
11602           // NOTE: to avoid multiple warnings, only check the first declaration.
11603           if (Var->isFirstDecl())
11604             RequireCompleteType(Var->getLocation(), Type,
11605                                 diag::ext_typecheck_decl_incomplete_type);
11606         }
11607       }
11608 
11609       // Record the tentative definition; we're done.
11610       if (!Var->isInvalidDecl())
11611         TentativeDefinitions.push_back(Var);
11612       return;
11613     }
11614 
11615     // Provide a specific diagnostic for uninitialized variable
11616     // definitions with incomplete array type.
11617     if (Type->isIncompleteArrayType()) {
11618       Diag(Var->getLocation(),
11619            diag::err_typecheck_incomplete_array_needs_initializer);
11620       Var->setInvalidDecl();
11621       return;
11622     }
11623 
11624     // Provide a specific diagnostic for uninitialized variable
11625     // definitions with reference type.
11626     if (Type->isReferenceType()) {
11627       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11628         << Var->getDeclName()
11629         << SourceRange(Var->getLocation(), Var->getLocation());
11630       Var->setInvalidDecl();
11631       return;
11632     }
11633 
11634     // Do not attempt to type-check the default initializer for a
11635     // variable with dependent type.
11636     if (Type->isDependentType())
11637       return;
11638 
11639     if (Var->isInvalidDecl())
11640       return;
11641 
11642     if (!Var->hasAttr<AliasAttr>()) {
11643       if (RequireCompleteType(Var->getLocation(),
11644                               Context.getBaseElementType(Type),
11645                               diag::err_typecheck_decl_incomplete_type)) {
11646         Var->setInvalidDecl();
11647         return;
11648       }
11649     } else {
11650       return;
11651     }
11652 
11653     // The variable can not have an abstract class type.
11654     if (RequireNonAbstractType(Var->getLocation(), Type,
11655                                diag::err_abstract_type_in_decl,
11656                                AbstractVariableType)) {
11657       Var->setInvalidDecl();
11658       return;
11659     }
11660 
11661     // Check for jumps past the implicit initializer.  C++0x
11662     // clarifies that this applies to a "variable with automatic
11663     // storage duration", not a "local variable".
11664     // C++11 [stmt.dcl]p3
11665     //   A program that jumps from a point where a variable with automatic
11666     //   storage duration is not in scope to a point where it is in scope is
11667     //   ill-formed unless the variable has scalar type, class type with a
11668     //   trivial default constructor and a trivial destructor, a cv-qualified
11669     //   version of one of these types, or an array of one of the preceding
11670     //   types and is declared without an initializer.
11671     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11672       if (const RecordType *Record
11673             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11674         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11675         // Mark the function (if we're in one) for further checking even if the
11676         // looser rules of C++11 do not require such checks, so that we can
11677         // diagnose incompatibilities with C++98.
11678         if (!CXXRecord->isPOD())
11679           setFunctionHasBranchProtectedScope();
11680       }
11681     }
11682     // In OpenCL, we can't initialize objects in the __local address space,
11683     // even implicitly, so don't synthesize an implicit initializer.
11684     if (getLangOpts().OpenCL &&
11685         Var->getType().getAddressSpace() == LangAS::opencl_local)
11686       return;
11687     // C++03 [dcl.init]p9:
11688     //   If no initializer is specified for an object, and the
11689     //   object is of (possibly cv-qualified) non-POD class type (or
11690     //   array thereof), the object shall be default-initialized; if
11691     //   the object is of const-qualified type, the underlying class
11692     //   type shall have a user-declared default
11693     //   constructor. Otherwise, if no initializer is specified for
11694     //   a non- static object, the object and its subobjects, if
11695     //   any, have an indeterminate initial value); if the object
11696     //   or any of its subobjects are of const-qualified type, the
11697     //   program is ill-formed.
11698     // C++0x [dcl.init]p11:
11699     //   If no initializer is specified for an object, the object is
11700     //   default-initialized; [...].
11701     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11702     InitializationKind Kind
11703       = InitializationKind::CreateDefault(Var->getLocation());
11704 
11705     InitializationSequence InitSeq(*this, Entity, Kind, None);
11706     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11707     if (Init.isInvalid())
11708       Var->setInvalidDecl();
11709     else if (Init.get()) {
11710       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11711       // This is important for template substitution.
11712       Var->setInitStyle(VarDecl::CallInit);
11713     }
11714 
11715     CheckCompleteVariableDeclaration(Var);
11716   }
11717 }
11718 
11719 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11720   // If there is no declaration, there was an error parsing it. Ignore it.
11721   if (!D)
11722     return;
11723 
11724   VarDecl *VD = dyn_cast<VarDecl>(D);
11725   if (!VD) {
11726     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11727     D->setInvalidDecl();
11728     return;
11729   }
11730 
11731   VD->setCXXForRangeDecl(true);
11732 
11733   // for-range-declaration cannot be given a storage class specifier.
11734   int Error = -1;
11735   switch (VD->getStorageClass()) {
11736   case SC_None:
11737     break;
11738   case SC_Extern:
11739     Error = 0;
11740     break;
11741   case SC_Static:
11742     Error = 1;
11743     break;
11744   case SC_PrivateExtern:
11745     Error = 2;
11746     break;
11747   case SC_Auto:
11748     Error = 3;
11749     break;
11750   case SC_Register:
11751     Error = 4;
11752     break;
11753   }
11754   if (Error != -1) {
11755     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11756       << VD->getDeclName() << Error;
11757     D->setInvalidDecl();
11758   }
11759 }
11760 
11761 StmtResult
11762 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11763                                  IdentifierInfo *Ident,
11764                                  ParsedAttributes &Attrs,
11765                                  SourceLocation AttrEnd) {
11766   // C++1y [stmt.iter]p1:
11767   //   A range-based for statement of the form
11768   //      for ( for-range-identifier : for-range-initializer ) statement
11769   //   is equivalent to
11770   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11771   DeclSpec DS(Attrs.getPool().getFactory());
11772 
11773   const char *PrevSpec;
11774   unsigned DiagID;
11775   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11776                      getPrintingPolicy());
11777 
11778   Declarator D(DS, DeclaratorContext::ForContext);
11779   D.SetIdentifier(Ident, IdentLoc);
11780   D.takeAttributes(Attrs, AttrEnd);
11781 
11782   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
11783                 IdentLoc);
11784   Decl *Var = ActOnDeclarator(S, D);
11785   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11786   FinalizeDeclaration(Var);
11787   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11788                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11789 }
11790 
11791 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11792   if (var->isInvalidDecl()) return;
11793 
11794   if (getLangOpts().OpenCL) {
11795     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11796     // initialiser
11797     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11798         !var->hasInit()) {
11799       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11800           << 1 /*Init*/;
11801       var->setInvalidDecl();
11802       return;
11803     }
11804   }
11805 
11806   // In Objective-C, don't allow jumps past the implicit initialization of a
11807   // local retaining variable.
11808   if (getLangOpts().ObjC &&
11809       var->hasLocalStorage()) {
11810     switch (var->getType().getObjCLifetime()) {
11811     case Qualifiers::OCL_None:
11812     case Qualifiers::OCL_ExplicitNone:
11813     case Qualifiers::OCL_Autoreleasing:
11814       break;
11815 
11816     case Qualifiers::OCL_Weak:
11817     case Qualifiers::OCL_Strong:
11818       setFunctionHasBranchProtectedScope();
11819       break;
11820     }
11821   }
11822 
11823   if (var->hasLocalStorage() &&
11824       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11825     setFunctionHasBranchProtectedScope();
11826 
11827   // Warn about externally-visible variables being defined without a
11828   // prior declaration.  We only want to do this for global
11829   // declarations, but we also specifically need to avoid doing it for
11830   // class members because the linkage of an anonymous class can
11831   // change if it's later given a typedef name.
11832   if (var->isThisDeclarationADefinition() &&
11833       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11834       var->isExternallyVisible() && var->hasLinkage() &&
11835       !var->isInline() && !var->getDescribedVarTemplate() &&
11836       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11837       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11838                                   var->getLocation())) {
11839     // Find a previous declaration that's not a definition.
11840     VarDecl *prev = var->getPreviousDecl();
11841     while (prev && prev->isThisDeclarationADefinition())
11842       prev = prev->getPreviousDecl();
11843 
11844     if (!prev)
11845       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11846   }
11847 
11848   // Cache the result of checking for constant initialization.
11849   Optional<bool> CacheHasConstInit;
11850   const Expr *CacheCulprit;
11851   auto checkConstInit = [&]() mutable {
11852     if (!CacheHasConstInit)
11853       CacheHasConstInit = var->getInit()->isConstantInitializer(
11854             Context, var->getType()->isReferenceType(), &CacheCulprit);
11855     return *CacheHasConstInit;
11856   };
11857 
11858   if (var->getTLSKind() == VarDecl::TLS_Static) {
11859     if (var->getType().isDestructedType()) {
11860       // GNU C++98 edits for __thread, [basic.start.term]p3:
11861       //   The type of an object with thread storage duration shall not
11862       //   have a non-trivial destructor.
11863       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11864       if (getLangOpts().CPlusPlus11)
11865         Diag(var->getLocation(), diag::note_use_thread_local);
11866     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11867       if (!checkConstInit()) {
11868         // GNU C++98 edits for __thread, [basic.start.init]p4:
11869         //   An object of thread storage duration shall not require dynamic
11870         //   initialization.
11871         // FIXME: Need strict checking here.
11872         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11873           << CacheCulprit->getSourceRange();
11874         if (getLangOpts().CPlusPlus11)
11875           Diag(var->getLocation(), diag::note_use_thread_local);
11876       }
11877     }
11878   }
11879 
11880   // Apply section attributes and pragmas to global variables.
11881   bool GlobalStorage = var->hasGlobalStorage();
11882   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11883       !inTemplateInstantiation()) {
11884     PragmaStack<StringLiteral *> *Stack = nullptr;
11885     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11886     if (var->getType().isConstQualified())
11887       Stack = &ConstSegStack;
11888     else if (!var->getInit()) {
11889       Stack = &BSSSegStack;
11890       SectionFlags |= ASTContext::PSF_Write;
11891     } else {
11892       Stack = &DataSegStack;
11893       SectionFlags |= ASTContext::PSF_Write;
11894     }
11895     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11896       var->addAttr(SectionAttr::CreateImplicit(
11897           Context, SectionAttr::Declspec_allocate,
11898           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11899     }
11900     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11901       if (UnifySection(SA->getName(), SectionFlags, var))
11902         var->dropAttr<SectionAttr>();
11903 
11904     // Apply the init_seg attribute if this has an initializer.  If the
11905     // initializer turns out to not be dynamic, we'll end up ignoring this
11906     // attribute.
11907     if (CurInitSeg && var->getInit())
11908       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11909                                                CurInitSegLoc));
11910   }
11911 
11912   // All the following checks are C++ only.
11913   if (!getLangOpts().CPlusPlus) {
11914       // If this variable must be emitted, add it as an initializer for the
11915       // current module.
11916      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11917        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11918      return;
11919   }
11920 
11921   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11922     CheckCompleteDecompositionDeclaration(DD);
11923 
11924   QualType type = var->getType();
11925   if (type->isDependentType()) return;
11926 
11927   if (var->hasAttr<BlocksAttr>())
11928     getCurFunction()->addByrefBlockVar(var);
11929 
11930   Expr *Init = var->getInit();
11931   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11932   QualType baseType = Context.getBaseElementType(type);
11933 
11934   if (Init && !Init->isValueDependent()) {
11935     if (var->isConstexpr()) {
11936       SmallVector<PartialDiagnosticAt, 8> Notes;
11937       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11938         SourceLocation DiagLoc = var->getLocation();
11939         // If the note doesn't add any useful information other than a source
11940         // location, fold it into the primary diagnostic.
11941         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11942               diag::note_invalid_subexpr_in_const_expr) {
11943           DiagLoc = Notes[0].first;
11944           Notes.clear();
11945         }
11946         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11947           << var << Init->getSourceRange();
11948         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11949           Diag(Notes[I].first, Notes[I].second);
11950       }
11951     } else if (var->isUsableInConstantExpressions(Context)) {
11952       // Check whether the initializer of a const variable of integral or
11953       // enumeration type is an ICE now, since we can't tell whether it was
11954       // initialized by a constant expression if we check later.
11955       var->checkInitIsICE();
11956     }
11957 
11958     // Don't emit further diagnostics about constexpr globals since they
11959     // were just diagnosed.
11960     if (!var->isConstexpr() && GlobalStorage &&
11961             var->hasAttr<RequireConstantInitAttr>()) {
11962       // FIXME: Need strict checking in C++03 here.
11963       bool DiagErr = getLangOpts().CPlusPlus11
11964           ? !var->checkInitIsICE() : !checkConstInit();
11965       if (DiagErr) {
11966         auto attr = var->getAttr<RequireConstantInitAttr>();
11967         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11968           << Init->getSourceRange();
11969         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11970           << attr->getRange();
11971         if (getLangOpts().CPlusPlus11) {
11972           APValue Value;
11973           SmallVector<PartialDiagnosticAt, 8> Notes;
11974           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11975           for (auto &it : Notes)
11976             Diag(it.first, it.second);
11977         } else {
11978           Diag(CacheCulprit->getExprLoc(),
11979                diag::note_invalid_subexpr_in_const_expr)
11980               << CacheCulprit->getSourceRange();
11981         }
11982       }
11983     }
11984     else if (!var->isConstexpr() && IsGlobal &&
11985              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11986                                     var->getLocation())) {
11987       // Warn about globals which don't have a constant initializer.  Don't
11988       // warn about globals with a non-trivial destructor because we already
11989       // warned about them.
11990       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11991       if (!(RD && !RD->hasTrivialDestructor())) {
11992         if (!checkConstInit())
11993           Diag(var->getLocation(), diag::warn_global_constructor)
11994             << Init->getSourceRange();
11995       }
11996     }
11997   }
11998 
11999   // Require the destructor.
12000   if (const RecordType *recordType = baseType->getAs<RecordType>())
12001     FinalizeVarWithDestructor(var, recordType);
12002 
12003   // If this variable must be emitted, add it as an initializer for the current
12004   // module.
12005   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12006     Context.addModuleInitializer(ModuleScopes.back().Module, var);
12007 }
12008 
12009 /// Determines if a variable's alignment is dependent.
12010 static bool hasDependentAlignment(VarDecl *VD) {
12011   if (VD->getType()->isDependentType())
12012     return true;
12013   for (auto *I : VD->specific_attrs<AlignedAttr>())
12014     if (I->isAlignmentDependent())
12015       return true;
12016   return false;
12017 }
12018 
12019 /// Check if VD needs to be dllexport/dllimport due to being in a
12020 /// dllexport/import function.
12021 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12022   assert(VD->isStaticLocal());
12023 
12024   auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12025 
12026   // Find outermost function when VD is in lambda function.
12027   while (FD && !getDLLAttr(FD) &&
12028          !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12029          !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12030     FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12031   }
12032 
12033   if (!FD)
12034     return;
12035 
12036   // Static locals inherit dll attributes from their function.
12037   if (Attr *A = getDLLAttr(FD)) {
12038     auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12039     NewAttr->setInherited(true);
12040     VD->addAttr(NewAttr);
12041   } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12042     auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12043                                                           getASTContext(),
12044                                                           A->getSpellingListIndex());
12045     NewAttr->setInherited(true);
12046     VD->addAttr(NewAttr);
12047 
12048     // Export this function to enforce exporting this static variable even
12049     // if it is not used in this compilation unit.
12050     if (!FD->hasAttr<DLLExportAttr>())
12051       FD->addAttr(NewAttr);
12052 
12053   } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12054     auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12055                                                           getASTContext(),
12056                                                           A->getSpellingListIndex());
12057     NewAttr->setInherited(true);
12058     VD->addAttr(NewAttr);
12059   }
12060 }
12061 
12062 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12063 /// any semantic actions necessary after any initializer has been attached.
12064 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12065   // Note that we are no longer parsing the initializer for this declaration.
12066   ParsingInitForAutoVars.erase(ThisDecl);
12067 
12068   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12069   if (!VD)
12070     return;
12071 
12072   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12073   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12074       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12075     if (PragmaClangBSSSection.Valid)
12076       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12077                                                             PragmaClangBSSSection.SectionName,
12078                                                             PragmaClangBSSSection.PragmaLocation));
12079     if (PragmaClangDataSection.Valid)
12080       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12081                                                              PragmaClangDataSection.SectionName,
12082                                                              PragmaClangDataSection.PragmaLocation));
12083     if (PragmaClangRodataSection.Valid)
12084       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12085                                                                PragmaClangRodataSection.SectionName,
12086                                                                PragmaClangRodataSection.PragmaLocation));
12087   }
12088 
12089   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12090     for (auto *BD : DD->bindings()) {
12091       FinalizeDeclaration(BD);
12092     }
12093   }
12094 
12095   checkAttributesAfterMerging(*this, *VD);
12096 
12097   // Perform TLS alignment check here after attributes attached to the variable
12098   // which may affect the alignment have been processed. Only perform the check
12099   // if the target has a maximum TLS alignment (zero means no constraints).
12100   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12101     // Protect the check so that it's not performed on dependent types and
12102     // dependent alignments (we can't determine the alignment in that case).
12103     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12104         !VD->isInvalidDecl()) {
12105       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12106       if (Context.getDeclAlign(VD) > MaxAlignChars) {
12107         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12108           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12109           << (unsigned)MaxAlignChars.getQuantity();
12110       }
12111     }
12112   }
12113 
12114   if (VD->isStaticLocal()) {
12115     CheckStaticLocalForDllExport(VD);
12116 
12117     if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12118       // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12119       // function, only __shared__ variables or variables without any device
12120       // memory qualifiers may be declared with static storage class.
12121       // Note: It is unclear how a function-scope non-const static variable
12122       // without device memory qualifier is implemented, therefore only static
12123       // const variable without device memory qualifier is allowed.
12124       [&]() {
12125         if (!getLangOpts().CUDA)
12126           return;
12127         if (VD->hasAttr<CUDASharedAttr>())
12128           return;
12129         if (VD->getType().isConstQualified() &&
12130             !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12131           return;
12132         if (CUDADiagIfDeviceCode(VD->getLocation(),
12133                                  diag::err_device_static_local_var)
12134             << CurrentCUDATarget())
12135           VD->setInvalidDecl();
12136       }();
12137     }
12138   }
12139 
12140   // Perform check for initializers of device-side global variables.
12141   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12142   // 7.5). We must also apply the same checks to all __shared__
12143   // variables whether they are local or not. CUDA also allows
12144   // constant initializers for __constant__ and __device__ variables.
12145   if (getLangOpts().CUDA)
12146     checkAllowedCUDAInitializer(VD);
12147 
12148   // Grab the dllimport or dllexport attribute off of the VarDecl.
12149   const InheritableAttr *DLLAttr = getDLLAttr(VD);
12150 
12151   // Imported static data members cannot be defined out-of-line.
12152   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12153     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12154         VD->isThisDeclarationADefinition()) {
12155       // We allow definitions of dllimport class template static data members
12156       // with a warning.
12157       CXXRecordDecl *Context =
12158         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12159       bool IsClassTemplateMember =
12160           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12161           Context->getDescribedClassTemplate();
12162 
12163       Diag(VD->getLocation(),
12164            IsClassTemplateMember
12165                ? diag::warn_attribute_dllimport_static_field_definition
12166                : diag::err_attribute_dllimport_static_field_definition);
12167       Diag(IA->getLocation(), diag::note_attribute);
12168       if (!IsClassTemplateMember)
12169         VD->setInvalidDecl();
12170     }
12171   }
12172 
12173   // dllimport/dllexport variables cannot be thread local, their TLS index
12174   // isn't exported with the variable.
12175   if (DLLAttr && VD->getTLSKind()) {
12176     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12177     if (F && getDLLAttr(F)) {
12178       assert(VD->isStaticLocal());
12179       // But if this is a static local in a dlimport/dllexport function, the
12180       // function will never be inlined, which means the var would never be
12181       // imported, so having it marked import/export is safe.
12182     } else {
12183       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12184                                                                     << DLLAttr;
12185       VD->setInvalidDecl();
12186     }
12187   }
12188 
12189   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12190     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12191       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12192       VD->dropAttr<UsedAttr>();
12193     }
12194   }
12195 
12196   const DeclContext *DC = VD->getDeclContext();
12197   // If there's a #pragma GCC visibility in scope, and this isn't a class
12198   // member, set the visibility of this variable.
12199   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12200     AddPushedVisibilityAttribute(VD);
12201 
12202   // FIXME: Warn on unused var template partial specializations.
12203   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12204     MarkUnusedFileScopedDecl(VD);
12205 
12206   // Now we have parsed the initializer and can update the table of magic
12207   // tag values.
12208   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12209       !VD->getType()->isIntegralOrEnumerationType())
12210     return;
12211 
12212   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12213     const Expr *MagicValueExpr = VD->getInit();
12214     if (!MagicValueExpr) {
12215       continue;
12216     }
12217     llvm::APSInt MagicValueInt;
12218     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12219       Diag(I->getRange().getBegin(),
12220            diag::err_type_tag_for_datatype_not_ice)
12221         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12222       continue;
12223     }
12224     if (MagicValueInt.getActiveBits() > 64) {
12225       Diag(I->getRange().getBegin(),
12226            diag::err_type_tag_for_datatype_too_large)
12227         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12228       continue;
12229     }
12230     uint64_t MagicValue = MagicValueInt.getZExtValue();
12231     RegisterTypeTagForDatatype(I->getArgumentKind(),
12232                                MagicValue,
12233                                I->getMatchingCType(),
12234                                I->getLayoutCompatible(),
12235                                I->getMustBeNull());
12236   }
12237 }
12238 
12239 static bool hasDeducedAuto(DeclaratorDecl *DD) {
12240   auto *VD = dyn_cast<VarDecl>(DD);
12241   return VD && !VD->getType()->hasAutoForTrailingReturnType();
12242 }
12243 
12244 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
12245                                                    ArrayRef<Decl *> Group) {
12246   SmallVector<Decl*, 8> Decls;
12247 
12248   if (DS.isTypeSpecOwned())
12249     Decls.push_back(DS.getRepAsDecl());
12250 
12251   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12252   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12253   bool DiagnosedMultipleDecomps = false;
12254   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12255   bool DiagnosedNonDeducedAuto = false;
12256 
12257   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12258     if (Decl *D = Group[i]) {
12259       // For declarators, there are some additional syntactic-ish checks we need
12260       // to perform.
12261       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12262         if (!FirstDeclaratorInGroup)
12263           FirstDeclaratorInGroup = DD;
12264         if (!FirstDecompDeclaratorInGroup)
12265           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12266         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12267             !hasDeducedAuto(DD))
12268           FirstNonDeducedAutoInGroup = DD;
12269 
12270         if (FirstDeclaratorInGroup != DD) {
12271           // A decomposition declaration cannot be combined with any other
12272           // declaration in the same group.
12273           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12274             Diag(FirstDecompDeclaratorInGroup->getLocation(),
12275                  diag::err_decomp_decl_not_alone)
12276                 << FirstDeclaratorInGroup->getSourceRange()
12277                 << DD->getSourceRange();
12278             DiagnosedMultipleDecomps = true;
12279           }
12280 
12281           // A declarator that uses 'auto' in any way other than to declare a
12282           // variable with a deduced type cannot be combined with any other
12283           // declarator in the same group.
12284           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12285             Diag(FirstNonDeducedAutoInGroup->getLocation(),
12286                  diag::err_auto_non_deduced_not_alone)
12287                 << FirstNonDeducedAutoInGroup->getType()
12288                        ->hasAutoForTrailingReturnType()
12289                 << FirstDeclaratorInGroup->getSourceRange()
12290                 << DD->getSourceRange();
12291             DiagnosedNonDeducedAuto = true;
12292           }
12293         }
12294       }
12295 
12296       Decls.push_back(D);
12297     }
12298   }
12299 
12300   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12301     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12302       handleTagNumbering(Tag, S);
12303       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12304           getLangOpts().CPlusPlus)
12305         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
12306     }
12307   }
12308 
12309   return BuildDeclaratorGroup(Decls);
12310 }
12311 
12312 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
12313 /// group, performing any necessary semantic checking.
12314 Sema::DeclGroupPtrTy
12315 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12316   // C++14 [dcl.spec.auto]p7: (DR1347)
12317   //   If the type that replaces the placeholder type is not the same in each
12318   //   deduction, the program is ill-formed.
12319   if (Group.size() > 1) {
12320     QualType Deduced;
12321     VarDecl *DeducedDecl = nullptr;
12322     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
12323       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12324       if (!D || D->isInvalidDecl())
12325         break;
12326       DeducedType *DT = D->getType()->getContainedDeducedType();
12327       if (!DT || DT->getDeducedType().isNull())
12328         continue;
12329       if (Deduced.isNull()) {
12330         Deduced = DT->getDeducedType();
12331         DeducedDecl = D;
12332       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12333         auto *AT = dyn_cast<AutoType>(DT);
12334         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12335              diag::err_auto_different_deductions)
12336           << (AT ? (unsigned)AT->getKeyword() : 3)
12337           << Deduced << DeducedDecl->getDeclName()
12338           << DT->getDeducedType() << D->getDeclName()
12339           << DeducedDecl->getInit()->getSourceRange()
12340           << D->getInit()->getSourceRange();
12341         D->setInvalidDecl();
12342         break;
12343       }
12344     }
12345   }
12346 
12347   ActOnDocumentableDecls(Group);
12348 
12349   return DeclGroupPtrTy::make(
12350       DeclGroupRef::Create(Context, Group.data(), Group.size()));
12351 }
12352 
12353 void Sema::ActOnDocumentableDecl(Decl *D) {
12354   ActOnDocumentableDecls(D);
12355 }
12356 
12357 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12358   // Don't parse the comment if Doxygen diagnostics are ignored.
12359   if (Group.empty() || !Group[0])
12360     return;
12361 
12362   if (Diags.isIgnored(diag::warn_doc_param_not_found,
12363                       Group[0]->getLocation()) &&
12364       Diags.isIgnored(diag::warn_unknown_comment_command_name,
12365                       Group[0]->getLocation()))
12366     return;
12367 
12368   if (Group.size() >= 2) {
12369     // This is a decl group.  Normally it will contain only declarations
12370     // produced from declarator list.  But in case we have any definitions or
12371     // additional declaration references:
12372     //   'typedef struct S {} S;'
12373     //   'typedef struct S *S;'
12374     //   'struct S *pS;'
12375     // FinalizeDeclaratorGroup adds these as separate declarations.
12376     Decl *MaybeTagDecl = Group[0];
12377     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12378       Group = Group.slice(1);
12379     }
12380   }
12381 
12382   // See if there are any new comments that are not attached to a decl.
12383   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12384   if (!Comments.empty() &&
12385       !Comments.back()->isAttached()) {
12386     // There is at least one comment that not attached to a decl.
12387     // Maybe it should be attached to one of these decls?
12388     //
12389     // Note that this way we pick up not only comments that precede the
12390     // declaration, but also comments that *follow* the declaration -- thanks to
12391     // the lookahead in the lexer: we've consumed the semicolon and looked
12392     // ahead through comments.
12393     for (unsigned i = 0, e = Group.size(); i != e; ++i)
12394       Context.getCommentForDecl(Group[i], &PP);
12395   }
12396 }
12397 
12398 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12399 /// to introduce parameters into function prototype scope.
12400 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
12401   const DeclSpec &DS = D.getDeclSpec();
12402 
12403   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12404 
12405   // C++03 [dcl.stc]p2 also permits 'auto'.
12406   StorageClass SC = SC_None;
12407   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12408     SC = SC_Register;
12409     // In C++11, the 'register' storage class specifier is deprecated.
12410     // In C++17, it is not allowed, but we tolerate it as an extension.
12411     if (getLangOpts().CPlusPlus11) {
12412       Diag(DS.getStorageClassSpecLoc(),
12413            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12414                                      : diag::warn_deprecated_register)
12415         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12416     }
12417   } else if (getLangOpts().CPlusPlus &&
12418              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12419     SC = SC_Auto;
12420   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12421     Diag(DS.getStorageClassSpecLoc(),
12422          diag::err_invalid_storage_class_in_func_decl);
12423     D.getMutableDeclSpec().ClearStorageClassSpecs();
12424   }
12425 
12426   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12427     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12428       << DeclSpec::getSpecifierName(TSCS);
12429   if (DS.isInlineSpecified())
12430     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12431         << getLangOpts().CPlusPlus17;
12432   if (DS.isConstexprSpecified())
12433     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12434       << 0;
12435 
12436   DiagnoseFunctionSpecifiers(DS);
12437 
12438   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12439   QualType parmDeclType = TInfo->getType();
12440 
12441   if (getLangOpts().CPlusPlus) {
12442     // Check that there are no default arguments inside the type of this
12443     // parameter.
12444     CheckExtraCXXDefaultArguments(D);
12445 
12446     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12447     if (D.getCXXScopeSpec().isSet()) {
12448       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12449         << D.getCXXScopeSpec().getRange();
12450       D.getCXXScopeSpec().clear();
12451     }
12452   }
12453 
12454   // Ensure we have a valid name
12455   IdentifierInfo *II = nullptr;
12456   if (D.hasName()) {
12457     II = D.getIdentifier();
12458     if (!II) {
12459       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12460         << GetNameForDeclarator(D).getName();
12461       D.setInvalidType(true);
12462     }
12463   }
12464 
12465   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12466   if (II) {
12467     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12468                    ForVisibleRedeclaration);
12469     LookupName(R, S);
12470     if (R.isSingleResult()) {
12471       NamedDecl *PrevDecl = R.getFoundDecl();
12472       if (PrevDecl->isTemplateParameter()) {
12473         // Maybe we will complain about the shadowed template parameter.
12474         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12475         // Just pretend that we didn't see the previous declaration.
12476         PrevDecl = nullptr;
12477       } else if (S->isDeclScope(PrevDecl)) {
12478         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12479         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12480 
12481         // Recover by removing the name
12482         II = nullptr;
12483         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12484         D.setInvalidType(true);
12485       }
12486     }
12487   }
12488 
12489   // Temporarily put parameter variables in the translation unit, not
12490   // the enclosing context.  This prevents them from accidentally
12491   // looking like class members in C++.
12492   ParmVarDecl *New =
12493       CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12494                      D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
12495 
12496   if (D.isInvalidType())
12497     New->setInvalidDecl();
12498 
12499   assert(S->isFunctionPrototypeScope());
12500   assert(S->getFunctionPrototypeDepth() >= 1);
12501   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12502                     S->getNextFunctionPrototypeIndex());
12503 
12504   // Add the parameter declaration into this scope.
12505   S->AddDecl(New);
12506   if (II)
12507     IdResolver.AddDecl(New);
12508 
12509   ProcessDeclAttributes(S, New, D);
12510 
12511   if (D.getDeclSpec().isModulePrivateSpecified())
12512     Diag(New->getLocation(), diag::err_module_private_local)
12513       << 1 << New->getDeclName()
12514       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12515       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12516 
12517   if (New->hasAttr<BlocksAttr>()) {
12518     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12519   }
12520   return New;
12521 }
12522 
12523 /// Synthesizes a variable for a parameter arising from a
12524 /// typedef.
12525 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12526                                               SourceLocation Loc,
12527                                               QualType T) {
12528   /* FIXME: setting StartLoc == Loc.
12529      Would it be worth to modify callers so as to provide proper source
12530      location for the unnamed parameters, embedding the parameter's type? */
12531   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12532                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12533                                            SC_None, nullptr);
12534   Param->setImplicit();
12535   return Param;
12536 }
12537 
12538 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12539   // Don't diagnose unused-parameter errors in template instantiations; we
12540   // will already have done so in the template itself.
12541   if (inTemplateInstantiation())
12542     return;
12543 
12544   for (const ParmVarDecl *Parameter : Parameters) {
12545     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12546         !Parameter->hasAttr<UnusedAttr>()) {
12547       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12548         << Parameter->getDeclName();
12549     }
12550   }
12551 }
12552 
12553 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12554     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12555   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12556     return;
12557 
12558   // Warn if the return value is pass-by-value and larger than the specified
12559   // threshold.
12560   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12561     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12562     if (Size > LangOpts.NumLargeByValueCopy)
12563       Diag(D->getLocation(), diag::warn_return_value_size)
12564           << D->getDeclName() << Size;
12565   }
12566 
12567   // Warn if any parameter is pass-by-value and larger than the specified
12568   // threshold.
12569   for (const ParmVarDecl *Parameter : Parameters) {
12570     QualType T = Parameter->getType();
12571     if (T->isDependentType() || !T.isPODType(Context))
12572       continue;
12573     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12574     if (Size > LangOpts.NumLargeByValueCopy)
12575       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12576           << Parameter->getDeclName() << Size;
12577   }
12578 }
12579 
12580 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12581                                   SourceLocation NameLoc, IdentifierInfo *Name,
12582                                   QualType T, TypeSourceInfo *TSInfo,
12583                                   StorageClass SC) {
12584   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12585   if (getLangOpts().ObjCAutoRefCount &&
12586       T.getObjCLifetime() == Qualifiers::OCL_None &&
12587       T->isObjCLifetimeType()) {
12588 
12589     Qualifiers::ObjCLifetime lifetime;
12590 
12591     // Special cases for arrays:
12592     //   - if it's const, use __unsafe_unretained
12593     //   - otherwise, it's an error
12594     if (T->isArrayType()) {
12595       if (!T.isConstQualified()) {
12596         if (DelayedDiagnostics.shouldDelayDiagnostics())
12597           DelayedDiagnostics.add(
12598               sema::DelayedDiagnostic::makeForbiddenType(
12599               NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12600         else
12601           Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12602               << TSInfo->getTypeLoc().getSourceRange();
12603       }
12604       lifetime = Qualifiers::OCL_ExplicitNone;
12605     } else {
12606       lifetime = T->getObjCARCImplicitLifetime();
12607     }
12608     T = Context.getLifetimeQualifiedType(T, lifetime);
12609   }
12610 
12611   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12612                                          Context.getAdjustedParameterType(T),
12613                                          TSInfo, SC, nullptr);
12614 
12615   // Parameters can not be abstract class types.
12616   // For record types, this is done by the AbstractClassUsageDiagnoser once
12617   // the class has been completely parsed.
12618   if (!CurContext->isRecord() &&
12619       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12620                              AbstractParamType))
12621     New->setInvalidDecl();
12622 
12623   // Parameter declarators cannot be interface types. All ObjC objects are
12624   // passed by reference.
12625   if (T->isObjCObjectType()) {
12626     SourceLocation TypeEndLoc =
12627         getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12628     Diag(NameLoc,
12629          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12630       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12631     T = Context.getObjCObjectPointerType(T);
12632     New->setType(T);
12633   }
12634 
12635   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12636   // duration shall not be qualified by an address-space qualifier."
12637   // Since all parameters have automatic store duration, they can not have
12638   // an address space.
12639   if (T.getAddressSpace() != LangAS::Default &&
12640       // OpenCL allows function arguments declared to be an array of a type
12641       // to be qualified with an address space.
12642       !(getLangOpts().OpenCL &&
12643         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12644     Diag(NameLoc, diag::err_arg_with_address_space);
12645     New->setInvalidDecl();
12646   }
12647 
12648   return New;
12649 }
12650 
12651 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12652                                            SourceLocation LocAfterDecls) {
12653   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12654 
12655   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12656   // for a K&R function.
12657   if (!FTI.hasPrototype) {
12658     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12659       --i;
12660       if (FTI.Params[i].Param == nullptr) {
12661         SmallString<256> Code;
12662         llvm::raw_svector_ostream(Code)
12663             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12664         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12665             << FTI.Params[i].Ident
12666             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12667 
12668         // Implicitly declare the argument as type 'int' for lack of a better
12669         // type.
12670         AttributeFactory attrs;
12671         DeclSpec DS(attrs);
12672         const char* PrevSpec; // unused
12673         unsigned DiagID; // unused
12674         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12675                            DiagID, Context.getPrintingPolicy());
12676         // Use the identifier location for the type source range.
12677         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12678         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12679         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12680         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12681         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12682       }
12683     }
12684   }
12685 }
12686 
12687 Decl *
12688 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12689                               MultiTemplateParamsArg TemplateParameterLists,
12690                               SkipBodyInfo *SkipBody) {
12691   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12692   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12693   Scope *ParentScope = FnBodyScope->getParent();
12694 
12695   D.setFunctionDefinitionKind(FDK_Definition);
12696   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12697   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12698 }
12699 
12700 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12701   Consumer.HandleInlineFunctionDefinition(D);
12702 }
12703 
12704 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12705                              const FunctionDecl*& PossibleZeroParamPrototype) {
12706   // Don't warn about invalid declarations.
12707   if (FD->isInvalidDecl())
12708     return false;
12709 
12710   // Or declarations that aren't global.
12711   if (!FD->isGlobal())
12712     return false;
12713 
12714   // Don't warn about C++ member functions.
12715   if (isa<CXXMethodDecl>(FD))
12716     return false;
12717 
12718   // Don't warn about 'main'.
12719   if (FD->isMain())
12720     return false;
12721 
12722   // Don't warn about inline functions.
12723   if (FD->isInlined())
12724     return false;
12725 
12726   // Don't warn about function templates.
12727   if (FD->getDescribedFunctionTemplate())
12728     return false;
12729 
12730   // Don't warn about function template specializations.
12731   if (FD->isFunctionTemplateSpecialization())
12732     return false;
12733 
12734   // Don't warn for OpenCL kernels.
12735   if (FD->hasAttr<OpenCLKernelAttr>())
12736     return false;
12737 
12738   // Don't warn on explicitly deleted functions.
12739   if (FD->isDeleted())
12740     return false;
12741 
12742   bool MissingPrototype = true;
12743   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12744        Prev; Prev = Prev->getPreviousDecl()) {
12745     // Ignore any declarations that occur in function or method
12746     // scope, because they aren't visible from the header.
12747     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12748       continue;
12749 
12750     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12751     if (FD->getNumParams() == 0)
12752       PossibleZeroParamPrototype = Prev;
12753     break;
12754   }
12755 
12756   return MissingPrototype;
12757 }
12758 
12759 void
12760 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12761                                    const FunctionDecl *EffectiveDefinition,
12762                                    SkipBodyInfo *SkipBody) {
12763   const FunctionDecl *Definition = EffectiveDefinition;
12764   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12765     // If this is a friend function defined in a class template, it does not
12766     // have a body until it is used, nevertheless it is a definition, see
12767     // [temp.inst]p2:
12768     //
12769     // ... for the purpose of determining whether an instantiated redeclaration
12770     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12771     // corresponds to a definition in the template is considered to be a
12772     // definition.
12773     //
12774     // The following code must produce redefinition error:
12775     //
12776     //     template<typename T> struct C20 { friend void func_20() {} };
12777     //     C20<int> c20i;
12778     //     void func_20() {}
12779     //
12780     for (auto I : FD->redecls()) {
12781       if (I != FD && !I->isInvalidDecl() &&
12782           I->getFriendObjectKind() != Decl::FOK_None) {
12783         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12784           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12785             // A merged copy of the same function, instantiated as a member of
12786             // the same class, is OK.
12787             if (declaresSameEntity(OrigFD, Original) &&
12788                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12789                                    cast<Decl>(FD->getLexicalDeclContext())))
12790               continue;
12791           }
12792 
12793           if (Original->isThisDeclarationADefinition()) {
12794             Definition = I;
12795             break;
12796           }
12797         }
12798       }
12799     }
12800   }
12801 
12802   if (!Definition)
12803     // Similar to friend functions a friend function template may be a
12804     // definition and do not have a body if it is instantiated in a class
12805     // template.
12806     if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12807       for (auto I : FTD->redecls()) {
12808         auto D = cast<FunctionTemplateDecl>(I);
12809         if (D != FTD) {
12810           assert(!D->isThisDeclarationADefinition() &&
12811                  "More than one definition in redeclaration chain");
12812           if (D->getFriendObjectKind() != Decl::FOK_None)
12813             if (FunctionTemplateDecl *FT =
12814                                        D->getInstantiatedFromMemberTemplate()) {
12815               if (FT->isThisDeclarationADefinition()) {
12816                 Definition = D->getTemplatedDecl();
12817                 break;
12818               }
12819             }
12820         }
12821       }
12822     }
12823 
12824   if (!Definition)
12825     return;
12826 
12827   if (canRedefineFunction(Definition, getLangOpts()))
12828     return;
12829 
12830   // Don't emit an error when this is redefinition of a typo-corrected
12831   // definition.
12832   if (TypoCorrectedFunctionDefinitions.count(Definition))
12833     return;
12834 
12835   // If we don't have a visible definition of the function, and it's inline or
12836   // a template, skip the new definition.
12837   if (SkipBody && !hasVisibleDefinition(Definition) &&
12838       (Definition->getFormalLinkage() == InternalLinkage ||
12839        Definition->isInlined() ||
12840        Definition->getDescribedFunctionTemplate() ||
12841        Definition->getNumTemplateParameterLists())) {
12842     SkipBody->ShouldSkip = true;
12843     SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12844     if (auto *TD = Definition->getDescribedFunctionTemplate())
12845       makeMergedDefinitionVisible(TD);
12846     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12847     return;
12848   }
12849 
12850   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12851       Definition->getStorageClass() == SC_Extern)
12852     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12853         << FD->getDeclName() << getLangOpts().CPlusPlus;
12854   else
12855     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12856 
12857   Diag(Definition->getLocation(), diag::note_previous_definition);
12858   FD->setInvalidDecl();
12859 }
12860 
12861 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12862                                    Sema &S) {
12863   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12864 
12865   LambdaScopeInfo *LSI = S.PushLambdaScope();
12866   LSI->CallOperator = CallOperator;
12867   LSI->Lambda = LambdaClass;
12868   LSI->ReturnType = CallOperator->getReturnType();
12869   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12870 
12871   if (LCD == LCD_None)
12872     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12873   else if (LCD == LCD_ByCopy)
12874     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12875   else if (LCD == LCD_ByRef)
12876     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12877   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12878 
12879   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12880   LSI->Mutable = !CallOperator->isConst();
12881 
12882   // Add the captures to the LSI so they can be noted as already
12883   // captured within tryCaptureVar.
12884   auto I = LambdaClass->field_begin();
12885   for (const auto &C : LambdaClass->captures()) {
12886     if (C.capturesVariable()) {
12887       VarDecl *VD = C.getCapturedVar();
12888       if (VD->isInitCapture())
12889         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12890       QualType CaptureType = VD->getType();
12891       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12892       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12893           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12894           /*EllipsisLoc*/C.isPackExpansion()
12895                          ? C.getEllipsisLoc() : SourceLocation(),
12896           CaptureType, /*Expr*/ nullptr);
12897 
12898     } else if (C.capturesThis()) {
12899       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12900                               /*Expr*/ nullptr,
12901                               C.getCaptureKind() == LCK_StarThis);
12902     } else {
12903       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12904     }
12905     ++I;
12906   }
12907 }
12908 
12909 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12910                                     SkipBodyInfo *SkipBody) {
12911   if (!D) {
12912     // Parsing the function declaration failed in some way. Push on a fake scope
12913     // anyway so we can try to parse the function body.
12914     PushFunctionScope();
12915     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12916     return D;
12917   }
12918 
12919   FunctionDecl *FD = nullptr;
12920 
12921   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12922     FD = FunTmpl->getTemplatedDecl();
12923   else
12924     FD = cast<FunctionDecl>(D);
12925 
12926   // Do not push if it is a lambda because one is already pushed when building
12927   // the lambda in ActOnStartOfLambdaDefinition().
12928   if (!isLambdaCallOperator(FD))
12929     PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12930 
12931   // Check for defining attributes before the check for redefinition.
12932   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12933     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12934     FD->dropAttr<AliasAttr>();
12935     FD->setInvalidDecl();
12936   }
12937   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12938     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12939     FD->dropAttr<IFuncAttr>();
12940     FD->setInvalidDecl();
12941   }
12942 
12943   // See if this is a redefinition. If 'will have body' is already set, then
12944   // these checks were already performed when it was set.
12945   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12946     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12947 
12948     // If we're skipping the body, we're done. Don't enter the scope.
12949     if (SkipBody && SkipBody->ShouldSkip)
12950       return D;
12951   }
12952 
12953   // Mark this function as "will have a body eventually".  This lets users to
12954   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12955   // this function.
12956   FD->setWillHaveBody();
12957 
12958   // If we are instantiating a generic lambda call operator, push
12959   // a LambdaScopeInfo onto the function stack.  But use the information
12960   // that's already been calculated (ActOnLambdaExpr) to prime the current
12961   // LambdaScopeInfo.
12962   // When the template operator is being specialized, the LambdaScopeInfo,
12963   // has to be properly restored so that tryCaptureVariable doesn't try
12964   // and capture any new variables. In addition when calculating potential
12965   // captures during transformation of nested lambdas, it is necessary to
12966   // have the LSI properly restored.
12967   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12968     assert(inTemplateInstantiation() &&
12969            "There should be an active template instantiation on the stack "
12970            "when instantiating a generic lambda!");
12971     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12972   } else {
12973     // Enter a new function scope
12974     PushFunctionScope();
12975   }
12976 
12977   // Builtin functions cannot be defined.
12978   if (unsigned BuiltinID = FD->getBuiltinID()) {
12979     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12980         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12981       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12982       FD->setInvalidDecl();
12983     }
12984   }
12985 
12986   // The return type of a function definition must be complete
12987   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12988   QualType ResultType = FD->getReturnType();
12989   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12990       !FD->isInvalidDecl() &&
12991       RequireCompleteType(FD->getLocation(), ResultType,
12992                           diag::err_func_def_incomplete_result))
12993     FD->setInvalidDecl();
12994 
12995   if (FnBodyScope)
12996     PushDeclContext(FnBodyScope, FD);
12997 
12998   // Check the validity of our function parameters
12999   CheckParmsForFunctionDef(FD->parameters(),
13000                            /*CheckParameterNames=*/true);
13001 
13002   // Add non-parameter declarations already in the function to the current
13003   // scope.
13004   if (FnBodyScope) {
13005     for (Decl *NPD : FD->decls()) {
13006       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13007       if (!NonParmDecl)
13008         continue;
13009       assert(!isa<ParmVarDecl>(NonParmDecl) &&
13010              "parameters should not be in newly created FD yet");
13011 
13012       // If the decl has a name, make it accessible in the current scope.
13013       if (NonParmDecl->getDeclName())
13014         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13015 
13016       // Similarly, dive into enums and fish their constants out, making them
13017       // accessible in this scope.
13018       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13019         for (auto *EI : ED->enumerators())
13020           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13021       }
13022     }
13023   }
13024 
13025   // Introduce our parameters into the function scope
13026   for (auto Param : FD->parameters()) {
13027     Param->setOwningFunction(FD);
13028 
13029     // If this has an identifier, add it to the scope stack.
13030     if (Param->getIdentifier() && FnBodyScope) {
13031       CheckShadow(FnBodyScope, Param);
13032 
13033       PushOnScopeChains(Param, FnBodyScope);
13034     }
13035   }
13036 
13037   // Ensure that the function's exception specification is instantiated.
13038   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13039     ResolveExceptionSpec(D->getLocation(), FPT);
13040 
13041   // dllimport cannot be applied to non-inline function definitions.
13042   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13043       !FD->isTemplateInstantiation()) {
13044     assert(!FD->hasAttr<DLLExportAttr>());
13045     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13046     FD->setInvalidDecl();
13047     return D;
13048   }
13049   // We want to attach documentation to original Decl (which might be
13050   // a function template).
13051   ActOnDocumentableDecl(D);
13052   if (getCurLexicalContext()->isObjCContainer() &&
13053       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13054       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13055     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13056 
13057   return D;
13058 }
13059 
13060 /// Given the set of return statements within a function body,
13061 /// compute the variables that are subject to the named return value
13062 /// optimization.
13063 ///
13064 /// Each of the variables that is subject to the named return value
13065 /// optimization will be marked as NRVO variables in the AST, and any
13066 /// return statement that has a marked NRVO variable as its NRVO candidate can
13067 /// use the named return value optimization.
13068 ///
13069 /// This function applies a very simplistic algorithm for NRVO: if every return
13070 /// statement in the scope of a variable has the same NRVO candidate, that
13071 /// candidate is an NRVO variable.
13072 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
13073   ReturnStmt **Returns = Scope->Returns.data();
13074 
13075   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
13076     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13077       if (!NRVOCandidate->isNRVOVariable())
13078         Returns[I]->setNRVOCandidate(nullptr);
13079     }
13080   }
13081 }
13082 
13083 bool Sema::canDelayFunctionBody(const Declarator &D) {
13084   // We can't delay parsing the body of a constexpr function template (yet).
13085   if (D.getDeclSpec().isConstexprSpecified())
13086     return false;
13087 
13088   // We can't delay parsing the body of a function template with a deduced
13089   // return type (yet).
13090   if (D.getDeclSpec().hasAutoTypeSpec()) {
13091     // If the placeholder introduces a non-deduced trailing return type,
13092     // we can still delay parsing it.
13093     if (D.getNumTypeObjects()) {
13094       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13095       if (Outer.Kind == DeclaratorChunk::Function &&
13096           Outer.Fun.hasTrailingReturnType()) {
13097         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13098         return Ty.isNull() || !Ty->isUndeducedType();
13099       }
13100     }
13101     return false;
13102   }
13103 
13104   return true;
13105 }
13106 
13107 bool Sema::canSkipFunctionBody(Decl *D) {
13108   // We cannot skip the body of a function (or function template) which is
13109   // constexpr, since we may need to evaluate its body in order to parse the
13110   // rest of the file.
13111   // We cannot skip the body of a function with an undeduced return type,
13112   // because any callers of that function need to know the type.
13113   if (const FunctionDecl *FD = D->getAsFunction()) {
13114     if (FD->isConstexpr())
13115       return false;
13116     // We can't simply call Type::isUndeducedType here, because inside template
13117     // auto can be deduced to a dependent type, which is not considered
13118     // "undeduced".
13119     if (FD->getReturnType()->getContainedDeducedType())
13120       return false;
13121   }
13122   return Consumer.shouldSkipFunctionBody(D);
13123 }
13124 
13125 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13126   if (!Decl)
13127     return nullptr;
13128   if (FunctionDecl *FD = Decl->getAsFunction())
13129     FD->setHasSkippedBody();
13130   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13131     MD->setHasSkippedBody();
13132   return Decl;
13133 }
13134 
13135 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
13136   return ActOnFinishFunctionBody(D, BodyArg, false);
13137 }
13138 
13139 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
13140 /// body.
13141 class ExitFunctionBodyRAII {
13142 public:
13143   ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
13144   ~ExitFunctionBodyRAII() {
13145     if (!IsLambda)
13146       S.PopExpressionEvaluationContext();
13147   }
13148 
13149 private:
13150   Sema &S;
13151   bool IsLambda = false;
13152 };
13153 
13154 static void diagnoseImplicitlyRetainedSelf(Sema &S) {
13155   llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
13156 
13157   auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
13158     if (EscapeInfo.count(BD))
13159       return EscapeInfo[BD];
13160 
13161     bool R = false;
13162     const BlockDecl *CurBD = BD;
13163 
13164     do {
13165       R = !CurBD->doesNotEscape();
13166       if (R)
13167         break;
13168       CurBD = CurBD->getParent()->getInnermostBlockDecl();
13169     } while (CurBD);
13170 
13171     return EscapeInfo[BD] = R;
13172   };
13173 
13174   // If the location where 'self' is implicitly retained is inside a escaping
13175   // block, emit a diagnostic.
13176   for (const std::pair<SourceLocation, const BlockDecl *> &P :
13177        S.ImplicitlyRetainedSelfLocs)
13178     if (IsOrNestedInEscapingBlock(P.second))
13179       S.Diag(P.first, diag::warn_implicitly_retains_self)
13180           << FixItHint::CreateInsertion(P.first, "self->");
13181 }
13182 
13183 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
13184                                     bool IsInstantiation) {
13185   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13186 
13187   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13188   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13189 
13190   if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13191     CheckCompletedCoroutineBody(FD, Body);
13192 
13193   // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13194   // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13195   // meant to pop the context added in ActOnStartOfFunctionDef().
13196   ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13197 
13198   if (FD) {
13199     FD->setBody(Body);
13200     FD->setWillHaveBody(false);
13201 
13202     if (getLangOpts().CPlusPlus14) {
13203       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13204           FD->getReturnType()->isUndeducedType()) {
13205         // If the function has a deduced result type but contains no 'return'
13206         // statements, the result type as written must be exactly 'auto', and
13207         // the deduced result type is 'void'.
13208         if (!FD->getReturnType()->getAs<AutoType>()) {
13209           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13210               << FD->getReturnType();
13211           FD->setInvalidDecl();
13212         } else {
13213           // Substitute 'void' for the 'auto' in the type.
13214           TypeLoc ResultType = getReturnTypeLoc(FD);
13215           Context.adjustDeducedFunctionResultType(
13216               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
13217         }
13218       }
13219     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13220       // In C++11, we don't use 'auto' deduction rules for lambda call
13221       // operators because we don't support return type deduction.
13222       auto *LSI = getCurLambda();
13223       if (LSI->HasImplicitReturnType) {
13224         deduceClosureReturnType(*LSI);
13225 
13226         // C++11 [expr.prim.lambda]p4:
13227         //   [...] if there are no return statements in the compound-statement
13228         //   [the deduced type is] the type void
13229         QualType RetType =
13230             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13231 
13232         // Update the return type to the deduced type.
13233         const FunctionProtoType *Proto =
13234             FD->getType()->getAs<FunctionProtoType>();
13235         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
13236                                             Proto->getExtProtoInfo()));
13237       }
13238     }
13239 
13240     // If the function implicitly returns zero (like 'main') or is naked,
13241     // don't complain about missing return statements.
13242     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13243       WP.disableCheckFallThrough();
13244 
13245     // MSVC permits the use of pure specifier (=0) on function definition,
13246     // defined at class scope, warn about this non-standard construct.
13247     if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
13248       Diag(FD->getLocation(), diag::ext_pure_function_definition);
13249 
13250     if (!FD->isInvalidDecl()) {
13251       // Don't diagnose unused parameters of defaulted or deleted functions.
13252       if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13253         DiagnoseUnusedParameters(FD->parameters());
13254       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13255                                              FD->getReturnType(), FD);
13256 
13257       // If this is a structor, we need a vtable.
13258       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13259         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13260       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13261         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13262 
13263       // Try to apply the named return value optimization. We have to check
13264       // if we can do this here because lambdas keep return statements around
13265       // to deduce an implicit return type.
13266       if (FD->getReturnType()->isRecordType() &&
13267           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13268         computeNRVO(Body, getCurFunction());
13269     }
13270 
13271     // GNU warning -Wmissing-prototypes:
13272     //   Warn if a global function is defined without a previous
13273     //   prototype declaration. This warning is issued even if the
13274     //   definition itself provides a prototype. The aim is to detect
13275     //   global functions that fail to be declared in header files.
13276     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13277     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
13278       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13279 
13280       if (PossibleZeroParamPrototype) {
13281         // We found a declaration that is not a prototype,
13282         // but that could be a zero-parameter prototype
13283         if (TypeSourceInfo *TI =
13284                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
13285           TypeLoc TL = TI->getTypeLoc();
13286           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13287             Diag(PossibleZeroParamPrototype->getLocation(),
13288                  diag::note_declaration_not_a_prototype)
13289                 << PossibleZeroParamPrototype
13290                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13291         }
13292       }
13293 
13294       // GNU warning -Wstrict-prototypes
13295       //   Warn if K&R function is defined without a previous declaration.
13296       //   This warning is issued only if the definition itself does not provide
13297       //   a prototype. Only K&R definitions do not provide a prototype.
13298       //   An empty list in a function declarator that is part of a definition
13299       //   of that function specifies that the function has no parameters
13300       //   (C99 6.7.5.3p14)
13301       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13302           !LangOpts.CPlusPlus) {
13303         TypeSourceInfo *TI = FD->getTypeSourceInfo();
13304         TypeLoc TL = TI->getTypeLoc();
13305         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13306         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13307       }
13308     }
13309 
13310     // Warn on CPUDispatch with an actual body.
13311     if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13312       if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13313         if (!CmpndBody->body_empty())
13314           Diag(CmpndBody->body_front()->getBeginLoc(),
13315                diag::warn_dispatch_body_ignored);
13316 
13317     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13318       const CXXMethodDecl *KeyFunction;
13319       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13320           MD->isVirtual() &&
13321           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13322           MD == KeyFunction->getCanonicalDecl()) {
13323         // Update the key-function state if necessary for this ABI.
13324         if (FD->isInlined() &&
13325             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13326           Context.setNonKeyFunction(MD);
13327 
13328           // If the newly-chosen key function is already defined, then we
13329           // need to mark the vtable as used retroactively.
13330           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13331           const FunctionDecl *Definition;
13332           if (KeyFunction && KeyFunction->isDefined(Definition))
13333             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13334         } else {
13335           // We just defined they key function; mark the vtable as used.
13336           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13337         }
13338       }
13339     }
13340 
13341     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13342            "Function parsing confused");
13343   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13344     assert(MD == getCurMethodDecl() && "Method parsing confused");
13345     MD->setBody(Body);
13346     if (!MD->isInvalidDecl()) {
13347       if (!MD->hasSkippedBody())
13348         DiagnoseUnusedParameters(MD->parameters());
13349       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13350                                              MD->getReturnType(), MD);
13351 
13352       if (Body)
13353         computeNRVO(Body, getCurFunction());
13354     }
13355     if (getCurFunction()->ObjCShouldCallSuper) {
13356       Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13357           << MD->getSelector().getAsString();
13358       getCurFunction()->ObjCShouldCallSuper = false;
13359     }
13360     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13361       const ObjCMethodDecl *InitMethod = nullptr;
13362       bool isDesignated =
13363           MD->isDesignatedInitializerForTheInterface(&InitMethod);
13364       assert(isDesignated && InitMethod);
13365       (void)isDesignated;
13366 
13367       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13368         auto IFace = MD->getClassInterface();
13369         if (!IFace)
13370           return false;
13371         auto SuperD = IFace->getSuperClass();
13372         if (!SuperD)
13373           return false;
13374         return SuperD->getIdentifier() ==
13375             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13376       };
13377       // Don't issue this warning for unavailable inits or direct subclasses
13378       // of NSObject.
13379       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13380         Diag(MD->getLocation(),
13381              diag::warn_objc_designated_init_missing_super_call);
13382         Diag(InitMethod->getLocation(),
13383              diag::note_objc_designated_init_marked_here);
13384       }
13385       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13386     }
13387     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13388       // Don't issue this warning for unavaialable inits.
13389       if (!MD->isUnavailable())
13390         Diag(MD->getLocation(),
13391              diag::warn_objc_secondary_init_missing_init_call);
13392       getCurFunction()->ObjCWarnForNoInitDelegation = false;
13393     }
13394 
13395     diagnoseImplicitlyRetainedSelf(*this);
13396   } else {
13397     // Parsing the function declaration failed in some way. Pop the fake scope
13398     // we pushed on.
13399     PopFunctionScopeInfo(ActivePolicy, dcl);
13400     return nullptr;
13401   }
13402 
13403   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13404     DiagnoseUnguardedAvailabilityViolations(dcl);
13405 
13406   assert(!getCurFunction()->ObjCShouldCallSuper &&
13407          "This should only be set for ObjC methods, which should have been "
13408          "handled in the block above.");
13409 
13410   // Verify and clean out per-function state.
13411   if (Body && (!FD || !FD->isDefaulted())) {
13412     // C++ constructors that have function-try-blocks can't have return
13413     // statements in the handlers of that block. (C++ [except.handle]p14)
13414     // Verify this.
13415     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13416       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13417 
13418     // Verify that gotos and switch cases don't jump into scopes illegally.
13419     if (getCurFunction()->NeedsScopeChecking() &&
13420         !PP.isCodeCompletionEnabled())
13421       DiagnoseInvalidJumps(Body);
13422 
13423     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13424       if (!Destructor->getParent()->isDependentType())
13425         CheckDestructor(Destructor);
13426 
13427       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13428                                              Destructor->getParent());
13429     }
13430 
13431     // If any errors have occurred, clear out any temporaries that may have
13432     // been leftover. This ensures that these temporaries won't be picked up for
13433     // deletion in some later function.
13434     if (getDiagnostics().hasErrorOccurred() ||
13435         getDiagnostics().getSuppressAllDiagnostics()) {
13436       DiscardCleanupsInEvaluationContext();
13437     }
13438     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13439         !isa<FunctionTemplateDecl>(dcl)) {
13440       // Since the body is valid, issue any analysis-based warnings that are
13441       // enabled.
13442       ActivePolicy = &WP;
13443     }
13444 
13445     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13446         (!CheckConstexprFunctionDecl(FD) ||
13447          !CheckConstexprFunctionBody(FD, Body)))
13448       FD->setInvalidDecl();
13449 
13450     if (FD && FD->hasAttr<NakedAttr>()) {
13451       for (const Stmt *S : Body->children()) {
13452         // Allow local register variables without initializer as they don't
13453         // require prologue.
13454         bool RegisterVariables = false;
13455         if (auto *DS = dyn_cast<DeclStmt>(S)) {
13456           for (const auto *Decl : DS->decls()) {
13457             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13458               RegisterVariables =
13459                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13460               if (!RegisterVariables)
13461                 break;
13462             }
13463           }
13464         }
13465         if (RegisterVariables)
13466           continue;
13467         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13468           Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13469           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13470           FD->setInvalidDecl();
13471           break;
13472         }
13473       }
13474     }
13475 
13476     assert(ExprCleanupObjects.size() ==
13477                ExprEvalContexts.back().NumCleanupObjects &&
13478            "Leftover temporaries in function");
13479     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13480     assert(MaybeODRUseExprs.empty() &&
13481            "Leftover expressions for odr-use checking");
13482   }
13483 
13484   if (!IsInstantiation)
13485     PopDeclContext();
13486 
13487   PopFunctionScopeInfo(ActivePolicy, dcl);
13488   // If any errors have occurred, clear out any temporaries that may have
13489   // been leftover. This ensures that these temporaries won't be picked up for
13490   // deletion in some later function.
13491   if (getDiagnostics().hasErrorOccurred()) {
13492     DiscardCleanupsInEvaluationContext();
13493   }
13494 
13495   return dcl;
13496 }
13497 
13498 /// When we finish delayed parsing of an attribute, we must attach it to the
13499 /// relevant Decl.
13500 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
13501                                        ParsedAttributes &Attrs) {
13502   // Always attach attributes to the underlying decl.
13503   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13504     D = TD->getTemplatedDecl();
13505   ProcessDeclAttributeList(S, D, Attrs);
13506 
13507   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13508     if (Method->isStatic())
13509       checkThisInStaticMemberFunctionAttributes(Method);
13510 }
13511 
13512 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13513 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13514 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13515                                           IdentifierInfo &II, Scope *S) {
13516   // Find the scope in which the identifier is injected and the corresponding
13517   // DeclContext.
13518   // FIXME: C89 does not say what happens if there is no enclosing block scope.
13519   // In that case, we inject the declaration into the translation unit scope
13520   // instead.
13521   Scope *BlockScope = S;
13522   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13523     BlockScope = BlockScope->getParent();
13524 
13525   Scope *ContextScope = BlockScope;
13526   while (!ContextScope->getEntity())
13527     ContextScope = ContextScope->getParent();
13528   ContextRAII SavedContext(*this, ContextScope->getEntity());
13529 
13530   // Before we produce a declaration for an implicitly defined
13531   // function, see whether there was a locally-scoped declaration of
13532   // this name as a function or variable. If so, use that
13533   // (non-visible) declaration, and complain about it.
13534   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13535   if (ExternCPrev) {
13536     // We still need to inject the function into the enclosing block scope so
13537     // that later (non-call) uses can see it.
13538     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13539 
13540     // C89 footnote 38:
13541     //   If in fact it is not defined as having type "function returning int",
13542     //   the behavior is undefined.
13543     if (!isa<FunctionDecl>(ExternCPrev) ||
13544         !Context.typesAreCompatible(
13545             cast<FunctionDecl>(ExternCPrev)->getType(),
13546             Context.getFunctionNoProtoType(Context.IntTy))) {
13547       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13548           << ExternCPrev << !getLangOpts().C99;
13549       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13550       return ExternCPrev;
13551     }
13552   }
13553 
13554   // Extension in C99.  Legal in C90, but warn about it.
13555   unsigned diag_id;
13556   if (II.getName().startswith("__builtin_"))
13557     diag_id = diag::warn_builtin_unknown;
13558   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13559   else if (getLangOpts().OpenCL)
13560     diag_id = diag::err_opencl_implicit_function_decl;
13561   else if (getLangOpts().C99)
13562     diag_id = diag::ext_implicit_function_decl;
13563   else
13564     diag_id = diag::warn_implicit_function_decl;
13565   Diag(Loc, diag_id) << &II;
13566 
13567   // If we found a prior declaration of this function, don't bother building
13568   // another one. We've already pushed that one into scope, so there's nothing
13569   // more to do.
13570   if (ExternCPrev)
13571     return ExternCPrev;
13572 
13573   // Because typo correction is expensive, only do it if the implicit
13574   // function declaration is going to be treated as an error.
13575   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13576     TypoCorrection Corrected;
13577     DeclFilterCCC<FunctionDecl> CCC{};
13578     if (S && (Corrected =
13579                   CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13580                               S, nullptr, CCC, CTK_NonError)))
13581       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13582                    /*ErrorRecovery*/false);
13583   }
13584 
13585   // Set a Declarator for the implicit definition: int foo();
13586   const char *Dummy;
13587   AttributeFactory attrFactory;
13588   DeclSpec DS(attrFactory);
13589   unsigned DiagID;
13590   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13591                                   Context.getPrintingPolicy());
13592   (void)Error; // Silence warning.
13593   assert(!Error && "Error setting up implicit decl!");
13594   SourceLocation NoLoc;
13595   Declarator D(DS, DeclaratorContext::BlockContext);
13596   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13597                                              /*IsAmbiguous=*/false,
13598                                              /*LParenLoc=*/NoLoc,
13599                                              /*Params=*/nullptr,
13600                                              /*NumParams=*/0,
13601                                              /*EllipsisLoc=*/NoLoc,
13602                                              /*RParenLoc=*/NoLoc,
13603                                              /*RefQualifierIsLvalueRef=*/true,
13604                                              /*RefQualifierLoc=*/NoLoc,
13605                                              /*MutableLoc=*/NoLoc, EST_None,
13606                                              /*ESpecRange=*/SourceRange(),
13607                                              /*Exceptions=*/nullptr,
13608                                              /*ExceptionRanges=*/nullptr,
13609                                              /*NumExceptions=*/0,
13610                                              /*NoexceptExpr=*/nullptr,
13611                                              /*ExceptionSpecTokens=*/nullptr,
13612                                              /*DeclsInPrototype=*/None, Loc,
13613                                              Loc, D),
13614                 std::move(DS.getAttributes()), SourceLocation());
13615   D.SetIdentifier(&II, Loc);
13616 
13617   // Insert this function into the enclosing block scope.
13618   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13619   FD->setImplicit();
13620 
13621   AddKnownFunctionAttributes(FD);
13622 
13623   return FD;
13624 }
13625 
13626 /// Adds any function attributes that we know a priori based on
13627 /// the declaration of this function.
13628 ///
13629 /// These attributes can apply both to implicitly-declared builtins
13630 /// (like __builtin___printf_chk) or to library-declared functions
13631 /// like NSLog or printf.
13632 ///
13633 /// We need to check for duplicate attributes both here and where user-written
13634 /// attributes are applied to declarations.
13635 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13636   if (FD->isInvalidDecl())
13637     return;
13638 
13639   // If this is a built-in function, map its builtin attributes to
13640   // actual attributes.
13641   if (unsigned BuiltinID = FD->getBuiltinID()) {
13642     // Handle printf-formatting attributes.
13643     unsigned FormatIdx;
13644     bool HasVAListArg;
13645     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13646       if (!FD->hasAttr<FormatAttr>()) {
13647         const char *fmt = "printf";
13648         unsigned int NumParams = FD->getNumParams();
13649         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13650             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13651           fmt = "NSString";
13652         FD->addAttr(FormatAttr::CreateImplicit(Context,
13653                                                &Context.Idents.get(fmt),
13654                                                FormatIdx+1,
13655                                                HasVAListArg ? 0 : FormatIdx+2,
13656                                                FD->getLocation()));
13657       }
13658     }
13659     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13660                                              HasVAListArg)) {
13661      if (!FD->hasAttr<FormatAttr>())
13662        FD->addAttr(FormatAttr::CreateImplicit(Context,
13663                                               &Context.Idents.get("scanf"),
13664                                               FormatIdx+1,
13665                                               HasVAListArg ? 0 : FormatIdx+2,
13666                                               FD->getLocation()));
13667     }
13668 
13669     // Handle automatically recognized callbacks.
13670     SmallVector<int, 4> Encoding;
13671     if (!FD->hasAttr<CallbackAttr>() &&
13672         Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13673       FD->addAttr(CallbackAttr::CreateImplicit(
13674           Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13675 
13676     // Mark const if we don't care about errno and that is the only thing
13677     // preventing the function from being const. This allows IRgen to use LLVM
13678     // intrinsics for such functions.
13679     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13680         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13681       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13682 
13683     // We make "fma" on some platforms const because we know it does not set
13684     // errno in those environments even though it could set errno based on the
13685     // C standard.
13686     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13687     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13688         !FD->hasAttr<ConstAttr>()) {
13689       switch (BuiltinID) {
13690       case Builtin::BI__builtin_fma:
13691       case Builtin::BI__builtin_fmaf:
13692       case Builtin::BI__builtin_fmal:
13693       case Builtin::BIfma:
13694       case Builtin::BIfmaf:
13695       case Builtin::BIfmal:
13696         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13697         break;
13698       default:
13699         break;
13700       }
13701     }
13702 
13703     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13704         !FD->hasAttr<ReturnsTwiceAttr>())
13705       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13706                                          FD->getLocation()));
13707     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13708       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13709     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13710       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13711     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13712       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13713     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13714         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13715       // Add the appropriate attribute, depending on the CUDA compilation mode
13716       // and which target the builtin belongs to. For example, during host
13717       // compilation, aux builtins are __device__, while the rest are __host__.
13718       if (getLangOpts().CUDAIsDevice !=
13719           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13720         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13721       else
13722         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13723     }
13724   }
13725 
13726   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13727   // throw, add an implicit nothrow attribute to any extern "C" function we come
13728   // across.
13729   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13730       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13731     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13732     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13733       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13734   }
13735 
13736   IdentifierInfo *Name = FD->getIdentifier();
13737   if (!Name)
13738     return;
13739   if ((!getLangOpts().CPlusPlus &&
13740        FD->getDeclContext()->isTranslationUnit()) ||
13741       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13742        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13743        LinkageSpecDecl::lang_c)) {
13744     // Okay: this could be a libc/libm/Objective-C function we know
13745     // about.
13746   } else
13747     return;
13748 
13749   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13750     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13751     // target-specific builtins, perhaps?
13752     if (!FD->hasAttr<FormatAttr>())
13753       FD->addAttr(FormatAttr::CreateImplicit(Context,
13754                                              &Context.Idents.get("printf"), 2,
13755                                              Name->isStr("vasprintf") ? 0 : 3,
13756                                              FD->getLocation()));
13757   }
13758 
13759   if (Name->isStr("__CFStringMakeConstantString")) {
13760     // We already have a __builtin___CFStringMakeConstantString,
13761     // but builds that use -fno-constant-cfstrings don't go through that.
13762     if (!FD->hasAttr<FormatArgAttr>())
13763       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13764                                                 FD->getLocation()));
13765   }
13766 }
13767 
13768 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13769                                     TypeSourceInfo *TInfo) {
13770   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13771   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13772 
13773   if (!TInfo) {
13774     assert(D.isInvalidType() && "no declarator info for valid type");
13775     TInfo = Context.getTrivialTypeSourceInfo(T);
13776   }
13777 
13778   // Scope manipulation handled by caller.
13779   TypedefDecl *NewTD =
13780       TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
13781                           D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13782 
13783   // Bail out immediately if we have an invalid declaration.
13784   if (D.isInvalidType()) {
13785     NewTD->setInvalidDecl();
13786     return NewTD;
13787   }
13788 
13789   if (D.getDeclSpec().isModulePrivateSpecified()) {
13790     if (CurContext->isFunctionOrMethod())
13791       Diag(NewTD->getLocation(), diag::err_module_private_local)
13792         << 2 << NewTD->getDeclName()
13793         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13794         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13795     else
13796       NewTD->setModulePrivate();
13797   }
13798 
13799   // C++ [dcl.typedef]p8:
13800   //   If the typedef declaration defines an unnamed class (or
13801   //   enum), the first typedef-name declared by the declaration
13802   //   to be that class type (or enum type) is used to denote the
13803   //   class type (or enum type) for linkage purposes only.
13804   // We need to check whether the type was declared in the declaration.
13805   switch (D.getDeclSpec().getTypeSpecType()) {
13806   case TST_enum:
13807   case TST_struct:
13808   case TST_interface:
13809   case TST_union:
13810   case TST_class: {
13811     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13812     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13813     break;
13814   }
13815 
13816   default:
13817     break;
13818   }
13819 
13820   return NewTD;
13821 }
13822 
13823 /// Check that this is a valid underlying type for an enum declaration.
13824 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13825   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13826   QualType T = TI->getType();
13827 
13828   if (T->isDependentType())
13829     return false;
13830 
13831   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13832     if (BT->isInteger())
13833       return false;
13834 
13835   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13836   return true;
13837 }
13838 
13839 /// Check whether this is a valid redeclaration of a previous enumeration.
13840 /// \return true if the redeclaration was invalid.
13841 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13842                                   QualType EnumUnderlyingTy, bool IsFixed,
13843                                   const EnumDecl *Prev) {
13844   if (IsScoped != Prev->isScoped()) {
13845     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13846       << Prev->isScoped();
13847     Diag(Prev->getLocation(), diag::note_previous_declaration);
13848     return true;
13849   }
13850 
13851   if (IsFixed && Prev->isFixed()) {
13852     if (!EnumUnderlyingTy->isDependentType() &&
13853         !Prev->getIntegerType()->isDependentType() &&
13854         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13855                                         Prev->getIntegerType())) {
13856       // TODO: Highlight the underlying type of the redeclaration.
13857       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13858         << EnumUnderlyingTy << Prev->getIntegerType();
13859       Diag(Prev->getLocation(), diag::note_previous_declaration)
13860           << Prev->getIntegerTypeRange();
13861       return true;
13862     }
13863   } else if (IsFixed != Prev->isFixed()) {
13864     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13865       << Prev->isFixed();
13866     Diag(Prev->getLocation(), diag::note_previous_declaration);
13867     return true;
13868   }
13869 
13870   return false;
13871 }
13872 
13873 /// Get diagnostic %select index for tag kind for
13874 /// redeclaration diagnostic message.
13875 /// WARNING: Indexes apply to particular diagnostics only!
13876 ///
13877 /// \returns diagnostic %select index.
13878 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13879   switch (Tag) {
13880   case TTK_Struct: return 0;
13881   case TTK_Interface: return 1;
13882   case TTK_Class:  return 2;
13883   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13884   }
13885 }
13886 
13887 /// Determine if tag kind is a class-key compatible with
13888 /// class for redeclaration (class, struct, or __interface).
13889 ///
13890 /// \returns true iff the tag kind is compatible.
13891 static bool isClassCompatTagKind(TagTypeKind Tag)
13892 {
13893   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13894 }
13895 
13896 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13897                                              TagTypeKind TTK) {
13898   if (isa<TypedefDecl>(PrevDecl))
13899     return NTK_Typedef;
13900   else if (isa<TypeAliasDecl>(PrevDecl))
13901     return NTK_TypeAlias;
13902   else if (isa<ClassTemplateDecl>(PrevDecl))
13903     return NTK_Template;
13904   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13905     return NTK_TypeAliasTemplate;
13906   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13907     return NTK_TemplateTemplateArgument;
13908   switch (TTK) {
13909   case TTK_Struct:
13910   case TTK_Interface:
13911   case TTK_Class:
13912     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13913   case TTK_Union:
13914     return NTK_NonUnion;
13915   case TTK_Enum:
13916     return NTK_NonEnum;
13917   }
13918   llvm_unreachable("invalid TTK");
13919 }
13920 
13921 /// Determine whether a tag with a given kind is acceptable
13922 /// as a redeclaration of the given tag declaration.
13923 ///
13924 /// \returns true if the new tag kind is acceptable, false otherwise.
13925 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13926                                         TagTypeKind NewTag, bool isDefinition,
13927                                         SourceLocation NewTagLoc,
13928                                         const IdentifierInfo *Name) {
13929   // C++ [dcl.type.elab]p3:
13930   //   The class-key or enum keyword present in the
13931   //   elaborated-type-specifier shall agree in kind with the
13932   //   declaration to which the name in the elaborated-type-specifier
13933   //   refers. This rule also applies to the form of
13934   //   elaborated-type-specifier that declares a class-name or
13935   //   friend class since it can be construed as referring to the
13936   //   definition of the class. Thus, in any
13937   //   elaborated-type-specifier, the enum keyword shall be used to
13938   //   refer to an enumeration (7.2), the union class-key shall be
13939   //   used to refer to a union (clause 9), and either the class or
13940   //   struct class-key shall be used to refer to a class (clause 9)
13941   //   declared using the class or struct class-key.
13942   TagTypeKind OldTag = Previous->getTagKind();
13943   if (OldTag != NewTag &&
13944       !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
13945     return false;
13946 
13947   // Tags are compatible, but we might still want to warn on mismatched tags.
13948   // Non-class tags can't be mismatched at this point.
13949   if (!isClassCompatTagKind(NewTag))
13950     return true;
13951 
13952   // Declarations for which -Wmismatched-tags is disabled are entirely ignored
13953   // by our warning analysis. We don't want to warn about mismatches with (eg)
13954   // declarations in system headers that are designed to be specialized, but if
13955   // a user asks us to warn, we should warn if their code contains mismatched
13956   // declarations.
13957   auto IsIgnoredLoc = [&](SourceLocation Loc) {
13958     return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
13959                                       Loc);
13960   };
13961   if (IsIgnoredLoc(NewTagLoc))
13962     return true;
13963 
13964   auto IsIgnored = [&](const TagDecl *Tag) {
13965     return IsIgnoredLoc(Tag->getLocation());
13966   };
13967   while (IsIgnored(Previous)) {
13968     Previous = Previous->getPreviousDecl();
13969     if (!Previous)
13970       return true;
13971     OldTag = Previous->getTagKind();
13972   }
13973 
13974   bool isTemplate = false;
13975   if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13976     isTemplate = Record->getDescribedClassTemplate();
13977 
13978   if (inTemplateInstantiation()) {
13979     if (OldTag != NewTag) {
13980       // In a template instantiation, do not offer fix-its for tag mismatches
13981       // since they usually mess up the template instead of fixing the problem.
13982       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13983         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13984         << getRedeclDiagFromTagKind(OldTag);
13985       // FIXME: Note previous location?
13986     }
13987     return true;
13988   }
13989 
13990   if (isDefinition) {
13991     // On definitions, check all previous tags and issue a fix-it for each
13992     // one that doesn't match the current tag.
13993     if (Previous->getDefinition()) {
13994       // Don't suggest fix-its for redefinitions.
13995       return true;
13996     }
13997 
13998     bool previousMismatch = false;
13999     for (const TagDecl *I : Previous->redecls()) {
14000       if (I->getTagKind() != NewTag) {
14001         // Ignore previous declarations for which the warning was disabled.
14002         if (IsIgnored(I))
14003           continue;
14004 
14005         if (!previousMismatch) {
14006           previousMismatch = true;
14007           Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
14008             << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14009             << getRedeclDiagFromTagKind(I->getTagKind());
14010         }
14011         Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
14012           << getRedeclDiagFromTagKind(NewTag)
14013           << FixItHint::CreateReplacement(I->getInnerLocStart(),
14014                TypeWithKeyword::getTagTypeKindName(NewTag));
14015       }
14016     }
14017     return true;
14018   }
14019 
14020   // Identify the prevailing tag kind: this is the kind of the definition (if
14021   // there is a non-ignored definition), or otherwise the kind of the prior
14022   // (non-ignored) declaration.
14023   const TagDecl *PrevDef = Previous->getDefinition();
14024   if (PrevDef && IsIgnored(PrevDef))
14025     PrevDef = nullptr;
14026   const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
14027   if (Redecl->getTagKind() != NewTag) {
14028     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
14029       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14030       << getRedeclDiagFromTagKind(OldTag);
14031     Diag(Redecl->getLocation(), diag::note_previous_use);
14032 
14033     // If there is a previous definition, suggest a fix-it.
14034     if (PrevDef) {
14035       Diag(NewTagLoc, diag::note_struct_class_suggestion)
14036         << getRedeclDiagFromTagKind(Redecl->getTagKind())
14037         << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14038              TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14039     }
14040   }
14041 
14042   return true;
14043 }
14044 
14045 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14046 /// from an outer enclosing namespace or file scope inside a friend declaration.
14047 /// This should provide the commented out code in the following snippet:
14048 ///   namespace N {
14049 ///     struct X;
14050 ///     namespace M {
14051 ///       struct Y { friend struct /*N::*/ X; };
14052 ///     }
14053 ///   }
14054 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
14055                                          SourceLocation NameLoc) {
14056   // While the decl is in a namespace, do repeated lookup of that name and see
14057   // if we get the same namespace back.  If we do not, continue until
14058   // translation unit scope, at which point we have a fully qualified NNS.
14059   SmallVector<IdentifierInfo *, 4> Namespaces;
14060   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14061   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14062     // This tag should be declared in a namespace, which can only be enclosed by
14063     // other namespaces.  Bail if there's an anonymous namespace in the chain.
14064     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14065     if (!Namespace || Namespace->isAnonymousNamespace())
14066       return FixItHint();
14067     IdentifierInfo *II = Namespace->getIdentifier();
14068     Namespaces.push_back(II);
14069     NamedDecl *Lookup = SemaRef.LookupSingleName(
14070         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
14071     if (Lookup == Namespace)
14072       break;
14073   }
14074 
14075   // Once we have all the namespaces, reverse them to go outermost first, and
14076   // build an NNS.
14077   SmallString<64> Insertion;
14078   llvm::raw_svector_ostream OS(Insertion);
14079   if (DC->isTranslationUnit())
14080     OS << "::";
14081   std::reverse(Namespaces.begin(), Namespaces.end());
14082   for (auto *II : Namespaces)
14083     OS << II->getName() << "::";
14084   return FixItHint::CreateInsertion(NameLoc, Insertion);
14085 }
14086 
14087 /// Determine whether a tag originally declared in context \p OldDC can
14088 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14089 /// found a declaration in \p OldDC as a previous decl, perhaps through a
14090 /// using-declaration).
14091 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
14092                                          DeclContext *NewDC) {
14093   OldDC = OldDC->getRedeclContext();
14094   NewDC = NewDC->getRedeclContext();
14095 
14096   if (OldDC->Equals(NewDC))
14097     return true;
14098 
14099   // In MSVC mode, we allow a redeclaration if the contexts are related (either
14100   // encloses the other).
14101   if (S.getLangOpts().MSVCCompat &&
14102       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14103     return true;
14104 
14105   return false;
14106 }
14107 
14108 /// This is invoked when we see 'struct foo' or 'struct {'.  In the
14109 /// former case, Name will be non-null.  In the later case, Name will be null.
14110 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14111 /// reference/declaration/definition of a tag.
14112 ///
14113 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
14114 /// trailing-type-specifier) other than one in an alias-declaration.
14115 ///
14116 /// \param SkipBody If non-null, will be set to indicate if the caller should
14117 /// skip the definition of this tag and treat it as if it were a declaration.
14118 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
14119                      SourceLocation KWLoc, CXXScopeSpec &SS,
14120                      IdentifierInfo *Name, SourceLocation NameLoc,
14121                      const ParsedAttributesView &Attrs, AccessSpecifier AS,
14122                      SourceLocation ModulePrivateLoc,
14123                      MultiTemplateParamsArg TemplateParameterLists,
14124                      bool &OwnedDecl, bool &IsDependent,
14125                      SourceLocation ScopedEnumKWLoc,
14126                      bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
14127                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
14128                      SkipBodyInfo *SkipBody) {
14129   // If this is not a definition, it must have a name.
14130   IdentifierInfo *OrigName = Name;
14131   assert((Name != nullptr || TUK == TUK_Definition) &&
14132          "Nameless record must be a definition!");
14133   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14134 
14135   OwnedDecl = false;
14136   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14137   bool ScopedEnum = ScopedEnumKWLoc.isValid();
14138 
14139   // FIXME: Check member specializations more carefully.
14140   bool isMemberSpecialization = false;
14141   bool Invalid = false;
14142 
14143   // We only need to do this matching if we have template parameters
14144   // or a scope specifier, which also conveniently avoids this work
14145   // for non-C++ cases.
14146   if (TemplateParameterLists.size() > 0 ||
14147       (SS.isNotEmpty() && TUK != TUK_Reference)) {
14148     if (TemplateParameterList *TemplateParams =
14149             MatchTemplateParametersToScopeSpecifier(
14150                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14151                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14152       if (Kind == TTK_Enum) {
14153         Diag(KWLoc, diag::err_enum_template);
14154         return nullptr;
14155       }
14156 
14157       if (TemplateParams->size() > 0) {
14158         // This is a declaration or definition of a class template (which may
14159         // be a member of another template).
14160 
14161         if (Invalid)
14162           return nullptr;
14163 
14164         OwnedDecl = false;
14165         DeclResult Result = CheckClassTemplate(
14166             S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14167             AS, ModulePrivateLoc,
14168             /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14169             TemplateParameterLists.data(), SkipBody);
14170         return Result.get();
14171       } else {
14172         // The "template<>" header is extraneous.
14173         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14174           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14175         isMemberSpecialization = true;
14176       }
14177     }
14178   }
14179 
14180   // Figure out the underlying type if this a enum declaration. We need to do
14181   // this early, because it's needed to detect if this is an incompatible
14182   // redeclaration.
14183   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14184   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14185 
14186   if (Kind == TTK_Enum) {
14187     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14188       // No underlying type explicitly specified, or we failed to parse the
14189       // type, default to int.
14190       EnumUnderlying = Context.IntTy.getTypePtr();
14191     } else if (UnderlyingType.get()) {
14192       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14193       // integral type; any cv-qualification is ignored.
14194       TypeSourceInfo *TI = nullptr;
14195       GetTypeFromParser(UnderlyingType.get(), &TI);
14196       EnumUnderlying = TI;
14197 
14198       if (CheckEnumUnderlyingType(TI))
14199         // Recover by falling back to int.
14200         EnumUnderlying = Context.IntTy.getTypePtr();
14201 
14202       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14203                                           UPPC_FixedUnderlyingType))
14204         EnumUnderlying = Context.IntTy.getTypePtr();
14205 
14206     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14207       // For MSVC ABI compatibility, unfixed enums must use an underlying type
14208       // of 'int'. However, if this is an unfixed forward declaration, don't set
14209       // the underlying type unless the user enables -fms-compatibility. This
14210       // makes unfixed forward declared enums incomplete and is more conforming.
14211       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14212         EnumUnderlying = Context.IntTy.getTypePtr();
14213     }
14214   }
14215 
14216   DeclContext *SearchDC = CurContext;
14217   DeclContext *DC = CurContext;
14218   bool isStdBadAlloc = false;
14219   bool isStdAlignValT = false;
14220 
14221   RedeclarationKind Redecl = forRedeclarationInCurContext();
14222   if (TUK == TUK_Friend || TUK == TUK_Reference)
14223     Redecl = NotForRedeclaration;
14224 
14225   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14226   /// implemented asks for structural equivalence checking, the returned decl
14227   /// here is passed back to the parser, allowing the tag body to be parsed.
14228   auto createTagFromNewDecl = [&]() -> TagDecl * {
14229     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14230     // If there is an identifier, use the location of the identifier as the
14231     // location of the decl, otherwise use the location of the struct/union
14232     // keyword.
14233     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14234     TagDecl *New = nullptr;
14235 
14236     if (Kind == TTK_Enum) {
14237       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
14238                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
14239       // If this is an undefined enum, bail.
14240       if (TUK != TUK_Definition && !Invalid)
14241         return nullptr;
14242       if (EnumUnderlying) {
14243         EnumDecl *ED = cast<EnumDecl>(New);
14244         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14245           ED->setIntegerTypeSourceInfo(TI);
14246         else
14247           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14248         ED->setPromotionType(ED->getIntegerType());
14249       }
14250     } else { // struct/union
14251       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14252                                nullptr);
14253     }
14254 
14255     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14256       // Add alignment attributes if necessary; these attributes are checked
14257       // when the ASTContext lays out the structure.
14258       //
14259       // It is important for implementing the correct semantics that this
14260       // happen here (in ActOnTag). The #pragma pack stack is
14261       // maintained as a result of parser callbacks which can occur at
14262       // many points during the parsing of a struct declaration (because
14263       // the #pragma tokens are effectively skipped over during the
14264       // parsing of the struct).
14265       if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14266         AddAlignmentAttributesForRecord(RD);
14267         AddMsStructLayoutForRecord(RD);
14268       }
14269     }
14270     New->setLexicalDeclContext(CurContext);
14271     return New;
14272   };
14273 
14274   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
14275   if (Name && SS.isNotEmpty()) {
14276     // We have a nested-name tag ('struct foo::bar').
14277 
14278     // Check for invalid 'foo::'.
14279     if (SS.isInvalid()) {
14280       Name = nullptr;
14281       goto CreateNewDecl;
14282     }
14283 
14284     // If this is a friend or a reference to a class in a dependent
14285     // context, don't try to make a decl for it.
14286     if (TUK == TUK_Friend || TUK == TUK_Reference) {
14287       DC = computeDeclContext(SS, false);
14288       if (!DC) {
14289         IsDependent = true;
14290         return nullptr;
14291       }
14292     } else {
14293       DC = computeDeclContext(SS, true);
14294       if (!DC) {
14295         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14296           << SS.getRange();
14297         return nullptr;
14298       }
14299     }
14300 
14301     if (RequireCompleteDeclContext(SS, DC))
14302       return nullptr;
14303 
14304     SearchDC = DC;
14305     // Look-up name inside 'foo::'.
14306     LookupQualifiedName(Previous, DC);
14307 
14308     if (Previous.isAmbiguous())
14309       return nullptr;
14310 
14311     if (Previous.empty()) {
14312       // Name lookup did not find anything. However, if the
14313       // nested-name-specifier refers to the current instantiation,
14314       // and that current instantiation has any dependent base
14315       // classes, we might find something at instantiation time: treat
14316       // this as a dependent elaborated-type-specifier.
14317       // But this only makes any sense for reference-like lookups.
14318       if (Previous.wasNotFoundInCurrentInstantiation() &&
14319           (TUK == TUK_Reference || TUK == TUK_Friend)) {
14320         IsDependent = true;
14321         return nullptr;
14322       }
14323 
14324       // A tag 'foo::bar' must already exist.
14325       Diag(NameLoc, diag::err_not_tag_in_scope)
14326         << Kind << Name << DC << SS.getRange();
14327       Name = nullptr;
14328       Invalid = true;
14329       goto CreateNewDecl;
14330     }
14331   } else if (Name) {
14332     // C++14 [class.mem]p14:
14333     //   If T is the name of a class, then each of the following shall have a
14334     //   name different from T:
14335     //    -- every member of class T that is itself a type
14336     if (TUK != TUK_Reference && TUK != TUK_Friend &&
14337         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
14338       return nullptr;
14339 
14340     // If this is a named struct, check to see if there was a previous forward
14341     // declaration or definition.
14342     // FIXME: We're looking into outer scopes here, even when we
14343     // shouldn't be. Doing so can result in ambiguities that we
14344     // shouldn't be diagnosing.
14345     LookupName(Previous, S);
14346 
14347     // When declaring or defining a tag, ignore ambiguities introduced
14348     // by types using'ed into this scope.
14349     if (Previous.isAmbiguous() &&
14350         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14351       LookupResult::Filter F = Previous.makeFilter();
14352       while (F.hasNext()) {
14353         NamedDecl *ND = F.next();
14354         if (!ND->getDeclContext()->getRedeclContext()->Equals(
14355                 SearchDC->getRedeclContext()))
14356           F.erase();
14357       }
14358       F.done();
14359     }
14360 
14361     // C++11 [namespace.memdef]p3:
14362     //   If the name in a friend declaration is neither qualified nor
14363     //   a template-id and the declaration is a function or an
14364     //   elaborated-type-specifier, the lookup to determine whether
14365     //   the entity has been previously declared shall not consider
14366     //   any scopes outside the innermost enclosing namespace.
14367     //
14368     // MSVC doesn't implement the above rule for types, so a friend tag
14369     // declaration may be a redeclaration of a type declared in an enclosing
14370     // scope.  They do implement this rule for friend functions.
14371     //
14372     // Does it matter that this should be by scope instead of by
14373     // semantic context?
14374     if (!Previous.empty() && TUK == TUK_Friend) {
14375       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14376       LookupResult::Filter F = Previous.makeFilter();
14377       bool FriendSawTagOutsideEnclosingNamespace = false;
14378       while (F.hasNext()) {
14379         NamedDecl *ND = F.next();
14380         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14381         if (DC->isFileContext() &&
14382             !EnclosingNS->Encloses(ND->getDeclContext())) {
14383           if (getLangOpts().MSVCCompat)
14384             FriendSawTagOutsideEnclosingNamespace = true;
14385           else
14386             F.erase();
14387         }
14388       }
14389       F.done();
14390 
14391       // Diagnose this MSVC extension in the easy case where lookup would have
14392       // unambiguously found something outside the enclosing namespace.
14393       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14394         NamedDecl *ND = Previous.getFoundDecl();
14395         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14396             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14397       }
14398     }
14399 
14400     // Note:  there used to be some attempt at recovery here.
14401     if (Previous.isAmbiguous())
14402       return nullptr;
14403 
14404     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14405       // FIXME: This makes sure that we ignore the contexts associated
14406       // with C structs, unions, and enums when looking for a matching
14407       // tag declaration or definition. See the similar lookup tweak
14408       // in Sema::LookupName; is there a better way to deal with this?
14409       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14410         SearchDC = SearchDC->getParent();
14411     }
14412   }
14413 
14414   if (Previous.isSingleResult() &&
14415       Previous.getFoundDecl()->isTemplateParameter()) {
14416     // Maybe we will complain about the shadowed template parameter.
14417     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
14418     // Just pretend that we didn't see the previous declaration.
14419     Previous.clear();
14420   }
14421 
14422   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14423       DC->Equals(getStdNamespace())) {
14424     if (Name->isStr("bad_alloc")) {
14425       // This is a declaration of or a reference to "std::bad_alloc".
14426       isStdBadAlloc = true;
14427 
14428       // If std::bad_alloc has been implicitly declared (but made invisible to
14429       // name lookup), fill in this implicit declaration as the previous
14430       // declaration, so that the declarations get chained appropriately.
14431       if (Previous.empty() && StdBadAlloc)
14432         Previous.addDecl(getStdBadAlloc());
14433     } else if (Name->isStr("align_val_t")) {
14434       isStdAlignValT = true;
14435       if (Previous.empty() && StdAlignValT)
14436         Previous.addDecl(getStdAlignValT());
14437     }
14438   }
14439 
14440   // If we didn't find a previous declaration, and this is a reference
14441   // (or friend reference), move to the correct scope.  In C++, we
14442   // also need to do a redeclaration lookup there, just in case
14443   // there's a shadow friend decl.
14444   if (Name && Previous.empty() &&
14445       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14446     if (Invalid) goto CreateNewDecl;
14447     assert(SS.isEmpty());
14448 
14449     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14450       // C++ [basic.scope.pdecl]p5:
14451       //   -- for an elaborated-type-specifier of the form
14452       //
14453       //          class-key identifier
14454       //
14455       //      if the elaborated-type-specifier is used in the
14456       //      decl-specifier-seq or parameter-declaration-clause of a
14457       //      function defined in namespace scope, the identifier is
14458       //      declared as a class-name in the namespace that contains
14459       //      the declaration; otherwise, except as a friend
14460       //      declaration, the identifier is declared in the smallest
14461       //      non-class, non-function-prototype scope that contains the
14462       //      declaration.
14463       //
14464       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14465       // C structs and unions.
14466       //
14467       // It is an error in C++ to declare (rather than define) an enum
14468       // type, including via an elaborated type specifier.  We'll
14469       // diagnose that later; for now, declare the enum in the same
14470       // scope as we would have picked for any other tag type.
14471       //
14472       // GNU C also supports this behavior as part of its incomplete
14473       // enum types extension, while GNU C++ does not.
14474       //
14475       // Find the context where we'll be declaring the tag.
14476       // FIXME: We would like to maintain the current DeclContext as the
14477       // lexical context,
14478       SearchDC = getTagInjectionContext(SearchDC);
14479 
14480       // Find the scope where we'll be declaring the tag.
14481       S = getTagInjectionScope(S, getLangOpts());
14482     } else {
14483       assert(TUK == TUK_Friend);
14484       // C++ [namespace.memdef]p3:
14485       //   If a friend declaration in a non-local class first declares a
14486       //   class or function, the friend class or function is a member of
14487       //   the innermost enclosing namespace.
14488       SearchDC = SearchDC->getEnclosingNamespaceContext();
14489     }
14490 
14491     // In C++, we need to do a redeclaration lookup to properly
14492     // diagnose some problems.
14493     // FIXME: redeclaration lookup is also used (with and without C++) to find a
14494     // hidden declaration so that we don't get ambiguity errors when using a
14495     // type declared by an elaborated-type-specifier.  In C that is not correct
14496     // and we should instead merge compatible types found by lookup.
14497     if (getLangOpts().CPlusPlus) {
14498       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14499       LookupQualifiedName(Previous, SearchDC);
14500     } else {
14501       Previous.setRedeclarationKind(forRedeclarationInCurContext());
14502       LookupName(Previous, S);
14503     }
14504   }
14505 
14506   // If we have a known previous declaration to use, then use it.
14507   if (Previous.empty() && SkipBody && SkipBody->Previous)
14508     Previous.addDecl(SkipBody->Previous);
14509 
14510   if (!Previous.empty()) {
14511     NamedDecl *PrevDecl = Previous.getFoundDecl();
14512     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14513 
14514     // It's okay to have a tag decl in the same scope as a typedef
14515     // which hides a tag decl in the same scope.  Finding this
14516     // insanity with a redeclaration lookup can only actually happen
14517     // in C++.
14518     //
14519     // This is also okay for elaborated-type-specifiers, which is
14520     // technically forbidden by the current standard but which is
14521     // okay according to the likely resolution of an open issue;
14522     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14523     if (getLangOpts().CPlusPlus) {
14524       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14525         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14526           TagDecl *Tag = TT->getDecl();
14527           if (Tag->getDeclName() == Name &&
14528               Tag->getDeclContext()->getRedeclContext()
14529                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
14530             PrevDecl = Tag;
14531             Previous.clear();
14532             Previous.addDecl(Tag);
14533             Previous.resolveKind();
14534           }
14535         }
14536       }
14537     }
14538 
14539     // If this is a redeclaration of a using shadow declaration, it must
14540     // declare a tag in the same context. In MSVC mode, we allow a
14541     // redefinition if either context is within the other.
14542     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14543       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14544       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14545           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14546           !(OldTag && isAcceptableTagRedeclContext(
14547                           *this, OldTag->getDeclContext(), SearchDC))) {
14548         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14549         Diag(Shadow->getTargetDecl()->getLocation(),
14550              diag::note_using_decl_target);
14551         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14552             << 0;
14553         // Recover by ignoring the old declaration.
14554         Previous.clear();
14555         goto CreateNewDecl;
14556       }
14557     }
14558 
14559     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14560       // If this is a use of a previous tag, or if the tag is already declared
14561       // in the same scope (so that the definition/declaration completes or
14562       // rementions the tag), reuse the decl.
14563       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14564           isDeclInScope(DirectPrevDecl, SearchDC, S,
14565                         SS.isNotEmpty() || isMemberSpecialization)) {
14566         // Make sure that this wasn't declared as an enum and now used as a
14567         // struct or something similar.
14568         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14569                                           TUK == TUK_Definition, KWLoc,
14570                                           Name)) {
14571           bool SafeToContinue
14572             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14573                Kind != TTK_Enum);
14574           if (SafeToContinue)
14575             Diag(KWLoc, diag::err_use_with_wrong_tag)
14576               << Name
14577               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14578                                               PrevTagDecl->getKindName());
14579           else
14580             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14581           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14582 
14583           if (SafeToContinue)
14584             Kind = PrevTagDecl->getTagKind();
14585           else {
14586             // Recover by making this an anonymous redefinition.
14587             Name = nullptr;
14588             Previous.clear();
14589             Invalid = true;
14590           }
14591         }
14592 
14593         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14594           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14595 
14596           // If this is an elaborated-type-specifier for a scoped enumeration,
14597           // the 'class' keyword is not necessary and not permitted.
14598           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14599             if (ScopedEnum)
14600               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14601                 << PrevEnum->isScoped()
14602                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14603             return PrevTagDecl;
14604           }
14605 
14606           QualType EnumUnderlyingTy;
14607           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14608             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14609           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14610             EnumUnderlyingTy = QualType(T, 0);
14611 
14612           // All conflicts with previous declarations are recovered by
14613           // returning the previous declaration, unless this is a definition,
14614           // in which case we want the caller to bail out.
14615           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14616                                      ScopedEnum, EnumUnderlyingTy,
14617                                      IsFixed, PrevEnum))
14618             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14619         }
14620 
14621         // C++11 [class.mem]p1:
14622         //   A member shall not be declared twice in the member-specification,
14623         //   except that a nested class or member class template can be declared
14624         //   and then later defined.
14625         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14626             S->isDeclScope(PrevDecl)) {
14627           Diag(NameLoc, diag::ext_member_redeclared);
14628           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14629         }
14630 
14631         if (!Invalid) {
14632           // If this is a use, just return the declaration we found, unless
14633           // we have attributes.
14634           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14635             if (!Attrs.empty()) {
14636               // FIXME: Diagnose these attributes. For now, we create a new
14637               // declaration to hold them.
14638             } else if (TUK == TUK_Reference &&
14639                        (PrevTagDecl->getFriendObjectKind() ==
14640                             Decl::FOK_Undeclared ||
14641                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14642                        SS.isEmpty()) {
14643               // This declaration is a reference to an existing entity, but
14644               // has different visibility from that entity: it either makes
14645               // a friend visible or it makes a type visible in a new module.
14646               // In either case, create a new declaration. We only do this if
14647               // the declaration would have meant the same thing if no prior
14648               // declaration were found, that is, if it was found in the same
14649               // scope where we would have injected a declaration.
14650               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14651                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14652                 return PrevTagDecl;
14653               // This is in the injected scope, create a new declaration in
14654               // that scope.
14655               S = getTagInjectionScope(S, getLangOpts());
14656             } else {
14657               return PrevTagDecl;
14658             }
14659           }
14660 
14661           // Diagnose attempts to redefine a tag.
14662           if (TUK == TUK_Definition) {
14663             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14664               // If we're defining a specialization and the previous definition
14665               // is from an implicit instantiation, don't emit an error
14666               // here; we'll catch this in the general case below.
14667               bool IsExplicitSpecializationAfterInstantiation = false;
14668               if (isMemberSpecialization) {
14669                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14670                   IsExplicitSpecializationAfterInstantiation =
14671                     RD->getTemplateSpecializationKind() !=
14672                     TSK_ExplicitSpecialization;
14673                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14674                   IsExplicitSpecializationAfterInstantiation =
14675                     ED->getTemplateSpecializationKind() !=
14676                     TSK_ExplicitSpecialization;
14677               }
14678 
14679               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14680               // not keep more that one definition around (merge them). However,
14681               // ensure the decl passes the structural compatibility check in
14682               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14683               NamedDecl *Hidden = nullptr;
14684               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14685                 // There is a definition of this tag, but it is not visible. We
14686                 // explicitly make use of C++'s one definition rule here, and
14687                 // assume that this definition is identical to the hidden one
14688                 // we already have. Make the existing definition visible and
14689                 // use it in place of this one.
14690                 if (!getLangOpts().CPlusPlus) {
14691                   // Postpone making the old definition visible until after we
14692                   // complete parsing the new one and do the structural
14693                   // comparison.
14694                   SkipBody->CheckSameAsPrevious = true;
14695                   SkipBody->New = createTagFromNewDecl();
14696                   SkipBody->Previous = Def;
14697                   return Def;
14698                 } else {
14699                   SkipBody->ShouldSkip = true;
14700                   SkipBody->Previous = Def;
14701                   makeMergedDefinitionVisible(Hidden);
14702                   // Carry on and handle it like a normal definition. We'll
14703                   // skip starting the definitiion later.
14704                 }
14705               } else if (!IsExplicitSpecializationAfterInstantiation) {
14706                 // A redeclaration in function prototype scope in C isn't
14707                 // visible elsewhere, so merely issue a warning.
14708                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14709                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14710                 else
14711                   Diag(NameLoc, diag::err_redefinition) << Name;
14712                 notePreviousDefinition(Def,
14713                                        NameLoc.isValid() ? NameLoc : KWLoc);
14714                 // If this is a redefinition, recover by making this
14715                 // struct be anonymous, which will make any later
14716                 // references get the previous definition.
14717                 Name = nullptr;
14718                 Previous.clear();
14719                 Invalid = true;
14720               }
14721             } else {
14722               // If the type is currently being defined, complain
14723               // about a nested redefinition.
14724               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14725               if (TD->isBeingDefined()) {
14726                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14727                 Diag(PrevTagDecl->getLocation(),
14728                      diag::note_previous_definition);
14729                 Name = nullptr;
14730                 Previous.clear();
14731                 Invalid = true;
14732               }
14733             }
14734 
14735             // Okay, this is definition of a previously declared or referenced
14736             // tag. We're going to create a new Decl for it.
14737           }
14738 
14739           // Okay, we're going to make a redeclaration.  If this is some kind
14740           // of reference, make sure we build the redeclaration in the same DC
14741           // as the original, and ignore the current access specifier.
14742           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14743             SearchDC = PrevTagDecl->getDeclContext();
14744             AS = AS_none;
14745           }
14746         }
14747         // If we get here we have (another) forward declaration or we
14748         // have a definition.  Just create a new decl.
14749 
14750       } else {
14751         // If we get here, this is a definition of a new tag type in a nested
14752         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14753         // new decl/type.  We set PrevDecl to NULL so that the entities
14754         // have distinct types.
14755         Previous.clear();
14756       }
14757       // If we get here, we're going to create a new Decl. If PrevDecl
14758       // is non-NULL, it's a definition of the tag declared by
14759       // PrevDecl. If it's NULL, we have a new definition.
14760 
14761     // Otherwise, PrevDecl is not a tag, but was found with tag
14762     // lookup.  This is only actually possible in C++, where a few
14763     // things like templates still live in the tag namespace.
14764     } else {
14765       // Use a better diagnostic if an elaborated-type-specifier
14766       // found the wrong kind of type on the first
14767       // (non-redeclaration) lookup.
14768       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14769           !Previous.isForRedeclaration()) {
14770         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14771         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14772                                                        << Kind;
14773         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14774         Invalid = true;
14775 
14776       // Otherwise, only diagnose if the declaration is in scope.
14777       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14778                                 SS.isNotEmpty() || isMemberSpecialization)) {
14779         // do nothing
14780 
14781       // Diagnose implicit declarations introduced by elaborated types.
14782       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14783         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14784         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14785         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14786         Invalid = true;
14787 
14788       // Otherwise it's a declaration.  Call out a particularly common
14789       // case here.
14790       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14791         unsigned Kind = 0;
14792         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14793         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14794           << Name << Kind << TND->getUnderlyingType();
14795         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14796         Invalid = true;
14797 
14798       // Otherwise, diagnose.
14799       } else {
14800         // The tag name clashes with something else in the target scope,
14801         // issue an error and recover by making this tag be anonymous.
14802         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14803         notePreviousDefinition(PrevDecl, NameLoc);
14804         Name = nullptr;
14805         Invalid = true;
14806       }
14807 
14808       // The existing declaration isn't relevant to us; we're in a
14809       // new scope, so clear out the previous declaration.
14810       Previous.clear();
14811     }
14812   }
14813 
14814 CreateNewDecl:
14815 
14816   TagDecl *PrevDecl = nullptr;
14817   if (Previous.isSingleResult())
14818     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14819 
14820   // If there is an identifier, use the location of the identifier as the
14821   // location of the decl, otherwise use the location of the struct/union
14822   // keyword.
14823   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14824 
14825   // Otherwise, create a new declaration. If there is a previous
14826   // declaration of the same entity, the two will be linked via
14827   // PrevDecl.
14828   TagDecl *New;
14829 
14830   if (Kind == TTK_Enum) {
14831     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14832     // enum X { A, B, C } D;    D should chain to X.
14833     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14834                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14835                            ScopedEnumUsesClassTag, IsFixed);
14836 
14837     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14838       StdAlignValT = cast<EnumDecl>(New);
14839 
14840     // If this is an undefined enum, warn.
14841     if (TUK != TUK_Definition && !Invalid) {
14842       TagDecl *Def;
14843       if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14844         // C++0x: 7.2p2: opaque-enum-declaration.
14845         // Conflicts are diagnosed above. Do nothing.
14846       }
14847       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14848         Diag(Loc, diag::ext_forward_ref_enum_def)
14849           << New;
14850         Diag(Def->getLocation(), diag::note_previous_definition);
14851       } else {
14852         unsigned DiagID = diag::ext_forward_ref_enum;
14853         if (getLangOpts().MSVCCompat)
14854           DiagID = diag::ext_ms_forward_ref_enum;
14855         else if (getLangOpts().CPlusPlus)
14856           DiagID = diag::err_forward_ref_enum;
14857         Diag(Loc, DiagID);
14858       }
14859     }
14860 
14861     if (EnumUnderlying) {
14862       EnumDecl *ED = cast<EnumDecl>(New);
14863       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14864         ED->setIntegerTypeSourceInfo(TI);
14865       else
14866         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14867       ED->setPromotionType(ED->getIntegerType());
14868       assert(ED->isComplete() && "enum with type should be complete");
14869     }
14870   } else {
14871     // struct/union/class
14872 
14873     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14874     // struct X { int A; } D;    D should chain to X.
14875     if (getLangOpts().CPlusPlus) {
14876       // FIXME: Look for a way to use RecordDecl for simple structs.
14877       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14878                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14879 
14880       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14881         StdBadAlloc = cast<CXXRecordDecl>(New);
14882     } else
14883       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14884                                cast_or_null<RecordDecl>(PrevDecl));
14885   }
14886 
14887   // C++11 [dcl.type]p3:
14888   //   A type-specifier-seq shall not define a class or enumeration [...].
14889   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14890       TUK == TUK_Definition) {
14891     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14892       << Context.getTagDeclType(New);
14893     Invalid = true;
14894   }
14895 
14896   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14897       DC->getDeclKind() == Decl::Enum) {
14898     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14899       << Context.getTagDeclType(New);
14900     Invalid = true;
14901   }
14902 
14903   // Maybe add qualifier info.
14904   if (SS.isNotEmpty()) {
14905     if (SS.isSet()) {
14906       // If this is either a declaration or a definition, check the
14907       // nested-name-specifier against the current context.
14908       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14909           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14910                                        isMemberSpecialization))
14911         Invalid = true;
14912 
14913       New->setQualifierInfo(SS.getWithLocInContext(Context));
14914       if (TemplateParameterLists.size() > 0) {
14915         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14916       }
14917     }
14918     else
14919       Invalid = true;
14920   }
14921 
14922   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14923     // Add alignment attributes if necessary; these attributes are checked when
14924     // the ASTContext lays out the structure.
14925     //
14926     // It is important for implementing the correct semantics that this
14927     // happen here (in ActOnTag). The #pragma pack stack is
14928     // maintained as a result of parser callbacks which can occur at
14929     // many points during the parsing of a struct declaration (because
14930     // the #pragma tokens are effectively skipped over during the
14931     // parsing of the struct).
14932     if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14933       AddAlignmentAttributesForRecord(RD);
14934       AddMsStructLayoutForRecord(RD);
14935     }
14936   }
14937 
14938   if (ModulePrivateLoc.isValid()) {
14939     if (isMemberSpecialization)
14940       Diag(New->getLocation(), diag::err_module_private_specialization)
14941         << 2
14942         << FixItHint::CreateRemoval(ModulePrivateLoc);
14943     // __module_private__ does not apply to local classes. However, we only
14944     // diagnose this as an error when the declaration specifiers are
14945     // freestanding. Here, we just ignore the __module_private__.
14946     else if (!SearchDC->isFunctionOrMethod())
14947       New->setModulePrivate();
14948   }
14949 
14950   // If this is a specialization of a member class (of a class template),
14951   // check the specialization.
14952   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14953     Invalid = true;
14954 
14955   // If we're declaring or defining a tag in function prototype scope in C,
14956   // note that this type can only be used within the function and add it to
14957   // the list of decls to inject into the function definition scope.
14958   if ((Name || Kind == TTK_Enum) &&
14959       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14960     if (getLangOpts().CPlusPlus) {
14961       // C++ [dcl.fct]p6:
14962       //   Types shall not be defined in return or parameter types.
14963       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14964         Diag(Loc, diag::err_type_defined_in_param_type)
14965             << Name;
14966         Invalid = true;
14967       }
14968     } else if (!PrevDecl) {
14969       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14970     }
14971   }
14972 
14973   if (Invalid)
14974     New->setInvalidDecl();
14975 
14976   // Set the lexical context. If the tag has a C++ scope specifier, the
14977   // lexical context will be different from the semantic context.
14978   New->setLexicalDeclContext(CurContext);
14979 
14980   // Mark this as a friend decl if applicable.
14981   // In Microsoft mode, a friend declaration also acts as a forward
14982   // declaration so we always pass true to setObjectOfFriendDecl to make
14983   // the tag name visible.
14984   if (TUK == TUK_Friend)
14985     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14986 
14987   // Set the access specifier.
14988   if (!Invalid && SearchDC->isRecord())
14989     SetMemberAccessSpecifier(New, PrevDecl, AS);
14990 
14991   if (PrevDecl)
14992     CheckRedeclarationModuleOwnership(New, PrevDecl);
14993 
14994   if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14995     New->startDefinition();
14996 
14997   ProcessDeclAttributeList(S, New, Attrs);
14998   AddPragmaAttributes(S, New);
14999 
15000   // If this has an identifier, add it to the scope stack.
15001   if (TUK == TUK_Friend) {
15002     // We might be replacing an existing declaration in the lookup tables;
15003     // if so, borrow its access specifier.
15004     if (PrevDecl)
15005       New->setAccess(PrevDecl->getAccess());
15006 
15007     DeclContext *DC = New->getDeclContext()->getRedeclContext();
15008     DC->makeDeclVisibleInContext(New);
15009     if (Name) // can be null along some error paths
15010       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
15011         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
15012   } else if (Name) {
15013     S = getNonFieldDeclScope(S);
15014     PushOnScopeChains(New, S, true);
15015   } else {
15016     CurContext->addDecl(New);
15017   }
15018 
15019   // If this is the C FILE type, notify the AST context.
15020   if (IdentifierInfo *II = New->getIdentifier())
15021     if (!New->isInvalidDecl() &&
15022         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
15023         II->isStr("FILE"))
15024       Context.setFILEDecl(New);
15025 
15026   if (PrevDecl)
15027     mergeDeclAttributes(New, PrevDecl);
15028 
15029   // If there's a #pragma GCC visibility in scope, set the visibility of this
15030   // record.
15031   AddPushedVisibilityAttribute(New);
15032 
15033   if (isMemberSpecialization && !New->isInvalidDecl())
15034     CompleteMemberSpecialization(New, Previous);
15035 
15036   OwnedDecl = true;
15037   // In C++, don't return an invalid declaration. We can't recover well from
15038   // the cases where we make the type anonymous.
15039   if (Invalid && getLangOpts().CPlusPlus) {
15040     if (New->isBeingDefined())
15041       if (auto RD = dyn_cast<RecordDecl>(New))
15042         RD->completeDefinition();
15043     return nullptr;
15044   } else if (SkipBody && SkipBody->ShouldSkip) {
15045     return SkipBody->Previous;
15046   } else {
15047     return New;
15048   }
15049 }
15050 
15051 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
15052   AdjustDeclIfTemplate(TagD);
15053   TagDecl *Tag = cast<TagDecl>(TagD);
15054 
15055   // Enter the tag context.
15056   PushDeclContext(S, Tag);
15057 
15058   ActOnDocumentableDecl(TagD);
15059 
15060   // If there's a #pragma GCC visibility in scope, set the visibility of this
15061   // record.
15062   AddPushedVisibilityAttribute(Tag);
15063 }
15064 
15065 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
15066                                     SkipBodyInfo &SkipBody) {
15067   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
15068     return false;
15069 
15070   // Make the previous decl visible.
15071   makeMergedDefinitionVisible(SkipBody.Previous);
15072   return true;
15073 }
15074 
15075 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15076   assert(isa<ObjCContainerDecl>(IDecl) &&
15077          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15078   DeclContext *OCD = cast<DeclContext>(IDecl);
15079   assert(getContainingDC(OCD) == CurContext &&
15080       "The next DeclContext should be lexically contained in the current one.");
15081   CurContext = OCD;
15082   return IDecl;
15083 }
15084 
15085 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
15086                                            SourceLocation FinalLoc,
15087                                            bool IsFinalSpelledSealed,
15088                                            SourceLocation LBraceLoc) {
15089   AdjustDeclIfTemplate(TagD);
15090   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15091 
15092   FieldCollector->StartClass();
15093 
15094   if (!Record->getIdentifier())
15095     return;
15096 
15097   if (FinalLoc.isValid())
15098     Record->addAttr(new (Context)
15099                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15100 
15101   // C++ [class]p2:
15102   //   [...] The class-name is also inserted into the scope of the
15103   //   class itself; this is known as the injected-class-name. For
15104   //   purposes of access checking, the injected-class-name is treated
15105   //   as if it were a public member name.
15106   CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15107       Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
15108       Record->getLocation(), Record->getIdentifier(),
15109       /*PrevDecl=*/nullptr,
15110       /*DelayTypeCreation=*/true);
15111   Context.getTypeDeclType(InjectedClassName, Record);
15112   InjectedClassName->setImplicit();
15113   InjectedClassName->setAccess(AS_public);
15114   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15115       InjectedClassName->setDescribedClassTemplate(Template);
15116   PushOnScopeChains(InjectedClassName, S);
15117   assert(InjectedClassName->isInjectedClassName() &&
15118          "Broken injected-class-name");
15119 }
15120 
15121 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
15122                                     SourceRange BraceRange) {
15123   AdjustDeclIfTemplate(TagD);
15124   TagDecl *Tag = cast<TagDecl>(TagD);
15125   Tag->setBraceRange(BraceRange);
15126 
15127   // Make sure we "complete" the definition even it is invalid.
15128   if (Tag->isBeingDefined()) {
15129     assert(Tag->isInvalidDecl() && "We should already have completed it");
15130     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15131       RD->completeDefinition();
15132   }
15133 
15134   if (isa<CXXRecordDecl>(Tag)) {
15135     FieldCollector->FinishClass();
15136   }
15137 
15138   // Exit this scope of this tag's definition.
15139   PopDeclContext();
15140 
15141   if (getCurLexicalContext()->isObjCContainer() &&
15142       Tag->getDeclContext()->isFileContext())
15143     Tag->setTopLevelDeclInObjCContainer();
15144 
15145   // Notify the consumer that we've defined a tag.
15146   if (!Tag->isInvalidDecl())
15147     Consumer.HandleTagDeclDefinition(Tag);
15148 }
15149 
15150 void Sema::ActOnObjCContainerFinishDefinition() {
15151   // Exit this scope of this interface definition.
15152   PopDeclContext();
15153 }
15154 
15155 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15156   assert(DC == CurContext && "Mismatch of container contexts");
15157   OriginalLexicalContext = DC;
15158   ActOnObjCContainerFinishDefinition();
15159 }
15160 
15161 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15162   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15163   OriginalLexicalContext = nullptr;
15164 }
15165 
15166 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
15167   AdjustDeclIfTemplate(TagD);
15168   TagDecl *Tag = cast<TagDecl>(TagD);
15169   Tag->setInvalidDecl();
15170 
15171   // Make sure we "complete" the definition even it is invalid.
15172   if (Tag->isBeingDefined()) {
15173     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15174       RD->completeDefinition();
15175   }
15176 
15177   // We're undoing ActOnTagStartDefinition here, not
15178   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15179   // the FieldCollector.
15180 
15181   PopDeclContext();
15182 }
15183 
15184 // Note that FieldName may be null for anonymous bitfields.
15185 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15186                                 IdentifierInfo *FieldName,
15187                                 QualType FieldTy, bool IsMsStruct,
15188                                 Expr *BitWidth, bool *ZeroWidth) {
15189   // Default to true; that shouldn't confuse checks for emptiness
15190   if (ZeroWidth)
15191     *ZeroWidth = true;
15192 
15193   // C99 6.7.2.1p4 - verify the field type.
15194   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15195   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15196     // Handle incomplete types with specific error.
15197     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15198       return ExprError();
15199     if (FieldName)
15200       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15201         << FieldName << FieldTy << BitWidth->getSourceRange();
15202     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15203       << FieldTy << BitWidth->getSourceRange();
15204   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15205                                              UPPC_BitFieldWidth))
15206     return ExprError();
15207 
15208   // If the bit-width is type- or value-dependent, don't try to check
15209   // it now.
15210   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15211     return BitWidth;
15212 
15213   llvm::APSInt Value;
15214   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15215   if (ICE.isInvalid())
15216     return ICE;
15217   BitWidth = ICE.get();
15218 
15219   if (Value != 0 && ZeroWidth)
15220     *ZeroWidth = false;
15221 
15222   // Zero-width bitfield is ok for anonymous field.
15223   if (Value == 0 && FieldName)
15224     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15225 
15226   if (Value.isSigned() && Value.isNegative()) {
15227     if (FieldName)
15228       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15229                << FieldName << Value.toString(10);
15230     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15231       << Value.toString(10);
15232   }
15233 
15234   if (!FieldTy->isDependentType()) {
15235     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15236     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15237     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15238 
15239     // Over-wide bitfields are an error in C or when using the MSVC bitfield
15240     // ABI.
15241     bool CStdConstraintViolation =
15242         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15243     bool MSBitfieldViolation =
15244         Value.ugt(TypeStorageSize) &&
15245         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15246     if (CStdConstraintViolation || MSBitfieldViolation) {
15247       unsigned DiagWidth =
15248           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15249       if (FieldName)
15250         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15251                << FieldName << (unsigned)Value.getZExtValue()
15252                << !CStdConstraintViolation << DiagWidth;
15253 
15254       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15255              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15256              << DiagWidth;
15257     }
15258 
15259     // Warn on types where the user might conceivably expect to get all
15260     // specified bits as value bits: that's all integral types other than
15261     // 'bool'.
15262     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15263       if (FieldName)
15264         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15265             << FieldName << (unsigned)Value.getZExtValue()
15266             << (unsigned)TypeWidth;
15267       else
15268         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15269             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15270     }
15271   }
15272 
15273   return BitWidth;
15274 }
15275 
15276 /// ActOnField - Each field of a C struct/union is passed into this in order
15277 /// to create a FieldDecl object for it.
15278 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
15279                        Declarator &D, Expr *BitfieldWidth) {
15280   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15281                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
15282                                /*InitStyle=*/ICIS_NoInit, AS_public);
15283   return Res;
15284 }
15285 
15286 /// HandleField - Analyze a field of a C struct or a C++ data member.
15287 ///
15288 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
15289                              SourceLocation DeclStart,
15290                              Declarator &D, Expr *BitWidth,
15291                              InClassInitStyle InitStyle,
15292                              AccessSpecifier AS) {
15293   if (D.isDecompositionDeclarator()) {
15294     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15295     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15296       << Decomp.getSourceRange();
15297     return nullptr;
15298   }
15299 
15300   IdentifierInfo *II = D.getIdentifier();
15301   SourceLocation Loc = DeclStart;
15302   if (II) Loc = D.getIdentifierLoc();
15303 
15304   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15305   QualType T = TInfo->getType();
15306   if (getLangOpts().CPlusPlus) {
15307     CheckExtraCXXDefaultArguments(D);
15308 
15309     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15310                                         UPPC_DataMemberType)) {
15311       D.setInvalidType();
15312       T = Context.IntTy;
15313       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
15314     }
15315   }
15316 
15317   DiagnoseFunctionSpecifiers(D.getDeclSpec());
15318 
15319   if (D.getDeclSpec().isInlineSpecified())
15320     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15321         << getLangOpts().CPlusPlus17;
15322   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15323     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15324          diag::err_invalid_thread)
15325       << DeclSpec::getSpecifierName(TSCS);
15326 
15327   // Check to see if this name was declared as a member previously
15328   NamedDecl *PrevDecl = nullptr;
15329   LookupResult Previous(*this, II, Loc, LookupMemberName,
15330                         ForVisibleRedeclaration);
15331   LookupName(Previous, S);
15332   switch (Previous.getResultKind()) {
15333     case LookupResult::Found:
15334     case LookupResult::FoundUnresolvedValue:
15335       PrevDecl = Previous.getAsSingle<NamedDecl>();
15336       break;
15337 
15338     case LookupResult::FoundOverloaded:
15339       PrevDecl = Previous.getRepresentativeDecl();
15340       break;
15341 
15342     case LookupResult::NotFound:
15343     case LookupResult::NotFoundInCurrentInstantiation:
15344     case LookupResult::Ambiguous:
15345       break;
15346   }
15347   Previous.suppressDiagnostics();
15348 
15349   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15350     // Maybe we will complain about the shadowed template parameter.
15351     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15352     // Just pretend that we didn't see the previous declaration.
15353     PrevDecl = nullptr;
15354   }
15355 
15356   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15357     PrevDecl = nullptr;
15358 
15359   bool Mutable
15360     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15361   SourceLocation TSSL = D.getBeginLoc();
15362   FieldDecl *NewFD
15363     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
15364                      TSSL, AS, PrevDecl, &D);
15365 
15366   if (NewFD->isInvalidDecl())
15367     Record->setInvalidDecl();
15368 
15369   if (D.getDeclSpec().isModulePrivateSpecified())
15370     NewFD->setModulePrivate();
15371 
15372   if (NewFD->isInvalidDecl() && PrevDecl) {
15373     // Don't introduce NewFD into scope; there's already something
15374     // with the same name in the same scope.
15375   } else if (II) {
15376     PushOnScopeChains(NewFD, S);
15377   } else
15378     Record->addDecl(NewFD);
15379 
15380   return NewFD;
15381 }
15382 
15383 /// Build a new FieldDecl and check its well-formedness.
15384 ///
15385 /// This routine builds a new FieldDecl given the fields name, type,
15386 /// record, etc. \p PrevDecl should refer to any previous declaration
15387 /// with the same name and in the same scope as the field to be
15388 /// created.
15389 ///
15390 /// \returns a new FieldDecl.
15391 ///
15392 /// \todo The Declarator argument is a hack. It will be removed once
15393 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
15394                                 TypeSourceInfo *TInfo,
15395                                 RecordDecl *Record, SourceLocation Loc,
15396                                 bool Mutable, Expr *BitWidth,
15397                                 InClassInitStyle InitStyle,
15398                                 SourceLocation TSSL,
15399                                 AccessSpecifier AS, NamedDecl *PrevDecl,
15400                                 Declarator *D) {
15401   IdentifierInfo *II = Name.getAsIdentifierInfo();
15402   bool InvalidDecl = false;
15403   if (D) InvalidDecl = D->isInvalidType();
15404 
15405   // If we receive a broken type, recover by assuming 'int' and
15406   // marking this declaration as invalid.
15407   if (T.isNull()) {
15408     InvalidDecl = true;
15409     T = Context.IntTy;
15410   }
15411 
15412   QualType EltTy = Context.getBaseElementType(T);
15413   if (!EltTy->isDependentType()) {
15414     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15415       // Fields of incomplete type force their record to be invalid.
15416       Record->setInvalidDecl();
15417       InvalidDecl = true;
15418     } else {
15419       NamedDecl *Def;
15420       EltTy->isIncompleteType(&Def);
15421       if (Def && Def->isInvalidDecl()) {
15422         Record->setInvalidDecl();
15423         InvalidDecl = true;
15424       }
15425     }
15426   }
15427 
15428   // TR 18037 does not allow fields to be declared with address space
15429   if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15430       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15431     Diag(Loc, diag::err_field_with_address_space);
15432     Record->setInvalidDecl();
15433     InvalidDecl = true;
15434   }
15435 
15436   if (LangOpts.OpenCL) {
15437     // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15438     // used as structure or union field: image, sampler, event or block types.
15439     if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15440         T->isBlockPointerType()) {
15441       Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15442       Record->setInvalidDecl();
15443       InvalidDecl = true;
15444     }
15445     // OpenCL v1.2 s6.9.c: bitfields are not supported.
15446     if (BitWidth) {
15447       Diag(Loc, diag::err_opencl_bitfields);
15448       InvalidDecl = true;
15449     }
15450   }
15451 
15452   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15453   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15454       T.hasQualifiers()) {
15455     InvalidDecl = true;
15456     Diag(Loc, diag::err_anon_bitfield_qualifiers);
15457   }
15458 
15459   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15460   // than a variably modified type.
15461   if (!InvalidDecl && T->isVariablyModifiedType()) {
15462     bool SizeIsNegative;
15463     llvm::APSInt Oversized;
15464 
15465     TypeSourceInfo *FixedTInfo =
15466       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15467                                                     SizeIsNegative,
15468                                                     Oversized);
15469     if (FixedTInfo) {
15470       Diag(Loc, diag::warn_illegal_constant_array_size);
15471       TInfo = FixedTInfo;
15472       T = FixedTInfo->getType();
15473     } else {
15474       if (SizeIsNegative)
15475         Diag(Loc, diag::err_typecheck_negative_array_size);
15476       else if (Oversized.getBoolValue())
15477         Diag(Loc, diag::err_array_too_large)
15478           << Oversized.toString(10);
15479       else
15480         Diag(Loc, diag::err_typecheck_field_variable_size);
15481       InvalidDecl = true;
15482     }
15483   }
15484 
15485   // Fields can not have abstract class types
15486   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15487                                              diag::err_abstract_type_in_decl,
15488                                              AbstractFieldType))
15489     InvalidDecl = true;
15490 
15491   bool ZeroWidth = false;
15492   if (InvalidDecl)
15493     BitWidth = nullptr;
15494   // If this is declared as a bit-field, check the bit-field.
15495   if (BitWidth) {
15496     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
15497                               &ZeroWidth).get();
15498     if (!BitWidth) {
15499       InvalidDecl = true;
15500       BitWidth = nullptr;
15501       ZeroWidth = false;
15502     }
15503   }
15504 
15505   // Check that 'mutable' is consistent with the type of the declaration.
15506   if (!InvalidDecl && Mutable) {
15507     unsigned DiagID = 0;
15508     if (T->isReferenceType())
15509       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15510                                         : diag::err_mutable_reference;
15511     else if (T.isConstQualified())
15512       DiagID = diag::err_mutable_const;
15513 
15514     if (DiagID) {
15515       SourceLocation ErrLoc = Loc;
15516       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15517         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15518       Diag(ErrLoc, DiagID);
15519       if (DiagID != diag::ext_mutable_reference) {
15520         Mutable = false;
15521         InvalidDecl = true;
15522       }
15523     }
15524   }
15525 
15526   // C++11 [class.union]p8 (DR1460):
15527   //   At most one variant member of a union may have a
15528   //   brace-or-equal-initializer.
15529   if (InitStyle != ICIS_NoInit)
15530     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15531 
15532   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
15533                                        BitWidth, Mutable, InitStyle);
15534   if (InvalidDecl)
15535     NewFD->setInvalidDecl();
15536 
15537   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15538     Diag(Loc, diag::err_duplicate_member) << II;
15539     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15540     NewFD->setInvalidDecl();
15541   }
15542 
15543   if (!InvalidDecl && getLangOpts().CPlusPlus) {
15544     if (Record->isUnion()) {
15545       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15546         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
15547         if (RDecl->getDefinition()) {
15548           // C++ [class.union]p1: An object of a class with a non-trivial
15549           // constructor, a non-trivial copy constructor, a non-trivial
15550           // destructor, or a non-trivial copy assignment operator
15551           // cannot be a member of a union, nor can an array of such
15552           // objects.
15553           if (CheckNontrivialField(NewFD))
15554             NewFD->setInvalidDecl();
15555         }
15556       }
15557 
15558       // C++ [class.union]p1: If a union contains a member of reference type,
15559       // the program is ill-formed, except when compiling with MSVC extensions
15560       // enabled.
15561       if (EltTy->isReferenceType()) {
15562         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15563                                     diag::ext_union_member_of_reference_type :
15564                                     diag::err_union_member_of_reference_type)
15565           << NewFD->getDeclName() << EltTy;
15566         if (!getLangOpts().MicrosoftExt)
15567           NewFD->setInvalidDecl();
15568       }
15569     }
15570   }
15571 
15572   // FIXME: We need to pass in the attributes given an AST
15573   // representation, not a parser representation.
15574   if (D) {
15575     // FIXME: The current scope is almost... but not entirely... correct here.
15576     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15577 
15578     if (NewFD->hasAttrs())
15579       CheckAlignasUnderalignment(NewFD);
15580   }
15581 
15582   // In auto-retain/release, infer strong retension for fields of
15583   // retainable type.
15584   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15585     NewFD->setInvalidDecl();
15586 
15587   if (T.isObjCGCWeak())
15588     Diag(Loc, diag::warn_attribute_weak_on_field);
15589 
15590   NewFD->setAccess(AS);
15591   return NewFD;
15592 }
15593 
15594 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15595   assert(FD);
15596   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15597 
15598   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15599     return false;
15600 
15601   QualType EltTy = Context.getBaseElementType(FD->getType());
15602   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15603     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15604     if (RDecl->getDefinition()) {
15605       // We check for copy constructors before constructors
15606       // because otherwise we'll never get complaints about
15607       // copy constructors.
15608 
15609       CXXSpecialMember member = CXXInvalid;
15610       // We're required to check for any non-trivial constructors. Since the
15611       // implicit default constructor is suppressed if there are any
15612       // user-declared constructors, we just need to check that there is a
15613       // trivial default constructor and a trivial copy constructor. (We don't
15614       // worry about move constructors here, since this is a C++98 check.)
15615       if (RDecl->hasNonTrivialCopyConstructor())
15616         member = CXXCopyConstructor;
15617       else if (!RDecl->hasTrivialDefaultConstructor())
15618         member = CXXDefaultConstructor;
15619       else if (RDecl->hasNonTrivialCopyAssignment())
15620         member = CXXCopyAssignment;
15621       else if (RDecl->hasNonTrivialDestructor())
15622         member = CXXDestructor;
15623 
15624       if (member != CXXInvalid) {
15625         if (!getLangOpts().CPlusPlus11 &&
15626             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15627           // Objective-C++ ARC: it is an error to have a non-trivial field of
15628           // a union. However, system headers in Objective-C programs
15629           // occasionally have Objective-C lifetime objects within unions,
15630           // and rather than cause the program to fail, we make those
15631           // members unavailable.
15632           SourceLocation Loc = FD->getLocation();
15633           if (getSourceManager().isInSystemHeader(Loc)) {
15634             if (!FD->hasAttr<UnavailableAttr>())
15635               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15636                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15637             return false;
15638           }
15639         }
15640 
15641         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15642                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15643                diag::err_illegal_union_or_anon_struct_member)
15644           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15645         DiagnoseNontrivial(RDecl, member);
15646         return !getLangOpts().CPlusPlus11;
15647       }
15648     }
15649   }
15650 
15651   return false;
15652 }
15653 
15654 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15655 ///  AST enum value.
15656 static ObjCIvarDecl::AccessControl
15657 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15658   switch (ivarVisibility) {
15659   default: llvm_unreachable("Unknown visitibility kind");
15660   case tok::objc_private: return ObjCIvarDecl::Private;
15661   case tok::objc_public: return ObjCIvarDecl::Public;
15662   case tok::objc_protected: return ObjCIvarDecl::Protected;
15663   case tok::objc_package: return ObjCIvarDecl::Package;
15664   }
15665 }
15666 
15667 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15668 /// in order to create an IvarDecl object for it.
15669 Decl *Sema::ActOnIvar(Scope *S,
15670                                 SourceLocation DeclStart,
15671                                 Declarator &D, Expr *BitfieldWidth,
15672                                 tok::ObjCKeywordKind Visibility) {
15673 
15674   IdentifierInfo *II = D.getIdentifier();
15675   Expr *BitWidth = (Expr*)BitfieldWidth;
15676   SourceLocation Loc = DeclStart;
15677   if (II) Loc = D.getIdentifierLoc();
15678 
15679   // FIXME: Unnamed fields can be handled in various different ways, for
15680   // example, unnamed unions inject all members into the struct namespace!
15681 
15682   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15683   QualType T = TInfo->getType();
15684 
15685   if (BitWidth) {
15686     // 6.7.2.1p3, 6.7.2.1p4
15687     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15688     if (!BitWidth)
15689       D.setInvalidType();
15690   } else {
15691     // Not a bitfield.
15692 
15693     // validate II.
15694 
15695   }
15696   if (T->isReferenceType()) {
15697     Diag(Loc, diag::err_ivar_reference_type);
15698     D.setInvalidType();
15699   }
15700   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15701   // than a variably modified type.
15702   else if (T->isVariablyModifiedType()) {
15703     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15704     D.setInvalidType();
15705   }
15706 
15707   // Get the visibility (access control) for this ivar.
15708   ObjCIvarDecl::AccessControl ac =
15709     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15710                                         : ObjCIvarDecl::None;
15711   // Must set ivar's DeclContext to its enclosing interface.
15712   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15713   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15714     return nullptr;
15715   ObjCContainerDecl *EnclosingContext;
15716   if (ObjCImplementationDecl *IMPDecl =
15717       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15718     if (LangOpts.ObjCRuntime.isFragile()) {
15719     // Case of ivar declared in an implementation. Context is that of its class.
15720       EnclosingContext = IMPDecl->getClassInterface();
15721       assert(EnclosingContext && "Implementation has no class interface!");
15722     }
15723     else
15724       EnclosingContext = EnclosingDecl;
15725   } else {
15726     if (ObjCCategoryDecl *CDecl =
15727         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15728       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15729         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15730         return nullptr;
15731       }
15732     }
15733     EnclosingContext = EnclosingDecl;
15734   }
15735 
15736   // Construct the decl.
15737   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15738                                              DeclStart, Loc, II, T,
15739                                              TInfo, ac, (Expr *)BitfieldWidth);
15740 
15741   if (II) {
15742     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15743                                            ForVisibleRedeclaration);
15744     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15745         && !isa<TagDecl>(PrevDecl)) {
15746       Diag(Loc, diag::err_duplicate_member) << II;
15747       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15748       NewID->setInvalidDecl();
15749     }
15750   }
15751 
15752   // Process attributes attached to the ivar.
15753   ProcessDeclAttributes(S, NewID, D);
15754 
15755   if (D.isInvalidType())
15756     NewID->setInvalidDecl();
15757 
15758   // In ARC, infer 'retaining' for ivars of retainable type.
15759   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15760     NewID->setInvalidDecl();
15761 
15762   if (D.getDeclSpec().isModulePrivateSpecified())
15763     NewID->setModulePrivate();
15764 
15765   if (II) {
15766     // FIXME: When interfaces are DeclContexts, we'll need to add
15767     // these to the interface.
15768     S->AddDecl(NewID);
15769     IdResolver.AddDecl(NewID);
15770   }
15771 
15772   if (LangOpts.ObjCRuntime.isNonFragile() &&
15773       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15774     Diag(Loc, diag::warn_ivars_in_interface);
15775 
15776   return NewID;
15777 }
15778 
15779 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15780 /// class and class extensions. For every class \@interface and class
15781 /// extension \@interface, if the last ivar is a bitfield of any type,
15782 /// then add an implicit `char :0` ivar to the end of that interface.
15783 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15784                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15785   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15786     return;
15787 
15788   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15789   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15790 
15791   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15792     return;
15793   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15794   if (!ID) {
15795     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15796       if (!CD->IsClassExtension())
15797         return;
15798     }
15799     // No need to add this to end of @implementation.
15800     else
15801       return;
15802   }
15803   // All conditions are met. Add a new bitfield to the tail end of ivars.
15804   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15805   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15806 
15807   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15808                               DeclLoc, DeclLoc, nullptr,
15809                               Context.CharTy,
15810                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15811                                                                DeclLoc),
15812                               ObjCIvarDecl::Private, BW,
15813                               true);
15814   AllIvarDecls.push_back(Ivar);
15815 }
15816 
15817 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15818                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15819                        SourceLocation RBrac,
15820                        const ParsedAttributesView &Attrs) {
15821   assert(EnclosingDecl && "missing record or interface decl");
15822 
15823   // If this is an Objective-C @implementation or category and we have
15824   // new fields here we should reset the layout of the interface since
15825   // it will now change.
15826   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15827     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15828     switch (DC->getKind()) {
15829     default: break;
15830     case Decl::ObjCCategory:
15831       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15832       break;
15833     case Decl::ObjCImplementation:
15834       Context.
15835         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15836       break;
15837     }
15838   }
15839 
15840   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15841   CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15842 
15843   // Start counting up the number of named members; make sure to include
15844   // members of anonymous structs and unions in the total.
15845   unsigned NumNamedMembers = 0;
15846   if (Record) {
15847     for (const auto *I : Record->decls()) {
15848       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15849         if (IFD->getDeclName())
15850           ++NumNamedMembers;
15851     }
15852   }
15853 
15854   // Verify that all the fields are okay.
15855   SmallVector<FieldDecl*, 32> RecFields;
15856 
15857   bool ObjCFieldLifetimeErrReported = false;
15858   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15859        i != end; ++i) {
15860     FieldDecl *FD = cast<FieldDecl>(*i);
15861 
15862     // Get the type for the field.
15863     const Type *FDTy = FD->getType().getTypePtr();
15864 
15865     if (!FD->isAnonymousStructOrUnion()) {
15866       // Remember all fields written by the user.
15867       RecFields.push_back(FD);
15868     }
15869 
15870     // If the field is already invalid for some reason, don't emit more
15871     // diagnostics about it.
15872     if (FD->isInvalidDecl()) {
15873       EnclosingDecl->setInvalidDecl();
15874       continue;
15875     }
15876 
15877     // C99 6.7.2.1p2:
15878     //   A structure or union shall not contain a member with
15879     //   incomplete or function type (hence, a structure shall not
15880     //   contain an instance of itself, but may contain a pointer to
15881     //   an instance of itself), except that the last member of a
15882     //   structure with more than one named member may have incomplete
15883     //   array type; such a structure (and any union containing,
15884     //   possibly recursively, a member that is such a structure)
15885     //   shall not be a member of a structure or an element of an
15886     //   array.
15887     bool IsLastField = (i + 1 == Fields.end());
15888     if (FDTy->isFunctionType()) {
15889       // Field declared as a function.
15890       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15891         << FD->getDeclName();
15892       FD->setInvalidDecl();
15893       EnclosingDecl->setInvalidDecl();
15894       continue;
15895     } else if (FDTy->isIncompleteArrayType() &&
15896                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15897       if (Record) {
15898         // Flexible array member.
15899         // Microsoft and g++ is more permissive regarding flexible array.
15900         // It will accept flexible array in union and also
15901         // as the sole element of a struct/class.
15902         unsigned DiagID = 0;
15903         if (!Record->isUnion() && !IsLastField) {
15904           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15905             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15906           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15907           FD->setInvalidDecl();
15908           EnclosingDecl->setInvalidDecl();
15909           continue;
15910         } else if (Record->isUnion())
15911           DiagID = getLangOpts().MicrosoftExt
15912                        ? diag::ext_flexible_array_union_ms
15913                        : getLangOpts().CPlusPlus
15914                              ? diag::ext_flexible_array_union_gnu
15915                              : diag::err_flexible_array_union;
15916         else if (NumNamedMembers < 1)
15917           DiagID = getLangOpts().MicrosoftExt
15918                        ? diag::ext_flexible_array_empty_aggregate_ms
15919                        : getLangOpts().CPlusPlus
15920                              ? diag::ext_flexible_array_empty_aggregate_gnu
15921                              : diag::err_flexible_array_empty_aggregate;
15922 
15923         if (DiagID)
15924           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15925                                           << Record->getTagKind();
15926         // While the layout of types that contain virtual bases is not specified
15927         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15928         // virtual bases after the derived members.  This would make a flexible
15929         // array member declared at the end of an object not adjacent to the end
15930         // of the type.
15931         if (CXXRecord && CXXRecord->getNumVBases() != 0)
15932           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15933               << FD->getDeclName() << Record->getTagKind();
15934         if (!getLangOpts().C99)
15935           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15936             << FD->getDeclName() << Record->getTagKind();
15937 
15938         // If the element type has a non-trivial destructor, we would not
15939         // implicitly destroy the elements, so disallow it for now.
15940         //
15941         // FIXME: GCC allows this. We should probably either implicitly delete
15942         // the destructor of the containing class, or just allow this.
15943         QualType BaseElem = Context.getBaseElementType(FD->getType());
15944         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15945           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15946             << FD->getDeclName() << FD->getType();
15947           FD->setInvalidDecl();
15948           EnclosingDecl->setInvalidDecl();
15949           continue;
15950         }
15951         // Okay, we have a legal flexible array member at the end of the struct.
15952         Record->setHasFlexibleArrayMember(true);
15953       } else {
15954         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15955         // unless they are followed by another ivar. That check is done
15956         // elsewhere, after synthesized ivars are known.
15957       }
15958     } else if (!FDTy->isDependentType() &&
15959                RequireCompleteType(FD->getLocation(), FD->getType(),
15960                                    diag::err_field_incomplete)) {
15961       // Incomplete type
15962       FD->setInvalidDecl();
15963       EnclosingDecl->setInvalidDecl();
15964       continue;
15965     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15966       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15967         // A type which contains a flexible array member is considered to be a
15968         // flexible array member.
15969         Record->setHasFlexibleArrayMember(true);
15970         if (!Record->isUnion()) {
15971           // If this is a struct/class and this is not the last element, reject
15972           // it.  Note that GCC supports variable sized arrays in the middle of
15973           // structures.
15974           if (!IsLastField)
15975             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15976               << FD->getDeclName() << FD->getType();
15977           else {
15978             // We support flexible arrays at the end of structs in
15979             // other structs as an extension.
15980             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15981               << FD->getDeclName();
15982           }
15983         }
15984       }
15985       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15986           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15987                                  diag::err_abstract_type_in_decl,
15988                                  AbstractIvarType)) {
15989         // Ivars can not have abstract class types
15990         FD->setInvalidDecl();
15991       }
15992       if (Record && FDTTy->getDecl()->hasObjectMember())
15993         Record->setHasObjectMember(true);
15994       if (Record && FDTTy->getDecl()->hasVolatileMember())
15995         Record->setHasVolatileMember(true);
15996       if (Record && Record->isUnion() &&
15997           FD->getType().isNonTrivialPrimitiveCType(Context))
15998         Diag(FD->getLocation(),
15999              diag::err_nontrivial_primitive_type_in_union);
16000     } else if (FDTy->isObjCObjectType()) {
16001       /// A field cannot be an Objective-c object
16002       Diag(FD->getLocation(), diag::err_statically_allocated_object)
16003         << FixItHint::CreateInsertion(FD->getLocation(), "*");
16004       QualType T = Context.getObjCObjectPointerType(FD->getType());
16005       FD->setType(T);
16006     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
16007                Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
16008                !getLangOpts().CPlusPlus) {
16009       // It's an error in ARC or Weak if a field has lifetime.
16010       // We don't want to report this in a system header, though,
16011       // so we just make the field unavailable.
16012       // FIXME: that's really not sufficient; we need to make the type
16013       // itself invalid to, say, initialize or copy.
16014       QualType T = FD->getType();
16015       if (T.hasNonTrivialObjCLifetime()) {
16016         SourceLocation loc = FD->getLocation();
16017         if (getSourceManager().isInSystemHeader(loc)) {
16018           if (!FD->hasAttr<UnavailableAttr>()) {
16019             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16020                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
16021           }
16022         } else {
16023           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
16024             << T->isBlockPointerType() << Record->getTagKind();
16025         }
16026         ObjCFieldLifetimeErrReported = true;
16027       }
16028     } else if (getLangOpts().ObjC &&
16029                getLangOpts().getGC() != LangOptions::NonGC &&
16030                Record && !Record->hasObjectMember()) {
16031       if (FD->getType()->isObjCObjectPointerType() ||
16032           FD->getType().isObjCGCStrong())
16033         Record->setHasObjectMember(true);
16034       else if (Context.getAsArrayType(FD->getType())) {
16035         QualType BaseType = Context.getBaseElementType(FD->getType());
16036         if (BaseType->isRecordType() &&
16037             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16038           Record->setHasObjectMember(true);
16039         else if (BaseType->isObjCObjectPointerType() ||
16040                  BaseType.isObjCGCStrong())
16041                Record->setHasObjectMember(true);
16042       }
16043     }
16044 
16045     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16046       QualType FT = FD->getType();
16047       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16048         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16049       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16050       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16051         Record->setNonTrivialToPrimitiveCopy(true);
16052       if (FT.isDestructedType()) {
16053         Record->setNonTrivialToPrimitiveDestroy(true);
16054         Record->setParamDestroyedInCallee(true);
16055       }
16056 
16057       if (const auto *RT = FT->getAs<RecordType>()) {
16058         if (RT->getDecl()->getArgPassingRestrictions() ==
16059             RecordDecl::APK_CanNeverPassInRegs)
16060           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16061       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16062         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16063     }
16064 
16065     if (Record && FD->getType().isVolatileQualified())
16066       Record->setHasVolatileMember(true);
16067     // Keep track of the number of named members.
16068     if (FD->getIdentifier())
16069       ++NumNamedMembers;
16070   }
16071 
16072   // Okay, we successfully defined 'Record'.
16073   if (Record) {
16074     bool Completed = false;
16075     if (CXXRecord) {
16076       if (!CXXRecord->isInvalidDecl()) {
16077         // Set access bits correctly on the directly-declared conversions.
16078         for (CXXRecordDecl::conversion_iterator
16079                I = CXXRecord->conversion_begin(),
16080                E = CXXRecord->conversion_end(); I != E; ++I)
16081           I.setAccess((*I)->getAccess());
16082       }
16083 
16084       if (!CXXRecord->isDependentType()) {
16085         // Add any implicitly-declared members to this class.
16086         AddImplicitlyDeclaredMembersToClass(CXXRecord);
16087 
16088         if (!CXXRecord->isInvalidDecl()) {
16089           // If we have virtual base classes, we may end up finding multiple
16090           // final overriders for a given virtual function. Check for this
16091           // problem now.
16092           if (CXXRecord->getNumVBases()) {
16093             CXXFinalOverriderMap FinalOverriders;
16094             CXXRecord->getFinalOverriders(FinalOverriders);
16095 
16096             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16097                                              MEnd = FinalOverriders.end();
16098                  M != MEnd; ++M) {
16099               for (OverridingMethods::iterator SO = M->second.begin(),
16100                                             SOEnd = M->second.end();
16101                    SO != SOEnd; ++SO) {
16102                 assert(SO->second.size() > 0 &&
16103                        "Virtual function without overriding functions?");
16104                 if (SO->second.size() == 1)
16105                   continue;
16106 
16107                 // C++ [class.virtual]p2:
16108                 //   In a derived class, if a virtual member function of a base
16109                 //   class subobject has more than one final overrider the
16110                 //   program is ill-formed.
16111                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16112                   << (const NamedDecl *)M->first << Record;
16113                 Diag(M->first->getLocation(),
16114                      diag::note_overridden_virtual_function);
16115                 for (OverridingMethods::overriding_iterator
16116                           OM = SO->second.begin(),
16117                        OMEnd = SO->second.end();
16118                      OM != OMEnd; ++OM)
16119                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
16120                     << (const NamedDecl *)M->first << OM->Method->getParent();
16121 
16122                 Record->setInvalidDecl();
16123               }
16124             }
16125             CXXRecord->completeDefinition(&FinalOverriders);
16126             Completed = true;
16127           }
16128         }
16129       }
16130     }
16131 
16132     if (!Completed)
16133       Record->completeDefinition();
16134 
16135     // Handle attributes before checking the layout.
16136     ProcessDeclAttributeList(S, Record, Attrs);
16137 
16138     // We may have deferred checking for a deleted destructor. Check now.
16139     if (CXXRecord) {
16140       auto *Dtor = CXXRecord->getDestructor();
16141       if (Dtor && Dtor->isImplicit() &&
16142           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16143         CXXRecord->setImplicitDestructorIsDeleted();
16144         SetDeclDeleted(Dtor, CXXRecord->getLocation());
16145       }
16146     }
16147 
16148     if (Record->hasAttrs()) {
16149       CheckAlignasUnderalignment(Record);
16150 
16151       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16152         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16153                                            IA->getRange(), IA->getBestCase(),
16154                                            IA->getSemanticSpelling());
16155     }
16156 
16157     // Check if the structure/union declaration is a type that can have zero
16158     // size in C. For C this is a language extension, for C++ it may cause
16159     // compatibility problems.
16160     bool CheckForZeroSize;
16161     if (!getLangOpts().CPlusPlus) {
16162       CheckForZeroSize = true;
16163     } else {
16164       // For C++ filter out types that cannot be referenced in C code.
16165       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16166       CheckForZeroSize =
16167           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16168           !CXXRecord->isDependentType() &&
16169           CXXRecord->isCLike();
16170     }
16171     if (CheckForZeroSize) {
16172       bool ZeroSize = true;
16173       bool IsEmpty = true;
16174       unsigned NonBitFields = 0;
16175       for (RecordDecl::field_iterator I = Record->field_begin(),
16176                                       E = Record->field_end();
16177            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16178         IsEmpty = false;
16179         if (I->isUnnamedBitfield()) {
16180           if (!I->isZeroLengthBitField(Context))
16181             ZeroSize = false;
16182         } else {
16183           ++NonBitFields;
16184           QualType FieldType = I->getType();
16185           if (FieldType->isIncompleteType() ||
16186               !Context.getTypeSizeInChars(FieldType).isZero())
16187             ZeroSize = false;
16188         }
16189       }
16190 
16191       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16192       // allowed in C++, but warn if its declaration is inside
16193       // extern "C" block.
16194       if (ZeroSize) {
16195         Diag(RecLoc, getLangOpts().CPlusPlus ?
16196                          diag::warn_zero_size_struct_union_in_extern_c :
16197                          diag::warn_zero_size_struct_union_compat)
16198           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16199       }
16200 
16201       // Structs without named members are extension in C (C99 6.7.2.1p7),
16202       // but are accepted by GCC.
16203       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16204         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16205                                diag::ext_no_named_members_in_struct_union)
16206           << Record->isUnion();
16207       }
16208     }
16209   } else {
16210     ObjCIvarDecl **ClsFields =
16211       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16212     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16213       ID->setEndOfDefinitionLoc(RBrac);
16214       // Add ivar's to class's DeclContext.
16215       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16216         ClsFields[i]->setLexicalDeclContext(ID);
16217         ID->addDecl(ClsFields[i]);
16218       }
16219       // Must enforce the rule that ivars in the base classes may not be
16220       // duplicates.
16221       if (ID->getSuperClass())
16222         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16223     } else if (ObjCImplementationDecl *IMPDecl =
16224                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16225       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16226       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16227         // Ivar declared in @implementation never belongs to the implementation.
16228         // Only it is in implementation's lexical context.
16229         ClsFields[I]->setLexicalDeclContext(IMPDecl);
16230       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16231       IMPDecl->setIvarLBraceLoc(LBrac);
16232       IMPDecl->setIvarRBraceLoc(RBrac);
16233     } else if (ObjCCategoryDecl *CDecl =
16234                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16235       // case of ivars in class extension; all other cases have been
16236       // reported as errors elsewhere.
16237       // FIXME. Class extension does not have a LocEnd field.
16238       // CDecl->setLocEnd(RBrac);
16239       // Add ivar's to class extension's DeclContext.
16240       // Diagnose redeclaration of private ivars.
16241       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16242       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16243         if (IDecl) {
16244           if (const ObjCIvarDecl *ClsIvar =
16245               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16246             Diag(ClsFields[i]->getLocation(),
16247                  diag::err_duplicate_ivar_declaration);
16248             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16249             continue;
16250           }
16251           for (const auto *Ext : IDecl->known_extensions()) {
16252             if (const ObjCIvarDecl *ClsExtIvar
16253                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16254               Diag(ClsFields[i]->getLocation(),
16255                    diag::err_duplicate_ivar_declaration);
16256               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16257               continue;
16258             }
16259           }
16260         }
16261         ClsFields[i]->setLexicalDeclContext(CDecl);
16262         CDecl->addDecl(ClsFields[i]);
16263       }
16264       CDecl->setIvarLBraceLoc(LBrac);
16265       CDecl->setIvarRBraceLoc(RBrac);
16266     }
16267   }
16268 }
16269 
16270 /// Determine whether the given integral value is representable within
16271 /// the given type T.
16272 static bool isRepresentableIntegerValue(ASTContext &Context,
16273                                         llvm::APSInt &Value,
16274                                         QualType T) {
16275   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16276          "Integral type required!");
16277   unsigned BitWidth = Context.getIntWidth(T);
16278 
16279   if (Value.isUnsigned() || Value.isNonNegative()) {
16280     if (T->isSignedIntegerOrEnumerationType())
16281       --BitWidth;
16282     return Value.getActiveBits() <= BitWidth;
16283   }
16284   return Value.getMinSignedBits() <= BitWidth;
16285 }
16286 
16287 // Given an integral type, return the next larger integral type
16288 // (or a NULL type of no such type exists).
16289 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
16290   // FIXME: Int128/UInt128 support, which also needs to be introduced into
16291   // enum checking below.
16292   assert((T->isIntegralType(Context) ||
16293          T->isEnumeralType()) && "Integral type required!");
16294   const unsigned NumTypes = 4;
16295   QualType SignedIntegralTypes[NumTypes] = {
16296     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
16297   };
16298   QualType UnsignedIntegralTypes[NumTypes] = {
16299     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
16300     Context.UnsignedLongLongTy
16301   };
16302 
16303   unsigned BitWidth = Context.getTypeSize(T);
16304   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16305                                                         : UnsignedIntegralTypes;
16306   for (unsigned I = 0; I != NumTypes; ++I)
16307     if (Context.getTypeSize(Types[I]) > BitWidth)
16308       return Types[I];
16309 
16310   return QualType();
16311 }
16312 
16313 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16314                                           EnumConstantDecl *LastEnumConst,
16315                                           SourceLocation IdLoc,
16316                                           IdentifierInfo *Id,
16317                                           Expr *Val) {
16318   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16319   llvm::APSInt EnumVal(IntWidth);
16320   QualType EltTy;
16321 
16322   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
16323     Val = nullptr;
16324 
16325   if (Val)
16326     Val = DefaultLvalueConversion(Val).get();
16327 
16328   if (Val) {
16329     if (Enum->isDependentType() || Val->isTypeDependent())
16330       EltTy = Context.DependentTy;
16331     else {
16332       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16333           !getLangOpts().MSVCCompat) {
16334         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16335         // constant-expression in the enumerator-definition shall be a converted
16336         // constant expression of the underlying type.
16337         EltTy = Enum->getIntegerType();
16338         ExprResult Converted =
16339           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16340                                            CCEK_Enumerator);
16341         if (Converted.isInvalid())
16342           Val = nullptr;
16343         else
16344           Val = Converted.get();
16345       } else if (!Val->isValueDependent() &&
16346                  !(Val = VerifyIntegerConstantExpression(Val,
16347                                                          &EnumVal).get())) {
16348         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16349       } else {
16350         if (Enum->isComplete()) {
16351           EltTy = Enum->getIntegerType();
16352 
16353           // In Obj-C and Microsoft mode, require the enumeration value to be
16354           // representable in the underlying type of the enumeration. In C++11,
16355           // we perform a non-narrowing conversion as part of converted constant
16356           // expression checking.
16357           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16358             if (getLangOpts().MSVCCompat) {
16359               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16360               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
16361             } else
16362               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16363           } else
16364             Val = ImpCastExprToType(Val, EltTy,
16365                                     EltTy->isBooleanType() ?
16366                                     CK_IntegralToBoolean : CK_IntegralCast)
16367                     .get();
16368         } else if (getLangOpts().CPlusPlus) {
16369           // C++11 [dcl.enum]p5:
16370           //   If the underlying type is not fixed, the type of each enumerator
16371           //   is the type of its initializing value:
16372           //     - If an initializer is specified for an enumerator, the
16373           //       initializing value has the same type as the expression.
16374           EltTy = Val->getType();
16375         } else {
16376           // C99 6.7.2.2p2:
16377           //   The expression that defines the value of an enumeration constant
16378           //   shall be an integer constant expression that has a value
16379           //   representable as an int.
16380 
16381           // Complain if the value is not representable in an int.
16382           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16383             Diag(IdLoc, diag::ext_enum_value_not_int)
16384               << EnumVal.toString(10) << Val->getSourceRange()
16385               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16386           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16387             // Force the type of the expression to 'int'.
16388             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
16389           }
16390           EltTy = Val->getType();
16391         }
16392       }
16393     }
16394   }
16395 
16396   if (!Val) {
16397     if (Enum->isDependentType())
16398       EltTy = Context.DependentTy;
16399     else if (!LastEnumConst) {
16400       // C++0x [dcl.enum]p5:
16401       //   If the underlying type is not fixed, the type of each enumerator
16402       //   is the type of its initializing value:
16403       //     - If no initializer is specified for the first enumerator, the
16404       //       initializing value has an unspecified integral type.
16405       //
16406       // GCC uses 'int' for its unspecified integral type, as does
16407       // C99 6.7.2.2p3.
16408       if (Enum->isFixed()) {
16409         EltTy = Enum->getIntegerType();
16410       }
16411       else {
16412         EltTy = Context.IntTy;
16413       }
16414     } else {
16415       // Assign the last value + 1.
16416       EnumVal = LastEnumConst->getInitVal();
16417       ++EnumVal;
16418       EltTy = LastEnumConst->getType();
16419 
16420       // Check for overflow on increment.
16421       if (EnumVal < LastEnumConst->getInitVal()) {
16422         // C++0x [dcl.enum]p5:
16423         //   If the underlying type is not fixed, the type of each enumerator
16424         //   is the type of its initializing value:
16425         //
16426         //     - Otherwise the type of the initializing value is the same as
16427         //       the type of the initializing value of the preceding enumerator
16428         //       unless the incremented value is not representable in that type,
16429         //       in which case the type is an unspecified integral type
16430         //       sufficient to contain the incremented value. If no such type
16431         //       exists, the program is ill-formed.
16432         QualType T = getNextLargerIntegralType(Context, EltTy);
16433         if (T.isNull() || Enum->isFixed()) {
16434           // There is no integral type larger enough to represent this
16435           // value. Complain, then allow the value to wrap around.
16436           EnumVal = LastEnumConst->getInitVal();
16437           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16438           ++EnumVal;
16439           if (Enum->isFixed())
16440             // When the underlying type is fixed, this is ill-formed.
16441             Diag(IdLoc, diag::err_enumerator_wrapped)
16442               << EnumVal.toString(10)
16443               << EltTy;
16444           else
16445             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16446               << EnumVal.toString(10);
16447         } else {
16448           EltTy = T;
16449         }
16450 
16451         // Retrieve the last enumerator's value, extent that type to the
16452         // type that is supposed to be large enough to represent the incremented
16453         // value, then increment.
16454         EnumVal = LastEnumConst->getInitVal();
16455         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16456         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16457         ++EnumVal;
16458 
16459         // If we're not in C++, diagnose the overflow of enumerator values,
16460         // which in C99 means that the enumerator value is not representable in
16461         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16462         // permits enumerator values that are representable in some larger
16463         // integral type.
16464         if (!getLangOpts().CPlusPlus && !T.isNull())
16465           Diag(IdLoc, diag::warn_enum_value_overflow);
16466       } else if (!getLangOpts().CPlusPlus &&
16467                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16468         // Enforce C99 6.7.2.2p2 even when we compute the next value.
16469         Diag(IdLoc, diag::ext_enum_value_not_int)
16470           << EnumVal.toString(10) << 1;
16471       }
16472     }
16473   }
16474 
16475   if (!EltTy->isDependentType()) {
16476     // Make the enumerator value match the signedness and size of the
16477     // enumerator's type.
16478     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16479     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16480   }
16481 
16482   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16483                                   Val, EnumVal);
16484 }
16485 
16486 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
16487                                                 SourceLocation IILoc) {
16488   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16489       !getLangOpts().CPlusPlus)
16490     return SkipBodyInfo();
16491 
16492   // We have an anonymous enum definition. Look up the first enumerator to
16493   // determine if we should merge the definition with an existing one and
16494   // skip the body.
16495   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
16496                                          forRedeclarationInCurContext());
16497   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16498   if (!PrevECD)
16499     return SkipBodyInfo();
16500 
16501   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16502   NamedDecl *Hidden;
16503   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16504     SkipBodyInfo Skip;
16505     Skip.Previous = Hidden;
16506     return Skip;
16507   }
16508 
16509   return SkipBodyInfo();
16510 }
16511 
16512 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
16513                               SourceLocation IdLoc, IdentifierInfo *Id,
16514                               const ParsedAttributesView &Attrs,
16515                               SourceLocation EqualLoc, Expr *Val) {
16516   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16517   EnumConstantDecl *LastEnumConst =
16518     cast_or_null<EnumConstantDecl>(lastEnumConst);
16519 
16520   // The scope passed in may not be a decl scope.  Zip up the scope tree until
16521   // we find one that is.
16522   S = getNonFieldDeclScope(S);
16523 
16524   // Verify that there isn't already something declared with this name in this
16525   // scope.
16526   LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
16527   LookupName(R, S);
16528   NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16529 
16530   if (PrevDecl && PrevDecl->isTemplateParameter()) {
16531     // Maybe we will complain about the shadowed template parameter.
16532     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
16533     // Just pretend that we didn't see the previous declaration.
16534     PrevDecl = nullptr;
16535   }
16536 
16537   // C++ [class.mem]p15:
16538   // If T is the name of a class, then each of the following shall have a name
16539   // different from T:
16540   // - every enumerator of every member of class T that is an unscoped
16541   // enumerated type
16542   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16543     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16544                             DeclarationNameInfo(Id, IdLoc));
16545 
16546   EnumConstantDecl *New =
16547     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
16548   if (!New)
16549     return nullptr;
16550 
16551   if (PrevDecl) {
16552     if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16553       // Check for other kinds of shadowing not already handled.
16554       CheckShadow(New, PrevDecl, R);
16555     }
16556 
16557     // When in C++, we may get a TagDecl with the same name; in this case the
16558     // enum constant will 'hide' the tag.
16559     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16560            "Received TagDecl when not in C++!");
16561     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16562       if (isa<EnumConstantDecl>(PrevDecl))
16563         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16564       else
16565         Diag(IdLoc, diag::err_redefinition) << Id;
16566       notePreviousDefinition(PrevDecl, IdLoc);
16567       return nullptr;
16568     }
16569   }
16570 
16571   // Process attributes.
16572   ProcessDeclAttributeList(S, New, Attrs);
16573   AddPragmaAttributes(S, New);
16574 
16575   // Register this decl in the current scope stack.
16576   New->setAccess(TheEnumDecl->getAccess());
16577   PushOnScopeChains(New, S);
16578 
16579   ActOnDocumentableDecl(New);
16580 
16581   return New;
16582 }
16583 
16584 // Returns true when the enum initial expression does not trigger the
16585 // duplicate enum warning.  A few common cases are exempted as follows:
16586 // Element2 = Element1
16587 // Element2 = Element1 + 1
16588 // Element2 = Element1 - 1
16589 // Where Element2 and Element1 are from the same enum.
16590 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16591   Expr *InitExpr = ECD->getInitExpr();
16592   if (!InitExpr)
16593     return true;
16594   InitExpr = InitExpr->IgnoreImpCasts();
16595 
16596   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16597     if (!BO->isAdditiveOp())
16598       return true;
16599     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16600     if (!IL)
16601       return true;
16602     if (IL->getValue() != 1)
16603       return true;
16604 
16605     InitExpr = BO->getLHS();
16606   }
16607 
16608   // This checks if the elements are from the same enum.
16609   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16610   if (!DRE)
16611     return true;
16612 
16613   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16614   if (!EnumConstant)
16615     return true;
16616 
16617   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16618       Enum)
16619     return true;
16620 
16621   return false;
16622 }
16623 
16624 // Emits a warning when an element is implicitly set a value that
16625 // a previous element has already been set to.
16626 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16627                                         EnumDecl *Enum, QualType EnumType) {
16628   // Avoid anonymous enums
16629   if (!Enum->getIdentifier())
16630     return;
16631 
16632   // Only check for small enums.
16633   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16634     return;
16635 
16636   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16637     return;
16638 
16639   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16640   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16641 
16642   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16643   typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16644 
16645   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16646   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16647     llvm::APSInt Val = D->getInitVal();
16648     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16649   };
16650 
16651   DuplicatesVector DupVector;
16652   ValueToVectorMap EnumMap;
16653 
16654   // Populate the EnumMap with all values represented by enum constants without
16655   // an initializer.
16656   for (auto *Element : Elements) {
16657     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16658 
16659     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16660     // this constant.  Skip this enum since it may be ill-formed.
16661     if (!ECD) {
16662       return;
16663     }
16664 
16665     // Constants with initalizers are handled in the next loop.
16666     if (ECD->getInitExpr())
16667       continue;
16668 
16669     // Duplicate values are handled in the next loop.
16670     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16671   }
16672 
16673   if (EnumMap.size() == 0)
16674     return;
16675 
16676   // Create vectors for any values that has duplicates.
16677   for (auto *Element : Elements) {
16678     // The last loop returned if any constant was null.
16679     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16680     if (!ValidDuplicateEnum(ECD, Enum))
16681       continue;
16682 
16683     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16684     if (Iter == EnumMap.end())
16685       continue;
16686 
16687     DeclOrVector& Entry = Iter->second;
16688     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16689       // Ensure constants are different.
16690       if (D == ECD)
16691         continue;
16692 
16693       // Create new vector and push values onto it.
16694       auto Vec = llvm::make_unique<ECDVector>();
16695       Vec->push_back(D);
16696       Vec->push_back(ECD);
16697 
16698       // Update entry to point to the duplicates vector.
16699       Entry = Vec.get();
16700 
16701       // Store the vector somewhere we can consult later for quick emission of
16702       // diagnostics.
16703       DupVector.emplace_back(std::move(Vec));
16704       continue;
16705     }
16706 
16707     ECDVector *Vec = Entry.get<ECDVector*>();
16708     // Make sure constants are not added more than once.
16709     if (*Vec->begin() == ECD)
16710       continue;
16711 
16712     Vec->push_back(ECD);
16713   }
16714 
16715   // Emit diagnostics.
16716   for (const auto &Vec : DupVector) {
16717     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16718 
16719     // Emit warning for one enum constant.
16720     auto *FirstECD = Vec->front();
16721     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16722       << FirstECD << FirstECD->getInitVal().toString(10)
16723       << FirstECD->getSourceRange();
16724 
16725     // Emit one note for each of the remaining enum constants with
16726     // the same value.
16727     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16728       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16729         << ECD << ECD->getInitVal().toString(10)
16730         << ECD->getSourceRange();
16731   }
16732 }
16733 
16734 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16735                              bool AllowMask) const {
16736   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16737   assert(ED->isCompleteDefinition() && "expected enum definition");
16738 
16739   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16740   llvm::APInt &FlagBits = R.first->second;
16741 
16742   if (R.second) {
16743     for (auto *E : ED->enumerators()) {
16744       const auto &EVal = E->getInitVal();
16745       // Only single-bit enumerators introduce new flag values.
16746       if (EVal.isPowerOf2())
16747         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16748     }
16749   }
16750 
16751   // A value is in a flag enum if either its bits are a subset of the enum's
16752   // flag bits (the first condition) or we are allowing masks and the same is
16753   // true of its complement (the second condition). When masks are allowed, we
16754   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16755   //
16756   // While it's true that any value could be used as a mask, the assumption is
16757   // that a mask will have all of the insignificant bits set. Anything else is
16758   // likely a logic error.
16759   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16760   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16761 }
16762 
16763 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16764                          Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
16765                          const ParsedAttributesView &Attrs) {
16766   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16767   QualType EnumType = Context.getTypeDeclType(Enum);
16768 
16769   ProcessDeclAttributeList(S, Enum, Attrs);
16770 
16771   if (Enum->isDependentType()) {
16772     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16773       EnumConstantDecl *ECD =
16774         cast_or_null<EnumConstantDecl>(Elements[i]);
16775       if (!ECD) continue;
16776 
16777       ECD->setType(EnumType);
16778     }
16779 
16780     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16781     return;
16782   }
16783 
16784   // TODO: If the result value doesn't fit in an int, it must be a long or long
16785   // long value.  ISO C does not support this, but GCC does as an extension,
16786   // emit a warning.
16787   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16788   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16789   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16790 
16791   // Verify that all the values are okay, compute the size of the values, and
16792   // reverse the list.
16793   unsigned NumNegativeBits = 0;
16794   unsigned NumPositiveBits = 0;
16795 
16796   // Keep track of whether all elements have type int.
16797   bool AllElementsInt = true;
16798 
16799   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16800     EnumConstantDecl *ECD =
16801       cast_or_null<EnumConstantDecl>(Elements[i]);
16802     if (!ECD) continue;  // Already issued a diagnostic.
16803 
16804     const llvm::APSInt &InitVal = ECD->getInitVal();
16805 
16806     // Keep track of the size of positive and negative values.
16807     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16808       NumPositiveBits = std::max(NumPositiveBits,
16809                                  (unsigned)InitVal.getActiveBits());
16810     else
16811       NumNegativeBits = std::max(NumNegativeBits,
16812                                  (unsigned)InitVal.getMinSignedBits());
16813 
16814     // Keep track of whether every enum element has type int (very common).
16815     if (AllElementsInt)
16816       AllElementsInt = ECD->getType() == Context.IntTy;
16817   }
16818 
16819   // Figure out the type that should be used for this enum.
16820   QualType BestType;
16821   unsigned BestWidth;
16822 
16823   // C++0x N3000 [conv.prom]p3:
16824   //   An rvalue of an unscoped enumeration type whose underlying
16825   //   type is not fixed can be converted to an rvalue of the first
16826   //   of the following types that can represent all the values of
16827   //   the enumeration: int, unsigned int, long int, unsigned long
16828   //   int, long long int, or unsigned long long int.
16829   // C99 6.4.4.3p2:
16830   //   An identifier declared as an enumeration constant has type int.
16831   // The C99 rule is modified by a gcc extension
16832   QualType BestPromotionType;
16833 
16834   bool Packed = Enum->hasAttr<PackedAttr>();
16835   // -fshort-enums is the equivalent to specifying the packed attribute on all
16836   // enum definitions.
16837   if (LangOpts.ShortEnums)
16838     Packed = true;
16839 
16840   // If the enum already has a type because it is fixed or dictated by the
16841   // target, promote that type instead of analyzing the enumerators.
16842   if (Enum->isComplete()) {
16843     BestType = Enum->getIntegerType();
16844     if (BestType->isPromotableIntegerType())
16845       BestPromotionType = Context.getPromotedIntegerType(BestType);
16846     else
16847       BestPromotionType = BestType;
16848 
16849     BestWidth = Context.getIntWidth(BestType);
16850   }
16851   else if (NumNegativeBits) {
16852     // If there is a negative value, figure out the smallest integer type (of
16853     // int/long/longlong) that fits.
16854     // If it's packed, check also if it fits a char or a short.
16855     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16856       BestType = Context.SignedCharTy;
16857       BestWidth = CharWidth;
16858     } else if (Packed && NumNegativeBits <= ShortWidth &&
16859                NumPositiveBits < ShortWidth) {
16860       BestType = Context.ShortTy;
16861       BestWidth = ShortWidth;
16862     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16863       BestType = Context.IntTy;
16864       BestWidth = IntWidth;
16865     } else {
16866       BestWidth = Context.getTargetInfo().getLongWidth();
16867 
16868       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16869         BestType = Context.LongTy;
16870       } else {
16871         BestWidth = Context.getTargetInfo().getLongLongWidth();
16872 
16873         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16874           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16875         BestType = Context.LongLongTy;
16876       }
16877     }
16878     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16879   } else {
16880     // If there is no negative value, figure out the smallest type that fits
16881     // all of the enumerator values.
16882     // If it's packed, check also if it fits a char or a short.
16883     if (Packed && NumPositiveBits <= CharWidth) {
16884       BestType = Context.UnsignedCharTy;
16885       BestPromotionType = Context.IntTy;
16886       BestWidth = CharWidth;
16887     } else if (Packed && NumPositiveBits <= ShortWidth) {
16888       BestType = Context.UnsignedShortTy;
16889       BestPromotionType = Context.IntTy;
16890       BestWidth = ShortWidth;
16891     } else if (NumPositiveBits <= IntWidth) {
16892       BestType = Context.UnsignedIntTy;
16893       BestWidth = IntWidth;
16894       BestPromotionType
16895         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16896                            ? Context.UnsignedIntTy : Context.IntTy;
16897     } else if (NumPositiveBits <=
16898                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16899       BestType = Context.UnsignedLongTy;
16900       BestPromotionType
16901         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16902                            ? Context.UnsignedLongTy : Context.LongTy;
16903     } else {
16904       BestWidth = Context.getTargetInfo().getLongLongWidth();
16905       assert(NumPositiveBits <= BestWidth &&
16906              "How could an initializer get larger than ULL?");
16907       BestType = Context.UnsignedLongLongTy;
16908       BestPromotionType
16909         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16910                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16911     }
16912   }
16913 
16914   // Loop over all of the enumerator constants, changing their types to match
16915   // the type of the enum if needed.
16916   for (auto *D : Elements) {
16917     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16918     if (!ECD) continue;  // Already issued a diagnostic.
16919 
16920     // Standard C says the enumerators have int type, but we allow, as an
16921     // extension, the enumerators to be larger than int size.  If each
16922     // enumerator value fits in an int, type it as an int, otherwise type it the
16923     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16924     // that X has type 'int', not 'unsigned'.
16925 
16926     // Determine whether the value fits into an int.
16927     llvm::APSInt InitVal = ECD->getInitVal();
16928 
16929     // If it fits into an integer type, force it.  Otherwise force it to match
16930     // the enum decl type.
16931     QualType NewTy;
16932     unsigned NewWidth;
16933     bool NewSign;
16934     if (!getLangOpts().CPlusPlus &&
16935         !Enum->isFixed() &&
16936         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16937       NewTy = Context.IntTy;
16938       NewWidth = IntWidth;
16939       NewSign = true;
16940     } else if (ECD->getType() == BestType) {
16941       // Already the right type!
16942       if (getLangOpts().CPlusPlus)
16943         // C++ [dcl.enum]p4: Following the closing brace of an
16944         // enum-specifier, each enumerator has the type of its
16945         // enumeration.
16946         ECD->setType(EnumType);
16947       continue;
16948     } else {
16949       NewTy = BestType;
16950       NewWidth = BestWidth;
16951       NewSign = BestType->isSignedIntegerOrEnumerationType();
16952     }
16953 
16954     // Adjust the APSInt value.
16955     InitVal = InitVal.extOrTrunc(NewWidth);
16956     InitVal.setIsSigned(NewSign);
16957     ECD->setInitVal(InitVal);
16958 
16959     // Adjust the Expr initializer and type.
16960     if (ECD->getInitExpr() &&
16961         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16962       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16963                                                 CK_IntegralCast,
16964                                                 ECD->getInitExpr(),
16965                                                 /*base paths*/ nullptr,
16966                                                 VK_RValue));
16967     if (getLangOpts().CPlusPlus)
16968       // C++ [dcl.enum]p4: Following the closing brace of an
16969       // enum-specifier, each enumerator has the type of its
16970       // enumeration.
16971       ECD->setType(EnumType);
16972     else
16973       ECD->setType(NewTy);
16974   }
16975 
16976   Enum->completeDefinition(BestType, BestPromotionType,
16977                            NumPositiveBits, NumNegativeBits);
16978 
16979   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16980 
16981   if (Enum->isClosedFlag()) {
16982     for (Decl *D : Elements) {
16983       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16984       if (!ECD) continue;  // Already issued a diagnostic.
16985 
16986       llvm::APSInt InitVal = ECD->getInitVal();
16987       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16988           !IsValueInFlagEnum(Enum, InitVal, true))
16989         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16990           << ECD << Enum;
16991     }
16992   }
16993 
16994   // Now that the enum type is defined, ensure it's not been underaligned.
16995   if (Enum->hasAttrs())
16996     CheckAlignasUnderalignment(Enum);
16997 }
16998 
16999 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
17000                                   SourceLocation StartLoc,
17001                                   SourceLocation EndLoc) {
17002   StringLiteral *AsmString = cast<StringLiteral>(expr);
17003 
17004   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
17005                                                    AsmString, StartLoc,
17006                                                    EndLoc);
17007   CurContext->addDecl(New);
17008   return New;
17009 }
17010 
17011 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
17012                                       IdentifierInfo* AliasName,
17013                                       SourceLocation PragmaLoc,
17014                                       SourceLocation NameLoc,
17015                                       SourceLocation AliasNameLoc) {
17016   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
17017                                          LookupOrdinaryName);
17018   AsmLabelAttr *Attr =
17019       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17020 
17021   // If a declaration that:
17022   // 1) declares a function or a variable
17023   // 2) has external linkage
17024   // already exists, add a label attribute to it.
17025   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17026     if (isDeclExternC(PrevDecl))
17027       PrevDecl->addAttr(Attr);
17028     else
17029       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17030           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17031   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17032   } else
17033     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17034 }
17035 
17036 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
17037                              SourceLocation PragmaLoc,
17038                              SourceLocation NameLoc) {
17039   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
17040 
17041   if (PrevDecl) {
17042     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17043   } else {
17044     (void)WeakUndeclaredIdentifiers.insert(
17045       std::pair<IdentifierInfo*,WeakInfo>
17046         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17047   }
17048 }
17049 
17050 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
17051                                 IdentifierInfo* AliasName,
17052                                 SourceLocation PragmaLoc,
17053                                 SourceLocation NameLoc,
17054                                 SourceLocation AliasNameLoc) {
17055   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
17056                                     LookupOrdinaryName);
17057   WeakInfo W = WeakInfo(Name, NameLoc);
17058 
17059   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17060     if (!PrevDecl->hasAttr<AliasAttr>())
17061       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17062         DeclApplyPragmaWeak(TUScope, ND, W);
17063   } else {
17064     (void)WeakUndeclaredIdentifiers.insert(
17065       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17066   }
17067 }
17068 
17069 Decl *Sema::getObjCDeclContext() const {
17070   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17071 }
17072