1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142 
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150 
151   default:
152     break;
153   }
154 
155   return false;
156 }
157 
158 namespace {
159 enum class UnqualifiedTypeNameLookupResult {
160   NotFound,
161   FoundNonType,
162   FoundType
163 };
164 } // end anonymous namespace
165 
166 /// \brief Tries to perform unqualified lookup of the type decls in bases for
167 /// dependent class.
168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169 /// type decl, \a FoundType if only type decls are found.
170 static UnqualifiedTypeNameLookupResult
171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
172                                 SourceLocation NameLoc,
173                                 const CXXRecordDecl *RD) {
174   if (!RD->hasDefinition())
175     return UnqualifiedTypeNameLookupResult::NotFound;
176   // Look for type decls in base classes.
177   UnqualifiedTypeNameLookupResult FoundTypeDecl =
178       UnqualifiedTypeNameLookupResult::NotFound;
179   for (const auto &Base : RD->bases()) {
180     const CXXRecordDecl *BaseRD = nullptr;
181     if (auto *BaseTT = Base.getType()->getAs<TagType>())
182       BaseRD = BaseTT->getAsCXXRecordDecl();
183     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184       // Look for type decls in dependent base classes that have known primary
185       // templates.
186       if (!TST || !TST->isDependentType())
187         continue;
188       auto *TD = TST->getTemplateName().getAsTemplateDecl();
189       if (!TD)
190         continue;
191       if (auto *BasePrimaryTemplate =
192           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194           BaseRD = BasePrimaryTemplate;
195         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
196           if (const ClassTemplatePartialSpecializationDecl *PS =
197                   CTD->findPartialSpecialization(Base.getType()))
198             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199               BaseRD = PS;
200         }
201       }
202     }
203     if (BaseRD) {
204       for (NamedDecl *ND : BaseRD->lookup(&II)) {
205         if (!isa<TypeDecl>(ND))
206           return UnqualifiedTypeNameLookupResult::FoundNonType;
207         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208       }
209       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211         case UnqualifiedTypeNameLookupResult::FoundNonType:
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         case UnqualifiedTypeNameLookupResult::FoundType:
214           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215           break;
216         case UnqualifiedTypeNameLookupResult::NotFound:
217           break;
218         }
219       }
220     }
221   }
222 
223   return FoundTypeDecl;
224 }
225 
226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
227                                                       const IdentifierInfo &II,
228                                                       SourceLocation NameLoc) {
229   // Lookup in the parent class template context, if any.
230   const CXXRecordDecl *RD = nullptr;
231   UnqualifiedTypeNameLookupResult FoundTypeDecl =
232       UnqualifiedTypeNameLookupResult::NotFound;
233   for (DeclContext *DC = S.CurContext;
234        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235        DC = DC->getParent()) {
236     // Look for type decls in dependent base classes that have known primary
237     // templates.
238     RD = dyn_cast<CXXRecordDecl>(DC);
239     if (RD && RD->getDescribedClassTemplate())
240       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241   }
242   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243     return nullptr;
244 
245   // We found some types in dependent base classes.  Recover as if the user
246   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
247   // lookup during template instantiation.
248   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249 
250   ASTContext &Context = S.Context;
251   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252                                           cast<Type>(Context.getRecordType(RD)));
253   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254 
255   CXXScopeSpec SS;
256   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257 
258   TypeLocBuilder Builder;
259   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
260   DepTL.setNameLoc(NameLoc);
261   DepTL.setElaboratedKeywordLoc(SourceLocation());
262   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264 }
265 
266 /// \brief If the identifier refers to a type name within this scope,
267 /// return the declaration of that type.
268 ///
269 /// This routine performs ordinary name lookup of the identifier II
270 /// within the given scope, with optional C++ scope specifier SS, to
271 /// determine whether the name refers to a type. If so, returns an
272 /// opaque pointer (actually a QualType) corresponding to that
273 /// type. Otherwise, returns NULL.
274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275                              Scope *S, CXXScopeSpec *SS,
276                              bool isClassName, bool HasTrailingDot,
277                              ParsedType ObjectTypePtr,
278                              bool IsCtorOrDtorName,
279                              bool WantNontrivialTypeSourceInfo,
280                              bool IsClassTemplateDeductionContext,
281                              IdentifierInfo **CorrectedII) {
282   // FIXME: Consider allowing this outside C++1z mode as an extension.
283   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
285                               !isClassName && !HasTrailingDot;
286 
287   // Determine where we will perform name lookup.
288   DeclContext *LookupCtx = nullptr;
289   if (ObjectTypePtr) {
290     QualType ObjectType = ObjectTypePtr.get();
291     if (ObjectType->isRecordType())
292       LookupCtx = computeDeclContext(ObjectType);
293   } else if (SS && SS->isNotEmpty()) {
294     LookupCtx = computeDeclContext(*SS, false);
295 
296     if (!LookupCtx) {
297       if (isDependentScopeSpecifier(*SS)) {
298         // C++ [temp.res]p3:
299         //   A qualified-id that refers to a type and in which the
300         //   nested-name-specifier depends on a template-parameter (14.6.2)
301         //   shall be prefixed by the keyword typename to indicate that the
302         //   qualified-id denotes a type, forming an
303         //   elaborated-type-specifier (7.1.5.3).
304         //
305         // We therefore do not perform any name lookup if the result would
306         // refer to a member of an unknown specialization.
307         if (!isClassName && !IsCtorOrDtorName)
308           return nullptr;
309 
310         // We know from the grammar that this name refers to a type,
311         // so build a dependent node to describe the type.
312         if (WantNontrivialTypeSourceInfo)
313           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314 
315         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317                                        II, NameLoc);
318         return ParsedType::make(T);
319       }
320 
321       return nullptr;
322     }
323 
324     if (!LookupCtx->isDependentContext() &&
325         RequireCompleteDeclContext(*SS, LookupCtx))
326       return nullptr;
327   }
328 
329   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330   // lookup for class-names.
331   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332                                       LookupOrdinaryName;
333   LookupResult Result(*this, &II, NameLoc, Kind);
334   if (LookupCtx) {
335     // Perform "qualified" name lookup into the declaration context we
336     // computed, which is either the type of the base of a member access
337     // expression or the declaration context associated with a prior
338     // nested-name-specifier.
339     LookupQualifiedName(Result, LookupCtx);
340 
341     if (ObjectTypePtr && Result.empty()) {
342       // C++ [basic.lookup.classref]p3:
343       //   If the unqualified-id is ~type-name, the type-name is looked up
344       //   in the context of the entire postfix-expression. If the type T of
345       //   the object expression is of a class type C, the type-name is also
346       //   looked up in the scope of class C. At least one of the lookups shall
347       //   find a name that refers to (possibly cv-qualified) T.
348       LookupName(Result, S);
349     }
350   } else {
351     // Perform unqualified name lookup.
352     LookupName(Result, S);
353 
354     // For unqualified lookup in a class template in MSVC mode, look into
355     // dependent base classes where the primary class template is known.
356     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357       if (ParsedType TypeInBase =
358               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359         return TypeInBase;
360     }
361   }
362 
363   NamedDecl *IIDecl = nullptr;
364   switch (Result.getResultKind()) {
365   case LookupResult::NotFound:
366   case LookupResult::NotFoundInCurrentInstantiation:
367     if (CorrectedII) {
368       TypoCorrection Correction =
369           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370                       llvm::make_unique<TypeNameValidatorCCC>(
371                           true, isClassName, AllowDeducedTemplate),
372                       CTK_ErrorRecovery);
373       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374       TemplateTy Template;
375       bool MemberOfUnknownSpecialization;
376       UnqualifiedId TemplateName;
377       TemplateName.setIdentifier(NewII, NameLoc);
378       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379       CXXScopeSpec NewSS, *NewSSPtr = SS;
380       if (SS && NNS) {
381         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382         NewSSPtr = &NewSS;
383       }
384       if (Correction && (NNS || NewII != &II) &&
385           // Ignore a correction to a template type as the to-be-corrected
386           // identifier is not a template (typo correction for template names
387           // is handled elsewhere).
388           !(getLangOpts().CPlusPlus && NewSSPtr &&
389             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390                            Template, MemberOfUnknownSpecialization))) {
391         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392                                     isClassName, HasTrailingDot, ObjectTypePtr,
393                                     IsCtorOrDtorName,
394                                     WantNontrivialTypeSourceInfo,
395                                     IsClassTemplateDeductionContext);
396         if (Ty) {
397           diagnoseTypo(Correction,
398                        PDiag(diag::err_unknown_type_or_class_name_suggest)
399                          << Result.getLookupName() << isClassName);
400           if (SS && NNS)
401             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402           *CorrectedII = NewII;
403           return Ty;
404         }
405       }
406     }
407     // If typo correction failed or was not performed, fall through
408     LLVM_FALLTHROUGH;
409   case LookupResult::FoundOverloaded:
410   case LookupResult::FoundUnresolvedValue:
411     Result.suppressDiagnostics();
412     return nullptr;
413 
414   case LookupResult::Ambiguous:
415     // Recover from type-hiding ambiguities by hiding the type.  We'll
416     // do the lookup again when looking for an object, and we can
417     // diagnose the error then.  If we don't do this, then the error
418     // about hiding the type will be immediately followed by an error
419     // that only makes sense if the identifier was treated like a type.
420     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
421       Result.suppressDiagnostics();
422       return nullptr;
423     }
424 
425     // Look to see if we have a type anywhere in the list of results.
426     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427          Res != ResEnd; ++Res) {
428       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430         if (!IIDecl ||
431             (*Res)->getLocation().getRawEncoding() <
432               IIDecl->getLocation().getRawEncoding())
433           IIDecl = *Res;
434       }
435     }
436 
437     if (!IIDecl) {
438       // None of the entities we found is a type, so there is no way
439       // to even assume that the result is a type. In this case, don't
440       // complain about the ambiguity. The parser will either try to
441       // perform this lookup again (e.g., as an object name), which
442       // will produce the ambiguity, or will complain that it expected
443       // a type name.
444       Result.suppressDiagnostics();
445       return nullptr;
446     }
447 
448     // We found a type within the ambiguous lookup; diagnose the
449     // ambiguity and then return that type. This might be the right
450     // answer, or it might not be, but it suppresses any attempt to
451     // perform the name lookup again.
452     break;
453 
454   case LookupResult::Found:
455     IIDecl = Result.getFoundDecl();
456     break;
457   }
458 
459   assert(IIDecl && "Didn't find decl");
460 
461   QualType T;
462   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463     // C++ [class.qual]p2: A lookup that would find the injected-class-name
464     // instead names the constructors of the class, except when naming a class.
465     // This is ill-formed when we're not actually forming a ctor or dtor name.
466     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469         FoundRD->isInjectedClassName() &&
470         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472           << &II << /*Type*/1;
473 
474     DiagnoseUseOfDecl(IIDecl, NameLoc);
475 
476     T = Context.getTypeDeclType(TD);
477     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480     if (!HasTrailingDot)
481       T = Context.getObjCInterfaceType(IDecl);
482   } else if (AllowDeducedTemplate) {
483     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
484       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
485                                                        QualType(), false);
486   }
487 
488   if (T.isNull()) {
489     // If it's not plausibly a type, suppress diagnostics.
490     Result.suppressDiagnostics();
491     return nullptr;
492   }
493 
494   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495   // constructor or destructor name (in such a case, the scope specifier
496   // will be attached to the enclosing Expr or Decl node).
497   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498       !isa<ObjCInterfaceDecl>(IIDecl)) {
499     if (WantNontrivialTypeSourceInfo) {
500       // Construct a type with type-source information.
501       TypeLocBuilder Builder;
502       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503 
504       T = getElaboratedType(ETK_None, *SS, T);
505       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
506       ElabTL.setElaboratedKeywordLoc(SourceLocation());
507       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509     } else {
510       T = getElaboratedType(ETK_None, *SS, T);
511     }
512   }
513 
514   return ParsedType::make(T);
515 }
516 
517 // Builds a fake NNS for the given decl context.
518 static NestedNameSpecifier *
519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
520   for (;; DC = DC->getLookupParent()) {
521     DC = DC->getPrimaryContext();
522     auto *ND = dyn_cast<NamespaceDecl>(DC);
523     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524       return NestedNameSpecifier::Create(Context, nullptr, ND);
525     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527                                          RD->getTypeForDecl());
528     else if (isa<TranslationUnitDecl>(DC))
529       return NestedNameSpecifier::GlobalSpecifier(Context);
530   }
531   llvm_unreachable("something isn't in TU scope?");
532 }
533 
534 /// Find the parent class with dependent bases of the innermost enclosing method
535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536 /// up allowing unqualified dependent type names at class-level, which MSVC
537 /// correctly rejects.
538 static const CXXRecordDecl *
539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
540   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541     DC = DC->getPrimaryContext();
542     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543       if (MD->getParent()->hasAnyDependentBases())
544         return MD->getParent();
545   }
546   return nullptr;
547 }
548 
549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
550                                           SourceLocation NameLoc,
551                                           bool IsTemplateTypeArg) {
552   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
553 
554   NestedNameSpecifier *NNS = nullptr;
555   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556     // If we weren't able to parse a default template argument, delay lookup
557     // until instantiation time by making a non-dependent DependentTypeName. We
558     // pretend we saw a NestedNameSpecifier referring to the current scope, and
559     // lookup is retried.
560     // FIXME: This hurts our diagnostic quality, since we get errors like "no
561     // type named 'Foo' in 'current_namespace'" when the user didn't write any
562     // name specifiers.
563     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565   } else if (const CXXRecordDecl *RD =
566                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
567     // Build a DependentNameType that will perform lookup into RD at
568     // instantiation time.
569     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570                                       RD->getTypeForDecl());
571 
572     // Diagnose that this identifier was undeclared, and retry the lookup during
573     // template instantiation.
574     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575                                                                       << RD;
576   } else {
577     // This is not a situation that we should recover from.
578     return ParsedType();
579   }
580 
581   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582 
583   // Build type location information.  We synthesized the qualifier, so we have
584   // to build a fake NestedNameSpecifierLoc.
585   NestedNameSpecifierLocBuilder NNSLocBuilder;
586   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588 
589   TypeLocBuilder Builder;
590   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
591   DepTL.setNameLoc(NameLoc);
592   DepTL.setElaboratedKeywordLoc(SourceLocation());
593   DepTL.setQualifierLoc(QualifierLoc);
594   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595 }
596 
597 /// isTagName() - This method is called *for error recovery purposes only*
598 /// to determine if the specified name is a valid tag name ("struct foo").  If
599 /// so, this returns the TST for the tag corresponding to it (TST_enum,
600 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
601 /// cases in C where the user forgot to specify the tag.
602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
603   // Do a tag name lookup in this scope.
604   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605   LookupName(R, S, false);
606   R.suppressDiagnostics();
607   if (R.getResultKind() == LookupResult::Found)
608     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609       switch (TD->getTagKind()) {
610       case TTK_Struct: return DeclSpec::TST_struct;
611       case TTK_Interface: return DeclSpec::TST_interface;
612       case TTK_Union:  return DeclSpec::TST_union;
613       case TTK_Class:  return DeclSpec::TST_class;
614       case TTK_Enum:   return DeclSpec::TST_enum;
615       }
616     }
617 
618   return DeclSpec::TST_unspecified;
619 }
620 
621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
623 /// then downgrade the missing typename error to a warning.
624 /// This is needed for MSVC compatibility; Example:
625 /// @code
626 /// template<class T> class A {
627 /// public:
628 ///   typedef int TYPE;
629 /// };
630 /// template<class T> class B : public A<T> {
631 /// public:
632 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
633 /// };
634 /// @endcode
635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
636   if (CurContext->isRecord()) {
637     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638       return true;
639 
640     const Type *Ty = SS->getScopeRep()->getAsType();
641 
642     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643     for (const auto &Base : RD->bases())
644       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645         return true;
646     return S->isFunctionPrototypeScope();
647   }
648   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649 }
650 
651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
652                                    SourceLocation IILoc,
653                                    Scope *S,
654                                    CXXScopeSpec *SS,
655                                    ParsedType &SuggestedType,
656                                    bool IsTemplateName) {
657   // Don't report typename errors for editor placeholders.
658   if (II->isEditorPlaceholder())
659     return;
660   // We don't have anything to suggest (yet).
661   SuggestedType = nullptr;
662 
663   // There may have been a typo in the name of the type. Look up typo
664   // results, in case we have something that we can suggest.
665   if (TypoCorrection Corrected =
666           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667                       llvm::make_unique<TypeNameValidatorCCC>(
668                           false, false, IsTemplateName, !IsTemplateName),
669                       CTK_ErrorRecovery)) {
670     // FIXME: Support error recovery for the template-name case.
671     bool CanRecover = !IsTemplateName;
672     if (Corrected.isKeyword()) {
673       // We corrected to a keyword.
674       diagnoseTypo(Corrected,
675                    PDiag(IsTemplateName ? diag::err_no_template_suggest
676                                         : diag::err_unknown_typename_suggest)
677                        << II);
678       II = Corrected.getCorrectionAsIdentifierInfo();
679     } else {
680       // We found a similarly-named type or interface; suggest that.
681       if (!SS || !SS->isSet()) {
682         diagnoseTypo(Corrected,
683                      PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                           : diag::err_unknown_typename_suggest)
685                          << II, CanRecover);
686       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689                                 II->getName().equals(CorrectedStr);
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName
692                                ? diag::err_no_member_template_suggest
693                                : diag::err_unknown_nested_typename_suggest)
694                          << II << DC << DroppedSpecifier << SS->getRange(),
695                      CanRecover);
696       } else {
697         llvm_unreachable("could not have corrected a typo here");
698       }
699 
700       if (!CanRecover)
701         return;
702 
703       CXXScopeSpec tmpSS;
704       if (Corrected.getCorrectionSpecifier())
705         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706                           SourceRange(IILoc));
707       // FIXME: Support class template argument deduction here.
708       SuggestedType =
709           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711                       /*IsCtorOrDtorName=*/false,
712                       /*NonTrivialTypeSourceInfo=*/true);
713     }
714     return;
715   }
716 
717   if (getLangOpts().CPlusPlus && !IsTemplateName) {
718     // See if II is a class template that the user forgot to pass arguments to.
719     UnqualifiedId Name;
720     Name.setIdentifier(II, IILoc);
721     CXXScopeSpec EmptySS;
722     TemplateTy TemplateResult;
723     bool MemberOfUnknownSpecialization;
724     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725                        Name, nullptr, true, TemplateResult,
726                        MemberOfUnknownSpecialization) == TNK_Type_template) {
727       TemplateName TplName = TemplateResult.get();
728       Diag(IILoc, diag::err_template_missing_args)
729         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732           << TplDecl->getTemplateParameters()->getSourceRange();
733       }
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 /// \brief 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,
851                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887 
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890 
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920 
921     // In C, we first see whether there is a tag type by the same name, in
922     // which case it's likely that the user just forgot to write "enum",
923     // "struct", or "union".
924     if (!getLangOpts().CPlusPlus && !SecondTry &&
925         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926       break;
927     }
928 
929     // Perform typo correction to determine if there is another name that is
930     // close to this name.
931     if (!SecondTry && CCC) {
932       SecondTry = true;
933       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934                                                  Result.getLookupKind(), S,
935                                                  &SS, std::move(CCC),
936                                                  CTK_ErrorRecovery)) {
937         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938         unsigned QualifiedDiag = diag::err_no_member_suggest;
939 
940         NamedDecl *FirstDecl = Corrected.getFoundDecl();
941         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944           UnqualifiedDiag = diag::err_no_template_suggest;
945           QualifiedDiag = diag::err_no_member_template_suggest;
946         } else if (UnderlyingFirstDecl &&
947                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950           UnqualifiedDiag = diag::err_unknown_typename_suggest;
951           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952         }
953 
954         if (SS.isEmpty()) {
955           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956         } else {// FIXME: is this even reachable? Test it.
957           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959                                   Name->getName().equals(CorrectedStr);
960           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961                                     << Name << computeDeclContext(SS, false)
962                                     << DroppedSpecifier << SS.getRange());
963         }
964 
965         // Update the name, so that the caller has the new name.
966         Name = Corrected.getCorrectionAsIdentifierInfo();
967 
968         // Typo correction corrected to a keyword.
969         if (Corrected.isKeyword())
970           return Name;
971 
972         // Also update the LookupResult...
973         // FIXME: This should probably go away at some point
974         Result.clear();
975         Result.setLookupName(Corrected.getCorrection());
976         if (FirstDecl)
977           Result.addDecl(FirstDecl);
978 
979         // If we found an Objective-C instance variable, let
980         // LookupInObjCMethod build the appropriate expression to
981         // reference the ivar.
982         // FIXME: This is a gross hack.
983         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984           Result.clear();
985           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986           return E;
987         }
988 
989         goto Corrected;
990       }
991     }
992 
993     // We failed to correct; just fall through and let the parser deal with it.
994     Result.suppressDiagnostics();
995     return NameClassification::Unknown();
996 
997   case LookupResult::NotFoundInCurrentInstantiation: {
998     // We performed name lookup into the current instantiation, and there were
999     // dependent bases, so we treat this result the same way as any other
1000     // dependent nested-name-specifier.
1001 
1002     // C++ [temp.res]p2:
1003     //   A name used in a template declaration or definition and that is
1004     //   dependent on a template-parameter is assumed not to name a type
1005     //   unless the applicable name lookup finds a type name or the name is
1006     //   qualified by the keyword typename.
1007     //
1008     // FIXME: If the next token is '<', we might want to ask the parser to
1009     // perform some heroics to see if we actually have a
1010     // template-argument-list, which would indicate a missing 'template'
1011     // keyword here.
1012     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013                                       NameInfo, IsAddressOfOperand,
1014                                       /*TemplateArgs=*/nullptr);
1015   }
1016 
1017   case LookupResult::Found:
1018   case LookupResult::FoundOverloaded:
1019   case LookupResult::FoundUnresolvedValue:
1020     break;
1021 
1022   case LookupResult::Ambiguous:
1023     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024         hasAnyAcceptableTemplateNames(Result)) {
1025       // C++ [temp.local]p3:
1026       //   A lookup that finds an injected-class-name (10.2) can result in an
1027       //   ambiguity in certain cases (for example, if it is found in more than
1028       //   one base class). If all of the injected-class-names that are found
1029       //   refer to specializations of the same class template, and if the name
1030       //   is followed by a template-argument-list, the reference refers to the
1031       //   class template itself and not a specialization thereof, and is not
1032       //   ambiguous.
1033       //
1034       // This filtering can make an ambiguous result into an unambiguous one,
1035       // so try again after filtering out template names.
1036       FilterAcceptableTemplateNames(Result);
1037       if (!Result.isAmbiguous()) {
1038         IsFilteredTemplateName = true;
1039         break;
1040       }
1041     }
1042 
1043     // Diagnose the ambiguity and return an error.
1044     return NameClassification::Error();
1045   }
1046 
1047   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049     // C++ [temp.names]p3:
1050     //   After name lookup (3.4) finds that a name is a template-name or that
1051     //   an operator-function-id or a literal- operator-id refers to a set of
1052     //   overloaded functions any member of which is a function template if
1053     //   this is followed by a <, the < is always taken as the delimiter of a
1054     //   template-argument-list and never as the less-than operator.
1055     if (!IsFilteredTemplateName)
1056       FilterAcceptableTemplateNames(Result);
1057 
1058     if (!Result.empty()) {
1059       bool IsFunctionTemplate;
1060       bool IsVarTemplate;
1061       TemplateName Template;
1062       if (Result.end() - Result.begin() > 1) {
1063         IsFunctionTemplate = true;
1064         Template = Context.getOverloadedTemplateName(Result.begin(),
1065                                                      Result.end());
1066       } else {
1067         TemplateDecl *TD
1068           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074                                                     /*TemplateKeyword=*/false,
1075                                                       TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// \brief Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 static bool isUsingDecl(NamedDecl *D) {
1452   return isa<UsingShadowDecl>(D) ||
1453          isa<UnresolvedUsingTypenameDecl>(D) ||
1454          isa<UnresolvedUsingValueDecl>(D);
1455 }
1456 
1457 /// Removes using shadow declarations from the lookup results.
1458 static void RemoveUsingDecls(LookupResult &R) {
1459   LookupResult::Filter F = R.makeFilter();
1460   while (F.hasNext())
1461     if (isUsingDecl(F.next()))
1462       F.erase();
1463 
1464   F.done();
1465 }
1466 
1467 /// \brief Check for this common pattern:
1468 /// @code
1469 /// class S {
1470 ///   S(const S&); // DO NOT IMPLEMENT
1471 ///   void operator=(const S&); // DO NOT IMPLEMENT
1472 /// };
1473 /// @endcode
1474 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1475   // FIXME: Should check for private access too but access is set after we get
1476   // the decl here.
1477   if (D->doesThisDeclarationHaveABody())
1478     return false;
1479 
1480   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1481     return CD->isCopyConstructor();
1482   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1483     return Method->isCopyAssignmentOperator();
1484   return false;
1485 }
1486 
1487 // We need this to handle
1488 //
1489 // typedef struct {
1490 //   void *foo() { return 0; }
1491 // } A;
1492 //
1493 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1494 // for example. If 'A', foo will have external linkage. If we have '*A',
1495 // foo will have no linkage. Since we can't know until we get to the end
1496 // of the typedef, this function finds out if D might have non-external linkage.
1497 // Callers should verify at the end of the TU if it D has external linkage or
1498 // not.
1499 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1500   const DeclContext *DC = D->getDeclContext();
1501   while (!DC->isTranslationUnit()) {
1502     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1503       if (!RD->hasNameForLinkage())
1504         return true;
1505     }
1506     DC = DC->getParent();
1507   }
1508 
1509   return !D->isExternallyVisible();
1510 }
1511 
1512 // FIXME: This needs to be refactored; some other isInMainFile users want
1513 // these semantics.
1514 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1515   if (S.TUKind != TU_Complete)
1516     return false;
1517   return S.SourceMgr.isInMainFile(Loc);
1518 }
1519 
1520 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1521   assert(D);
1522 
1523   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1524     return false;
1525 
1526   // Ignore all entities declared within templates, and out-of-line definitions
1527   // of members of class templates.
1528   if (D->getDeclContext()->isDependentContext() ||
1529       D->getLexicalDeclContext()->isDependentContext())
1530     return false;
1531 
1532   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1533     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1534       return false;
1535     // A non-out-of-line declaration of a member specialization was implicitly
1536     // instantiated; it's the out-of-line declaration that we're interested in.
1537     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1538         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1539       return false;
1540 
1541     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1542       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1543         return false;
1544     } else {
1545       // 'static inline' functions are defined in headers; don't warn.
1546       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1547         return false;
1548     }
1549 
1550     if (FD->doesThisDeclarationHaveABody() &&
1551         Context.DeclMustBeEmitted(FD))
1552       return false;
1553   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1554     // Constants and utility variables are defined in headers with internal
1555     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1556     // like "inline".)
1557     if (!isMainFileLoc(*this, VD->getLocation()))
1558       return false;
1559 
1560     if (Context.DeclMustBeEmitted(VD))
1561       return false;
1562 
1563     if (VD->isStaticDataMember() &&
1564         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1565       return false;
1566     if (VD->isStaticDataMember() &&
1567         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1568         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1569       return false;
1570 
1571     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1572       return false;
1573   } else {
1574     return false;
1575   }
1576 
1577   // Only warn for unused decls internal to the translation unit.
1578   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1579   // for inline functions defined in the main source file, for instance.
1580   return mightHaveNonExternalLinkage(D);
1581 }
1582 
1583 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1584   if (!D)
1585     return;
1586 
1587   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1588     const FunctionDecl *First = FD->getFirstDecl();
1589     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1590       return; // First should already be in the vector.
1591   }
1592 
1593   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594     const VarDecl *First = VD->getFirstDecl();
1595     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1596       return; // First should already be in the vector.
1597   }
1598 
1599   if (ShouldWarnIfUnusedFileScopedDecl(D))
1600     UnusedFileScopedDecls.push_back(D);
1601 }
1602 
1603 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1604   if (D->isInvalidDecl())
1605     return false;
1606 
1607   bool Referenced = false;
1608   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1609     // For a decomposition declaration, warn if none of the bindings are
1610     // referenced, instead of if the variable itself is referenced (which
1611     // it is, by the bindings' expressions).
1612     for (auto *BD : DD->bindings()) {
1613       if (BD->isReferenced()) {
1614         Referenced = true;
1615         break;
1616       }
1617     }
1618   } else if (!D->getDeclName()) {
1619     return false;
1620   } else if (D->isReferenced() || D->isUsed()) {
1621     Referenced = true;
1622   }
1623 
1624   if (Referenced || D->hasAttr<UnusedAttr>() ||
1625       D->hasAttr<ObjCPreciseLifetimeAttr>())
1626     return false;
1627 
1628   if (isa<LabelDecl>(D))
1629     return true;
1630 
1631   // Except for labels, we only care about unused decls that are local to
1632   // functions.
1633   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1634   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1635     // For dependent types, the diagnostic is deferred.
1636     WithinFunction =
1637         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1638   if (!WithinFunction)
1639     return false;
1640 
1641   if (isa<TypedefNameDecl>(D))
1642     return true;
1643 
1644   // White-list anything that isn't a local variable.
1645   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1646     return false;
1647 
1648   // Types of valid local variables should be complete, so this should succeed.
1649   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1650 
1651     // White-list anything with an __attribute__((unused)) type.
1652     const auto *Ty = VD->getType().getTypePtr();
1653 
1654     // Only look at the outermost level of typedef.
1655     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1656       if (TT->getDecl()->hasAttr<UnusedAttr>())
1657         return false;
1658     }
1659 
1660     // If we failed to complete the type for some reason, or if the type is
1661     // dependent, don't diagnose the variable.
1662     if (Ty->isIncompleteType() || Ty->isDependentType())
1663       return false;
1664 
1665     // Look at the element type to ensure that the warning behaviour is
1666     // consistent for both scalars and arrays.
1667     Ty = Ty->getBaseElementTypeUnsafe();
1668 
1669     if (const TagType *TT = Ty->getAs<TagType>()) {
1670       const TagDecl *Tag = TT->getDecl();
1671       if (Tag->hasAttr<UnusedAttr>())
1672         return false;
1673 
1674       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1675         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1676           return false;
1677 
1678         if (const Expr *Init = VD->getInit()) {
1679           if (const ExprWithCleanups *Cleanups =
1680                   dyn_cast<ExprWithCleanups>(Init))
1681             Init = Cleanups->getSubExpr();
1682           const CXXConstructExpr *Construct =
1683             dyn_cast<CXXConstructExpr>(Init);
1684           if (Construct && !Construct->isElidable()) {
1685             CXXConstructorDecl *CD = Construct->getConstructor();
1686             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1687               return false;
1688           }
1689         }
1690       }
1691     }
1692 
1693     // TODO: __attribute__((unused)) templates?
1694   }
1695 
1696   return true;
1697 }
1698 
1699 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1700                                      FixItHint &Hint) {
1701   if (isa<LabelDecl>(D)) {
1702     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1703                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1704     if (AfterColon.isInvalid())
1705       return;
1706     Hint = FixItHint::CreateRemoval(CharSourceRange::
1707                                     getCharRange(D->getLocStart(), AfterColon));
1708   }
1709 }
1710 
1711 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1712   if (D->getTypeForDecl()->isDependentType())
1713     return;
1714 
1715   for (auto *TmpD : D->decls()) {
1716     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1717       DiagnoseUnusedDecl(T);
1718     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1719       DiagnoseUnusedNestedTypedefs(R);
1720   }
1721 }
1722 
1723 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1724 /// unless they are marked attr(unused).
1725 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1726   if (!ShouldDiagnoseUnusedDecl(D))
1727     return;
1728 
1729   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1730     // typedefs can be referenced later on, so the diagnostics are emitted
1731     // at end-of-translation-unit.
1732     UnusedLocalTypedefNameCandidates.insert(TD);
1733     return;
1734   }
1735 
1736   FixItHint Hint;
1737   GenerateFixForUnusedDecl(D, Context, Hint);
1738 
1739   unsigned DiagID;
1740   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1741     DiagID = diag::warn_unused_exception_param;
1742   else if (isa<LabelDecl>(D))
1743     DiagID = diag::warn_unused_label;
1744   else
1745     DiagID = diag::warn_unused_variable;
1746 
1747   Diag(D->getLocation(), DiagID) << D << Hint;
1748 }
1749 
1750 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1751   // Verify that we have no forward references left.  If so, there was a goto
1752   // or address of a label taken, but no definition of it.  Label fwd
1753   // definitions are indicated with a null substmt which is also not a resolved
1754   // MS inline assembly label name.
1755   bool Diagnose = false;
1756   if (L->isMSAsmLabel())
1757     Diagnose = !L->isResolvedMSAsmLabel();
1758   else
1759     Diagnose = L->getStmt() == nullptr;
1760   if (Diagnose)
1761     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1762 }
1763 
1764 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1765   S->mergeNRVOIntoParent();
1766 
1767   if (S->decl_empty()) return;
1768   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1769          "Scope shouldn't contain decls!");
1770 
1771   for (auto *TmpD : S->decls()) {
1772     assert(TmpD && "This decl didn't get pushed??");
1773 
1774     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1775     NamedDecl *D = cast<NamedDecl>(TmpD);
1776 
1777     // Diagnose unused variables in this scope.
1778     if (!S->hasUnrecoverableErrorOccurred()) {
1779       DiagnoseUnusedDecl(D);
1780       if (const auto *RD = dyn_cast<RecordDecl>(D))
1781         DiagnoseUnusedNestedTypedefs(RD);
1782     }
1783 
1784     if (!D->getDeclName()) continue;
1785 
1786     // If this was a forward reference to a label, verify it was defined.
1787     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1788       CheckPoppedLabel(LD, *this);
1789 
1790     // Remove this name from our lexical scope, and warn on it if we haven't
1791     // already.
1792     IdResolver.RemoveDecl(D);
1793     auto ShadowI = ShadowingDecls.find(D);
1794     if (ShadowI != ShadowingDecls.end()) {
1795       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1796         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1797             << D << FD << FD->getParent();
1798         Diag(FD->getLocation(), diag::note_previous_declaration);
1799       }
1800       ShadowingDecls.erase(ShadowI);
1801     }
1802   }
1803 }
1804 
1805 /// \brief Look for an Objective-C class in the translation unit.
1806 ///
1807 /// \param Id The name of the Objective-C class we're looking for. If
1808 /// typo-correction fixes this name, the Id will be updated
1809 /// to the fixed name.
1810 ///
1811 /// \param IdLoc The location of the name in the translation unit.
1812 ///
1813 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1814 /// if there is no class with the given name.
1815 ///
1816 /// \returns The declaration of the named Objective-C class, or NULL if the
1817 /// class could not be found.
1818 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1819                                               SourceLocation IdLoc,
1820                                               bool DoTypoCorrection) {
1821   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1822   // creation from this context.
1823   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1824 
1825   if (!IDecl && DoTypoCorrection) {
1826     // Perform typo correction at the given location, but only if we
1827     // find an Objective-C class name.
1828     if (TypoCorrection C = CorrectTypo(
1829             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1830             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1831             CTK_ErrorRecovery)) {
1832       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1833       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1834       Id = IDecl->getIdentifier();
1835     }
1836   }
1837   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1838   // This routine must always return a class definition, if any.
1839   if (Def && Def->getDefinition())
1840       Def = Def->getDefinition();
1841   return Def;
1842 }
1843 
1844 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1845 /// from S, where a non-field would be declared. This routine copes
1846 /// with the difference between C and C++ scoping rules in structs and
1847 /// unions. For example, the following code is well-formed in C but
1848 /// ill-formed in C++:
1849 /// @code
1850 /// struct S6 {
1851 ///   enum { BAR } e;
1852 /// };
1853 ///
1854 /// void test_S6() {
1855 ///   struct S6 a;
1856 ///   a.e = BAR;
1857 /// }
1858 /// @endcode
1859 /// For the declaration of BAR, this routine will return a different
1860 /// scope. The scope S will be the scope of the unnamed enumeration
1861 /// within S6. In C++, this routine will return the scope associated
1862 /// with S6, because the enumeration's scope is a transparent
1863 /// context but structures can contain non-field names. In C, this
1864 /// routine will return the translation unit scope, since the
1865 /// enumeration's scope is a transparent context and structures cannot
1866 /// contain non-field names.
1867 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1868   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1869          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1870          (S->isClassScope() && !getLangOpts().CPlusPlus))
1871     S = S->getParent();
1872   return S;
1873 }
1874 
1875 /// \brief Looks up the declaration of "struct objc_super" and
1876 /// saves it for later use in building builtin declaration of
1877 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1878 /// pre-existing declaration exists no action takes place.
1879 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1880                                         IdentifierInfo *II) {
1881   if (!II->isStr("objc_msgSendSuper"))
1882     return;
1883   ASTContext &Context = ThisSema.Context;
1884 
1885   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1886                       SourceLocation(), Sema::LookupTagName);
1887   ThisSema.LookupName(Result, S);
1888   if (Result.getResultKind() == LookupResult::Found)
1889     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1890       Context.setObjCSuperType(Context.getTagDeclType(TD));
1891 }
1892 
1893 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1894   switch (Error) {
1895   case ASTContext::GE_None:
1896     return "";
1897   case ASTContext::GE_Missing_stdio:
1898     return "stdio.h";
1899   case ASTContext::GE_Missing_setjmp:
1900     return "setjmp.h";
1901   case ASTContext::GE_Missing_ucontext:
1902     return "ucontext.h";
1903   }
1904   llvm_unreachable("unhandled error kind");
1905 }
1906 
1907 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1908 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1909 /// if we're creating this built-in in anticipation of redeclaring the
1910 /// built-in.
1911 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1912                                      Scope *S, bool ForRedeclaration,
1913                                      SourceLocation Loc) {
1914   LookupPredefedObjCSuperType(*this, S, II);
1915 
1916   ASTContext::GetBuiltinTypeError Error;
1917   QualType R = Context.GetBuiltinType(ID, Error);
1918   if (Error) {
1919     if (ForRedeclaration)
1920       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1921           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1922     return nullptr;
1923   }
1924 
1925   if (!ForRedeclaration &&
1926       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1927        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1928     Diag(Loc, diag::ext_implicit_lib_function_decl)
1929         << Context.BuiltinInfo.getName(ID) << R;
1930     if (Context.BuiltinInfo.getHeaderName(ID) &&
1931         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1932       Diag(Loc, diag::note_include_header_or_declare)
1933           << Context.BuiltinInfo.getHeaderName(ID)
1934           << Context.BuiltinInfo.getName(ID);
1935   }
1936 
1937   if (R.isNull())
1938     return nullptr;
1939 
1940   DeclContext *Parent = Context.getTranslationUnitDecl();
1941   if (getLangOpts().CPlusPlus) {
1942     LinkageSpecDecl *CLinkageDecl =
1943         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1944                                 LinkageSpecDecl::lang_c, false);
1945     CLinkageDecl->setImplicit();
1946     Parent->addDecl(CLinkageDecl);
1947     Parent = CLinkageDecl;
1948   }
1949 
1950   FunctionDecl *New = FunctionDecl::Create(Context,
1951                                            Parent,
1952                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1953                                            SC_Extern,
1954                                            false,
1955                                            R->isFunctionProtoType());
1956   New->setImplicit();
1957 
1958   // Create Decl objects for each parameter, adding them to the
1959   // FunctionDecl.
1960   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1961     SmallVector<ParmVarDecl*, 16> Params;
1962     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1963       ParmVarDecl *parm =
1964           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1965                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1966                               SC_None, nullptr);
1967       parm->setScopeInfo(0, i);
1968       Params.push_back(parm);
1969     }
1970     New->setParams(Params);
1971   }
1972 
1973   AddKnownFunctionAttributes(New);
1974   RegisterLocallyScopedExternCDecl(New, S);
1975 
1976   // TUScope is the translation-unit scope to insert this function into.
1977   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1978   // relate Scopes to DeclContexts, and probably eliminate CurContext
1979   // entirely, but we're not there yet.
1980   DeclContext *SavedContext = CurContext;
1981   CurContext = Parent;
1982   PushOnScopeChains(New, TUScope);
1983   CurContext = SavedContext;
1984   return New;
1985 }
1986 
1987 /// Typedef declarations don't have linkage, but they still denote the same
1988 /// entity if their types are the same.
1989 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1990 /// isSameEntity.
1991 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1992                                                      TypedefNameDecl *Decl,
1993                                                      LookupResult &Previous) {
1994   // This is only interesting when modules are enabled.
1995   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1996     return;
1997 
1998   // Empty sets are uninteresting.
1999   if (Previous.empty())
2000     return;
2001 
2002   LookupResult::Filter Filter = Previous.makeFilter();
2003   while (Filter.hasNext()) {
2004     NamedDecl *Old = Filter.next();
2005 
2006     // Non-hidden declarations are never ignored.
2007     if (S.isVisible(Old))
2008       continue;
2009 
2010     // Declarations of the same entity are not ignored, even if they have
2011     // different linkages.
2012     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2013       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2014                                 Decl->getUnderlyingType()))
2015         continue;
2016 
2017       // If both declarations give a tag declaration a typedef name for linkage
2018       // purposes, then they declare the same entity.
2019       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2020           Decl->getAnonDeclWithTypedefName())
2021         continue;
2022     }
2023 
2024     Filter.erase();
2025   }
2026 
2027   Filter.done();
2028 }
2029 
2030 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2031   QualType OldType;
2032   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2033     OldType = OldTypedef->getUnderlyingType();
2034   else
2035     OldType = Context.getTypeDeclType(Old);
2036   QualType NewType = New->getUnderlyingType();
2037 
2038   if (NewType->isVariablyModifiedType()) {
2039     // Must not redefine a typedef with a variably-modified type.
2040     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2041     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2042       << Kind << NewType;
2043     if (Old->getLocation().isValid())
2044       notePreviousDefinition(Old, New->getLocation());
2045     New->setInvalidDecl();
2046     return true;
2047   }
2048 
2049   if (OldType != NewType &&
2050       !OldType->isDependentType() &&
2051       !NewType->isDependentType() &&
2052       !Context.hasSameType(OldType, NewType)) {
2053     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2054     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2055       << Kind << NewType << OldType;
2056     if (Old->getLocation().isValid())
2057       notePreviousDefinition(Old, New->getLocation());
2058     New->setInvalidDecl();
2059     return true;
2060   }
2061   return false;
2062 }
2063 
2064 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2065 /// same name and scope as a previous declaration 'Old'.  Figure out
2066 /// how to resolve this situation, merging decls or emitting
2067 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2068 ///
2069 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2070                                 LookupResult &OldDecls) {
2071   // If the new decl is known invalid already, don't bother doing any
2072   // merging checks.
2073   if (New->isInvalidDecl()) return;
2074 
2075   // Allow multiple definitions for ObjC built-in typedefs.
2076   // FIXME: Verify the underlying types are equivalent!
2077   if (getLangOpts().ObjC1) {
2078     const IdentifierInfo *TypeID = New->getIdentifier();
2079     switch (TypeID->getLength()) {
2080     default: break;
2081     case 2:
2082       {
2083         if (!TypeID->isStr("id"))
2084           break;
2085         QualType T = New->getUnderlyingType();
2086         if (!T->isPointerType())
2087           break;
2088         if (!T->isVoidPointerType()) {
2089           QualType PT = T->getAs<PointerType>()->getPointeeType();
2090           if (!PT->isStructureType())
2091             break;
2092         }
2093         Context.setObjCIdRedefinitionType(T);
2094         // Install the built-in type for 'id', ignoring the current definition.
2095         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2096         return;
2097       }
2098     case 5:
2099       if (!TypeID->isStr("Class"))
2100         break;
2101       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2102       // Install the built-in type for 'Class', ignoring the current definition.
2103       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2104       return;
2105     case 3:
2106       if (!TypeID->isStr("SEL"))
2107         break;
2108       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2109       // Install the built-in type for 'SEL', ignoring the current definition.
2110       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2111       return;
2112     }
2113     // Fall through - the typedef name was not a builtin type.
2114   }
2115 
2116   // Verify the old decl was also a type.
2117   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2118   if (!Old) {
2119     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2120       << New->getDeclName();
2121 
2122     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2123     if (OldD->getLocation().isValid())
2124       notePreviousDefinition(OldD, New->getLocation());
2125 
2126     return New->setInvalidDecl();
2127   }
2128 
2129   // If the old declaration is invalid, just give up here.
2130   if (Old->isInvalidDecl())
2131     return New->setInvalidDecl();
2132 
2133   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2134     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2135     auto *NewTag = New->getAnonDeclWithTypedefName();
2136     NamedDecl *Hidden = nullptr;
2137     if (OldTag && NewTag &&
2138         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2139         !hasVisibleDefinition(OldTag, &Hidden)) {
2140       // There is a definition of this tag, but it is not visible. Use it
2141       // instead of our tag.
2142       New->setTypeForDecl(OldTD->getTypeForDecl());
2143       if (OldTD->isModed())
2144         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2145                                     OldTD->getUnderlyingType());
2146       else
2147         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2148 
2149       // Make the old tag definition visible.
2150       makeMergedDefinitionVisible(Hidden);
2151 
2152       // If this was an unscoped enumeration, yank all of its enumerators
2153       // out of the scope.
2154       if (isa<EnumDecl>(NewTag)) {
2155         Scope *EnumScope = getNonFieldDeclScope(S);
2156         for (auto *D : NewTag->decls()) {
2157           auto *ED = cast<EnumConstantDecl>(D);
2158           assert(EnumScope->isDeclScope(ED));
2159           EnumScope->RemoveDecl(ED);
2160           IdResolver.RemoveDecl(ED);
2161           ED->getLexicalDeclContext()->removeDecl(ED);
2162         }
2163       }
2164     }
2165   }
2166 
2167   // If the typedef types are not identical, reject them in all languages and
2168   // with any extensions enabled.
2169   if (isIncompatibleTypedef(Old, New))
2170     return;
2171 
2172   // The types match.  Link up the redeclaration chain and merge attributes if
2173   // the old declaration was a typedef.
2174   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2175     New->setPreviousDecl(Typedef);
2176     mergeDeclAttributes(New, Old);
2177   }
2178 
2179   if (getLangOpts().MicrosoftExt)
2180     return;
2181 
2182   if (getLangOpts().CPlusPlus) {
2183     // C++ [dcl.typedef]p2:
2184     //   In a given non-class scope, a typedef specifier can be used to
2185     //   redefine the name of any type declared in that scope to refer
2186     //   to the type to which it already refers.
2187     if (!isa<CXXRecordDecl>(CurContext))
2188       return;
2189 
2190     // C++0x [dcl.typedef]p4:
2191     //   In a given class scope, a typedef specifier can be used to redefine
2192     //   any class-name declared in that scope that is not also a typedef-name
2193     //   to refer to the type to which it already refers.
2194     //
2195     // This wording came in via DR424, which was a correction to the
2196     // wording in DR56, which accidentally banned code like:
2197     //
2198     //   struct S {
2199     //     typedef struct A { } A;
2200     //   };
2201     //
2202     // in the C++03 standard. We implement the C++0x semantics, which
2203     // allow the above but disallow
2204     //
2205     //   struct S {
2206     //     typedef int I;
2207     //     typedef int I;
2208     //   };
2209     //
2210     // since that was the intent of DR56.
2211     if (!isa<TypedefNameDecl>(Old))
2212       return;
2213 
2214     Diag(New->getLocation(), diag::err_redefinition)
2215       << New->getDeclName();
2216     notePreviousDefinition(Old, New->getLocation());
2217     return New->setInvalidDecl();
2218   }
2219 
2220   // Modules always permit redefinition of typedefs, as does C11.
2221   if (getLangOpts().Modules || getLangOpts().C11)
2222     return;
2223 
2224   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2225   // is normally mapped to an error, but can be controlled with
2226   // -Wtypedef-redefinition.  If either the original or the redefinition is
2227   // in a system header, don't emit this for compatibility with GCC.
2228   if (getDiagnostics().getSuppressSystemWarnings() &&
2229       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2230       (Old->isImplicit() ||
2231        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2232        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2233     return;
2234 
2235   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2236     << New->getDeclName();
2237   notePreviousDefinition(Old, New->getLocation());
2238 }
2239 
2240 /// DeclhasAttr - returns true if decl Declaration already has the target
2241 /// attribute.
2242 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2243   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2244   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2245   for (const auto *i : D->attrs())
2246     if (i->getKind() == A->getKind()) {
2247       if (Ann) {
2248         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2249           return true;
2250         continue;
2251       }
2252       // FIXME: Don't hardcode this check
2253       if (OA && isa<OwnershipAttr>(i))
2254         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2255       return true;
2256     }
2257 
2258   return false;
2259 }
2260 
2261 static bool isAttributeTargetADefinition(Decl *D) {
2262   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2263     return VD->isThisDeclarationADefinition();
2264   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2265     return TD->isCompleteDefinition() || TD->isBeingDefined();
2266   return true;
2267 }
2268 
2269 /// Merge alignment attributes from \p Old to \p New, taking into account the
2270 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2271 ///
2272 /// \return \c true if any attributes were added to \p New.
2273 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2274   // Look for alignas attributes on Old, and pick out whichever attribute
2275   // specifies the strictest alignment requirement.
2276   AlignedAttr *OldAlignasAttr = nullptr;
2277   AlignedAttr *OldStrictestAlignAttr = nullptr;
2278   unsigned OldAlign = 0;
2279   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2280     // FIXME: We have no way of representing inherited dependent alignments
2281     // in a case like:
2282     //   template<int A, int B> struct alignas(A) X;
2283     //   template<int A, int B> struct alignas(B) X {};
2284     // For now, we just ignore any alignas attributes which are not on the
2285     // definition in such a case.
2286     if (I->isAlignmentDependent())
2287       return false;
2288 
2289     if (I->isAlignas())
2290       OldAlignasAttr = I;
2291 
2292     unsigned Align = I->getAlignment(S.Context);
2293     if (Align > OldAlign) {
2294       OldAlign = Align;
2295       OldStrictestAlignAttr = I;
2296     }
2297   }
2298 
2299   // Look for alignas attributes on New.
2300   AlignedAttr *NewAlignasAttr = nullptr;
2301   unsigned NewAlign = 0;
2302   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2303     if (I->isAlignmentDependent())
2304       return false;
2305 
2306     if (I->isAlignas())
2307       NewAlignasAttr = I;
2308 
2309     unsigned Align = I->getAlignment(S.Context);
2310     if (Align > NewAlign)
2311       NewAlign = Align;
2312   }
2313 
2314   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2315     // Both declarations have 'alignas' attributes. We require them to match.
2316     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2317     // fall short. (If two declarations both have alignas, they must both match
2318     // every definition, and so must match each other if there is a definition.)
2319 
2320     // If either declaration only contains 'alignas(0)' specifiers, then it
2321     // specifies the natural alignment for the type.
2322     if (OldAlign == 0 || NewAlign == 0) {
2323       QualType Ty;
2324       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2325         Ty = VD->getType();
2326       else
2327         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2328 
2329       if (OldAlign == 0)
2330         OldAlign = S.Context.getTypeAlign(Ty);
2331       if (NewAlign == 0)
2332         NewAlign = S.Context.getTypeAlign(Ty);
2333     }
2334 
2335     if (OldAlign != NewAlign) {
2336       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2337         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2338         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2339       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2340     }
2341   }
2342 
2343   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2344     // C++11 [dcl.align]p6:
2345     //   if any declaration of an entity has an alignment-specifier,
2346     //   every defining declaration of that entity shall specify an
2347     //   equivalent alignment.
2348     // C11 6.7.5/7:
2349     //   If the definition of an object does not have an alignment
2350     //   specifier, any other declaration of that object shall also
2351     //   have no alignment specifier.
2352     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2353       << OldAlignasAttr;
2354     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2355       << OldAlignasAttr;
2356   }
2357 
2358   bool AnyAdded = false;
2359 
2360   // Ensure we have an attribute representing the strictest alignment.
2361   if (OldAlign > NewAlign) {
2362     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2363     Clone->setInherited(true);
2364     New->addAttr(Clone);
2365     AnyAdded = true;
2366   }
2367 
2368   // Ensure we have an alignas attribute if the old declaration had one.
2369   if (OldAlignasAttr && !NewAlignasAttr &&
2370       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2371     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2372     Clone->setInherited(true);
2373     New->addAttr(Clone);
2374     AnyAdded = true;
2375   }
2376 
2377   return AnyAdded;
2378 }
2379 
2380 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2381                                const InheritableAttr *Attr,
2382                                Sema::AvailabilityMergeKind AMK) {
2383   // This function copies an attribute Attr from a previous declaration to the
2384   // new declaration D if the new declaration doesn't itself have that attribute
2385   // yet or if that attribute allows duplicates.
2386   // If you're adding a new attribute that requires logic different from
2387   // "use explicit attribute on decl if present, else use attribute from
2388   // previous decl", for example if the attribute needs to be consistent
2389   // between redeclarations, you need to call a custom merge function here.
2390   InheritableAttr *NewAttr = nullptr;
2391   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2392   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2393     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2394                                       AA->isImplicit(), AA->getIntroduced(),
2395                                       AA->getDeprecated(),
2396                                       AA->getObsoleted(), AA->getUnavailable(),
2397                                       AA->getMessage(), AA->getStrict(),
2398                                       AA->getReplacement(), AMK,
2399                                       AttrSpellingListIndex);
2400   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2401     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2402                                     AttrSpellingListIndex);
2403   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2404     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2405                                         AttrSpellingListIndex);
2406   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2407     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2408                                    AttrSpellingListIndex);
2409   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2410     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2411                                    AttrSpellingListIndex);
2412   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2413     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2414                                 FA->getFormatIdx(), FA->getFirstArg(),
2415                                 AttrSpellingListIndex);
2416   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2417     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2418                                  AttrSpellingListIndex);
2419   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2420     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2421                                        AttrSpellingListIndex,
2422                                        IA->getSemanticSpelling());
2423   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2424     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2425                                       &S.Context.Idents.get(AA->getSpelling()),
2426                                       AttrSpellingListIndex);
2427   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2428            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2429             isa<CUDAGlobalAttr>(Attr))) {
2430     // CUDA target attributes are part of function signature for
2431     // overloading purposes and must not be merged.
2432     return false;
2433   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2434     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2435   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2436     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2437   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2438     NewAttr = S.mergeInternalLinkageAttr(
2439         D, InternalLinkageA->getRange(),
2440         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2441         AttrSpellingListIndex);
2442   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2443     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2444                                 &S.Context.Idents.get(CommonA->getSpelling()),
2445                                 AttrSpellingListIndex);
2446   else if (isa<AlignedAttr>(Attr))
2447     // AlignedAttrs are handled separately, because we need to handle all
2448     // such attributes on a declaration at the same time.
2449     NewAttr = nullptr;
2450   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2451            (AMK == Sema::AMK_Override ||
2452             AMK == Sema::AMK_ProtocolImplementation))
2453     NewAttr = nullptr;
2454   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2455     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2456                               UA->getGuid());
2457   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2458     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2459 
2460   if (NewAttr) {
2461     NewAttr->setInherited(true);
2462     D->addAttr(NewAttr);
2463     if (isa<MSInheritanceAttr>(NewAttr))
2464       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2465     return true;
2466   }
2467 
2468   return false;
2469 }
2470 
2471 static const NamedDecl *getDefinition(const Decl *D) {
2472   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2473     return TD->getDefinition();
2474   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2475     const VarDecl *Def = VD->getDefinition();
2476     if (Def)
2477       return Def;
2478     return VD->getActingDefinition();
2479   }
2480   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2481     return FD->getDefinition();
2482   return nullptr;
2483 }
2484 
2485 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2486   for (const auto *Attribute : D->attrs())
2487     if (Attribute->getKind() == Kind)
2488       return true;
2489   return false;
2490 }
2491 
2492 /// checkNewAttributesAfterDef - If we already have a definition, check that
2493 /// there are no new attributes in this declaration.
2494 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2495   if (!New->hasAttrs())
2496     return;
2497 
2498   const NamedDecl *Def = getDefinition(Old);
2499   if (!Def || Def == New)
2500     return;
2501 
2502   AttrVec &NewAttributes = New->getAttrs();
2503   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2504     const Attr *NewAttribute = NewAttributes[I];
2505 
2506     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2507       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2508         Sema::SkipBodyInfo SkipBody;
2509         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2510 
2511         // If we're skipping this definition, drop the "alias" attribute.
2512         if (SkipBody.ShouldSkip) {
2513           NewAttributes.erase(NewAttributes.begin() + I);
2514           --E;
2515           continue;
2516         }
2517       } else {
2518         VarDecl *VD = cast<VarDecl>(New);
2519         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2520                                 VarDecl::TentativeDefinition
2521                             ? diag::err_alias_after_tentative
2522                             : diag::err_redefinition;
2523         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2524         if (Diag == diag::err_redefinition)
2525           S.notePreviousDefinition(Def, VD->getLocation());
2526         else
2527           S.Diag(Def->getLocation(), diag::note_previous_definition);
2528         VD->setInvalidDecl();
2529       }
2530       ++I;
2531       continue;
2532     }
2533 
2534     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2535       // Tentative definitions are only interesting for the alias check above.
2536       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2537         ++I;
2538         continue;
2539       }
2540     }
2541 
2542     if (hasAttribute(Def, NewAttribute->getKind())) {
2543       ++I;
2544       continue; // regular attr merging will take care of validating this.
2545     }
2546 
2547     if (isa<C11NoReturnAttr>(NewAttribute)) {
2548       // C's _Noreturn is allowed to be added to a function after it is defined.
2549       ++I;
2550       continue;
2551     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2552       if (AA->isAlignas()) {
2553         // C++11 [dcl.align]p6:
2554         //   if any declaration of an entity has an alignment-specifier,
2555         //   every defining declaration of that entity shall specify an
2556         //   equivalent alignment.
2557         // C11 6.7.5/7:
2558         //   If the definition of an object does not have an alignment
2559         //   specifier, any other declaration of that object shall also
2560         //   have no alignment specifier.
2561         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2562           << AA;
2563         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2564           << AA;
2565         NewAttributes.erase(NewAttributes.begin() + I);
2566         --E;
2567         continue;
2568       }
2569     }
2570 
2571     S.Diag(NewAttribute->getLocation(),
2572            diag::warn_attribute_precede_definition);
2573     S.Diag(Def->getLocation(), diag::note_previous_definition);
2574     NewAttributes.erase(NewAttributes.begin() + I);
2575     --E;
2576   }
2577 }
2578 
2579 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2580 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2581                                AvailabilityMergeKind AMK) {
2582   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2583     UsedAttr *NewAttr = OldAttr->clone(Context);
2584     NewAttr->setInherited(true);
2585     New->addAttr(NewAttr);
2586   }
2587 
2588   if (!Old->hasAttrs() && !New->hasAttrs())
2589     return;
2590 
2591   // Attributes declared post-definition are currently ignored.
2592   checkNewAttributesAfterDef(*this, New, Old);
2593 
2594   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2595     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2596       if (OldA->getLabel() != NewA->getLabel()) {
2597         // This redeclaration changes __asm__ label.
2598         Diag(New->getLocation(), diag::err_different_asm_label);
2599         Diag(OldA->getLocation(), diag::note_previous_declaration);
2600       }
2601     } else if (Old->isUsed()) {
2602       // This redeclaration adds an __asm__ label to a declaration that has
2603       // already been ODR-used.
2604       Diag(New->getLocation(), diag::err_late_asm_label_name)
2605         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2606     }
2607   }
2608 
2609   // Re-declaration cannot add abi_tag's.
2610   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2611     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2612       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2613         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2614                       NewTag) == OldAbiTagAttr->tags_end()) {
2615           Diag(NewAbiTagAttr->getLocation(),
2616                diag::err_new_abi_tag_on_redeclaration)
2617               << NewTag;
2618           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2619         }
2620       }
2621     } else {
2622       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2623       Diag(Old->getLocation(), diag::note_previous_declaration);
2624     }
2625   }
2626 
2627   // This redeclaration adds a section attribute.
2628   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2629     if (auto *VD = dyn_cast<VarDecl>(New)) {
2630       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2631         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2632         Diag(Old->getLocation(), diag::note_previous_declaration);
2633       }
2634     }
2635   }
2636 
2637   if (!Old->hasAttrs())
2638     return;
2639 
2640   bool foundAny = New->hasAttrs();
2641 
2642   // Ensure that any moving of objects within the allocated map is done before
2643   // we process them.
2644   if (!foundAny) New->setAttrs(AttrVec());
2645 
2646   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2647     // Ignore deprecated/unavailable/availability attributes if requested.
2648     AvailabilityMergeKind LocalAMK = AMK_None;
2649     if (isa<DeprecatedAttr>(I) ||
2650         isa<UnavailableAttr>(I) ||
2651         isa<AvailabilityAttr>(I)) {
2652       switch (AMK) {
2653       case AMK_None:
2654         continue;
2655 
2656       case AMK_Redeclaration:
2657       case AMK_Override:
2658       case AMK_ProtocolImplementation:
2659         LocalAMK = AMK;
2660         break;
2661       }
2662     }
2663 
2664     // Already handled.
2665     if (isa<UsedAttr>(I))
2666       continue;
2667 
2668     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2669       foundAny = true;
2670   }
2671 
2672   if (mergeAlignedAttrs(*this, New, Old))
2673     foundAny = true;
2674 
2675   if (!foundAny) New->dropAttrs();
2676 }
2677 
2678 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2679 /// to the new one.
2680 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2681                                      const ParmVarDecl *oldDecl,
2682                                      Sema &S) {
2683   // C++11 [dcl.attr.depend]p2:
2684   //   The first declaration of a function shall specify the
2685   //   carries_dependency attribute for its declarator-id if any declaration
2686   //   of the function specifies the carries_dependency attribute.
2687   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2688   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2689     S.Diag(CDA->getLocation(),
2690            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2691     // Find the first declaration of the parameter.
2692     // FIXME: Should we build redeclaration chains for function parameters?
2693     const FunctionDecl *FirstFD =
2694       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2695     const ParmVarDecl *FirstVD =
2696       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2697     S.Diag(FirstVD->getLocation(),
2698            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2699   }
2700 
2701   if (!oldDecl->hasAttrs())
2702     return;
2703 
2704   bool foundAny = newDecl->hasAttrs();
2705 
2706   // Ensure that any moving of objects within the allocated map is
2707   // done before we process them.
2708   if (!foundAny) newDecl->setAttrs(AttrVec());
2709 
2710   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2711     if (!DeclHasAttr(newDecl, I)) {
2712       InheritableAttr *newAttr =
2713         cast<InheritableParamAttr>(I->clone(S.Context));
2714       newAttr->setInherited(true);
2715       newDecl->addAttr(newAttr);
2716       foundAny = true;
2717     }
2718   }
2719 
2720   if (!foundAny) newDecl->dropAttrs();
2721 }
2722 
2723 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2724                                 const ParmVarDecl *OldParam,
2725                                 Sema &S) {
2726   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2727     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2728       if (*Oldnullability != *Newnullability) {
2729         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2730           << DiagNullabilityKind(
2731                *Newnullability,
2732                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2733                 != 0))
2734           << DiagNullabilityKind(
2735                *Oldnullability,
2736                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2737                 != 0));
2738         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2739       }
2740     } else {
2741       QualType NewT = NewParam->getType();
2742       NewT = S.Context.getAttributedType(
2743                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2744                          NewT, NewT);
2745       NewParam->setType(NewT);
2746     }
2747   }
2748 }
2749 
2750 namespace {
2751 
2752 /// Used in MergeFunctionDecl to keep track of function parameters in
2753 /// C.
2754 struct GNUCompatibleParamWarning {
2755   ParmVarDecl *OldParm;
2756   ParmVarDecl *NewParm;
2757   QualType PromotedType;
2758 };
2759 
2760 } // end anonymous namespace
2761 
2762 /// getSpecialMember - get the special member enum for a method.
2763 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2764   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2765     if (Ctor->isDefaultConstructor())
2766       return Sema::CXXDefaultConstructor;
2767 
2768     if (Ctor->isCopyConstructor())
2769       return Sema::CXXCopyConstructor;
2770 
2771     if (Ctor->isMoveConstructor())
2772       return Sema::CXXMoveConstructor;
2773   } else if (isa<CXXDestructorDecl>(MD)) {
2774     return Sema::CXXDestructor;
2775   } else if (MD->isCopyAssignmentOperator()) {
2776     return Sema::CXXCopyAssignment;
2777   } else if (MD->isMoveAssignmentOperator()) {
2778     return Sema::CXXMoveAssignment;
2779   }
2780 
2781   return Sema::CXXInvalid;
2782 }
2783 
2784 // Determine whether the previous declaration was a definition, implicit
2785 // declaration, or a declaration.
2786 template <typename T>
2787 static std::pair<diag::kind, SourceLocation>
2788 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2789   diag::kind PrevDiag;
2790   SourceLocation OldLocation = Old->getLocation();
2791   if (Old->isThisDeclarationADefinition())
2792     PrevDiag = diag::note_previous_definition;
2793   else if (Old->isImplicit()) {
2794     PrevDiag = diag::note_previous_implicit_declaration;
2795     if (OldLocation.isInvalid())
2796       OldLocation = New->getLocation();
2797   } else
2798     PrevDiag = diag::note_previous_declaration;
2799   return std::make_pair(PrevDiag, OldLocation);
2800 }
2801 
2802 /// canRedefineFunction - checks if a function can be redefined. Currently,
2803 /// only extern inline functions can be redefined, and even then only in
2804 /// GNU89 mode.
2805 static bool canRedefineFunction(const FunctionDecl *FD,
2806                                 const LangOptions& LangOpts) {
2807   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2808           !LangOpts.CPlusPlus &&
2809           FD->isInlineSpecified() &&
2810           FD->getStorageClass() == SC_Extern);
2811 }
2812 
2813 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2814   const AttributedType *AT = T->getAs<AttributedType>();
2815   while (AT && !AT->isCallingConv())
2816     AT = AT->getModifiedType()->getAs<AttributedType>();
2817   return AT;
2818 }
2819 
2820 template <typename T>
2821 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2822   const DeclContext *DC = Old->getDeclContext();
2823   if (DC->isRecord())
2824     return false;
2825 
2826   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2827   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2828     return true;
2829   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2830     return true;
2831   return false;
2832 }
2833 
2834 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2835 static bool isExternC(VarTemplateDecl *) { return false; }
2836 
2837 /// \brief Check whether a redeclaration of an entity introduced by a
2838 /// using-declaration is valid, given that we know it's not an overload
2839 /// (nor a hidden tag declaration).
2840 template<typename ExpectedDecl>
2841 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2842                                    ExpectedDecl *New) {
2843   // C++11 [basic.scope.declarative]p4:
2844   //   Given a set of declarations in a single declarative region, each of
2845   //   which specifies the same unqualified name,
2846   //   -- they shall all refer to the same entity, or all refer to functions
2847   //      and function templates; or
2848   //   -- exactly one declaration shall declare a class name or enumeration
2849   //      name that is not a typedef name and the other declarations shall all
2850   //      refer to the same variable or enumerator, or all refer to functions
2851   //      and function templates; in this case the class name or enumeration
2852   //      name is hidden (3.3.10).
2853 
2854   // C++11 [namespace.udecl]p14:
2855   //   If a function declaration in namespace scope or block scope has the
2856   //   same name and the same parameter-type-list as a function introduced
2857   //   by a using-declaration, and the declarations do not declare the same
2858   //   function, the program is ill-formed.
2859 
2860   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2861   if (Old &&
2862       !Old->getDeclContext()->getRedeclContext()->Equals(
2863           New->getDeclContext()->getRedeclContext()) &&
2864       !(isExternC(Old) && isExternC(New)))
2865     Old = nullptr;
2866 
2867   if (!Old) {
2868     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2869     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2870     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2871     return true;
2872   }
2873   return false;
2874 }
2875 
2876 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2877                                             const FunctionDecl *B) {
2878   assert(A->getNumParams() == B->getNumParams());
2879 
2880   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2881     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2882     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2883     if (AttrA == AttrB)
2884       return true;
2885     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2886   };
2887 
2888   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2889 }
2890 
2891 /// MergeFunctionDecl - We just parsed a function 'New' from
2892 /// declarator D which has the same name and scope as a previous
2893 /// declaration 'Old'.  Figure out how to resolve this situation,
2894 /// merging decls or emitting diagnostics as appropriate.
2895 ///
2896 /// In C++, New and Old must be declarations that are not
2897 /// overloaded. Use IsOverload to determine whether New and Old are
2898 /// overloaded, and to select the Old declaration that New should be
2899 /// merged with.
2900 ///
2901 /// Returns true if there was an error, false otherwise.
2902 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2903                              Scope *S, bool MergeTypeWithOld) {
2904   // Verify the old decl was also a function.
2905   FunctionDecl *Old = OldD->getAsFunction();
2906   if (!Old) {
2907     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2908       if (New->getFriendObjectKind()) {
2909         Diag(New->getLocation(), diag::err_using_decl_friend);
2910         Diag(Shadow->getTargetDecl()->getLocation(),
2911              diag::note_using_decl_target);
2912         Diag(Shadow->getUsingDecl()->getLocation(),
2913              diag::note_using_decl) << 0;
2914         return true;
2915       }
2916 
2917       // Check whether the two declarations might declare the same function.
2918       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2919         return true;
2920       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2921     } else {
2922       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2923         << New->getDeclName();
2924       notePreviousDefinition(OldD, New->getLocation());
2925       return true;
2926     }
2927   }
2928 
2929   // If the old declaration is invalid, just give up here.
2930   if (Old->isInvalidDecl())
2931     return true;
2932 
2933   diag::kind PrevDiag;
2934   SourceLocation OldLocation;
2935   std::tie(PrevDiag, OldLocation) =
2936       getNoteDiagForInvalidRedeclaration(Old, New);
2937 
2938   // Don't complain about this if we're in GNU89 mode and the old function
2939   // is an extern inline function.
2940   // Don't complain about specializations. They are not supposed to have
2941   // storage classes.
2942   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2943       New->getStorageClass() == SC_Static &&
2944       Old->hasExternalFormalLinkage() &&
2945       !New->getTemplateSpecializationInfo() &&
2946       !canRedefineFunction(Old, getLangOpts())) {
2947     if (getLangOpts().MicrosoftExt) {
2948       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2949       Diag(OldLocation, PrevDiag);
2950     } else {
2951       Diag(New->getLocation(), diag::err_static_non_static) << New;
2952       Diag(OldLocation, PrevDiag);
2953       return true;
2954     }
2955   }
2956 
2957   if (New->hasAttr<InternalLinkageAttr>() &&
2958       !Old->hasAttr<InternalLinkageAttr>()) {
2959     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2960         << New->getDeclName();
2961     notePreviousDefinition(Old, New->getLocation());
2962     New->dropAttr<InternalLinkageAttr>();
2963   }
2964 
2965   if (!getLangOpts().CPlusPlus) {
2966     bool OldOvl = Old->hasAttr<OverloadableAttr>();
2967     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
2968       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
2969         << New << OldOvl;
2970 
2971       // Try our best to find a decl that actually has the overloadable
2972       // attribute for the note. In most cases (e.g. programs with only one
2973       // broken declaration/definition), this won't matter.
2974       //
2975       // FIXME: We could do this if we juggled some extra state in
2976       // OverloadableAttr, rather than just removing it.
2977       const Decl *DiagOld = Old;
2978       if (OldOvl) {
2979         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
2980           const auto *A = D->getAttr<OverloadableAttr>();
2981           return A && !A->isImplicit();
2982         });
2983         // If we've implicitly added *all* of the overloadable attrs to this
2984         // chain, emitting a "previous redecl" note is pointless.
2985         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
2986       }
2987 
2988       if (DiagOld)
2989         Diag(DiagOld->getLocation(),
2990              diag::note_attribute_overloadable_prev_overload)
2991           << OldOvl;
2992 
2993       if (OldOvl)
2994         New->addAttr(OverloadableAttr::CreateImplicit(Context));
2995       else
2996         New->dropAttr<OverloadableAttr>();
2997     }
2998   }
2999 
3000   // If a function is first declared with a calling convention, but is later
3001   // declared or defined without one, all following decls assume the calling
3002   // convention of the first.
3003   //
3004   // It's OK if a function is first declared without a calling convention,
3005   // but is later declared or defined with the default calling convention.
3006   //
3007   // To test if either decl has an explicit calling convention, we look for
3008   // AttributedType sugar nodes on the type as written.  If they are missing or
3009   // were canonicalized away, we assume the calling convention was implicit.
3010   //
3011   // Note also that we DO NOT return at this point, because we still have
3012   // other tests to run.
3013   QualType OldQType = Context.getCanonicalType(Old->getType());
3014   QualType NewQType = Context.getCanonicalType(New->getType());
3015   const FunctionType *OldType = cast<FunctionType>(OldQType);
3016   const FunctionType *NewType = cast<FunctionType>(NewQType);
3017   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3018   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3019   bool RequiresAdjustment = false;
3020 
3021   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3022     FunctionDecl *First = Old->getFirstDecl();
3023     const FunctionType *FT =
3024         First->getType().getCanonicalType()->castAs<FunctionType>();
3025     FunctionType::ExtInfo FI = FT->getExtInfo();
3026     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3027     if (!NewCCExplicit) {
3028       // Inherit the CC from the previous declaration if it was specified
3029       // there but not here.
3030       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3031       RequiresAdjustment = true;
3032     } else {
3033       // Calling conventions aren't compatible, so complain.
3034       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3035       Diag(New->getLocation(), diag::err_cconv_change)
3036         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3037         << !FirstCCExplicit
3038         << (!FirstCCExplicit ? "" :
3039             FunctionType::getNameForCallConv(FI.getCC()));
3040 
3041       // Put the note on the first decl, since it is the one that matters.
3042       Diag(First->getLocation(), diag::note_previous_declaration);
3043       return true;
3044     }
3045   }
3046 
3047   // FIXME: diagnose the other way around?
3048   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3049     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3050     RequiresAdjustment = true;
3051   }
3052 
3053   // Merge regparm attribute.
3054   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3055       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3056     if (NewTypeInfo.getHasRegParm()) {
3057       Diag(New->getLocation(), diag::err_regparm_mismatch)
3058         << NewType->getRegParmType()
3059         << OldType->getRegParmType();
3060       Diag(OldLocation, diag::note_previous_declaration);
3061       return true;
3062     }
3063 
3064     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3065     RequiresAdjustment = true;
3066   }
3067 
3068   // Merge ns_returns_retained attribute.
3069   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3070     if (NewTypeInfo.getProducesResult()) {
3071       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3072           << "'ns_returns_retained'";
3073       Diag(OldLocation, diag::note_previous_declaration);
3074       return true;
3075     }
3076 
3077     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3078     RequiresAdjustment = true;
3079   }
3080 
3081   if (OldTypeInfo.getNoCallerSavedRegs() !=
3082       NewTypeInfo.getNoCallerSavedRegs()) {
3083     if (NewTypeInfo.getNoCallerSavedRegs()) {
3084       AnyX86NoCallerSavedRegistersAttr *Attr =
3085         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3086       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3087       Diag(OldLocation, diag::note_previous_declaration);
3088       return true;
3089     }
3090 
3091     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3092     RequiresAdjustment = true;
3093   }
3094 
3095   if (RequiresAdjustment) {
3096     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3097     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3098     New->setType(QualType(AdjustedType, 0));
3099     NewQType = Context.getCanonicalType(New->getType());
3100     NewType = cast<FunctionType>(NewQType);
3101   }
3102 
3103   // If this redeclaration makes the function inline, we may need to add it to
3104   // UndefinedButUsed.
3105   if (!Old->isInlined() && New->isInlined() &&
3106       !New->hasAttr<GNUInlineAttr>() &&
3107       !getLangOpts().GNUInline &&
3108       Old->isUsed(false) &&
3109       !Old->isDefined() && !New->isThisDeclarationADefinition())
3110     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3111                                            SourceLocation()));
3112 
3113   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3114   // about it.
3115   if (New->hasAttr<GNUInlineAttr>() &&
3116       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3117     UndefinedButUsed.erase(Old->getCanonicalDecl());
3118   }
3119 
3120   // If pass_object_size params don't match up perfectly, this isn't a valid
3121   // redeclaration.
3122   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3123       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3124     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3125         << New->getDeclName();
3126     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3127     return true;
3128   }
3129 
3130   if (getLangOpts().CPlusPlus) {
3131     // C++1z [over.load]p2
3132     //   Certain function declarations cannot be overloaded:
3133     //     -- Function declarations that differ only in the return type,
3134     //        the exception specification, or both cannot be overloaded.
3135 
3136     // Check the exception specifications match. This may recompute the type of
3137     // both Old and New if it resolved exception specifications, so grab the
3138     // types again after this. Because this updates the type, we do this before
3139     // any of the other checks below, which may update the "de facto" NewQType
3140     // but do not necessarily update the type of New.
3141     if (CheckEquivalentExceptionSpec(Old, New))
3142       return true;
3143     OldQType = Context.getCanonicalType(Old->getType());
3144     NewQType = Context.getCanonicalType(New->getType());
3145 
3146     // Go back to the type source info to compare the declared return types,
3147     // per C++1y [dcl.type.auto]p13:
3148     //   Redeclarations or specializations of a function or function template
3149     //   with a declared return type that uses a placeholder type shall also
3150     //   use that placeholder, not a deduced type.
3151     QualType OldDeclaredReturnType =
3152         (Old->getTypeSourceInfo()
3153              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3154              : OldType)->getReturnType();
3155     QualType NewDeclaredReturnType =
3156         (New->getTypeSourceInfo()
3157              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3158              : NewType)->getReturnType();
3159     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3160         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3161           New->isLocalExternDecl())) {
3162       QualType ResQT;
3163       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3164           OldDeclaredReturnType->isObjCObjectPointerType())
3165         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3166       if (ResQT.isNull()) {
3167         if (New->isCXXClassMember() && New->isOutOfLine())
3168           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3169               << New << New->getReturnTypeSourceRange();
3170         else
3171           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3172               << New->getReturnTypeSourceRange();
3173         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3174                                     << Old->getReturnTypeSourceRange();
3175         return true;
3176       }
3177       else
3178         NewQType = ResQT;
3179     }
3180 
3181     QualType OldReturnType = OldType->getReturnType();
3182     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3183     if (OldReturnType != NewReturnType) {
3184       // If this function has a deduced return type and has already been
3185       // defined, copy the deduced value from the old declaration.
3186       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3187       if (OldAT && OldAT->isDeduced()) {
3188         New->setType(
3189             SubstAutoType(New->getType(),
3190                           OldAT->isDependentType() ? Context.DependentTy
3191                                                    : OldAT->getDeducedType()));
3192         NewQType = Context.getCanonicalType(
3193             SubstAutoType(NewQType,
3194                           OldAT->isDependentType() ? Context.DependentTy
3195                                                    : OldAT->getDeducedType()));
3196       }
3197     }
3198 
3199     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3200     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3201     if (OldMethod && NewMethod) {
3202       // Preserve triviality.
3203       NewMethod->setTrivial(OldMethod->isTrivial());
3204 
3205       // MSVC allows explicit template specialization at class scope:
3206       // 2 CXXMethodDecls referring to the same function will be injected.
3207       // We don't want a redeclaration error.
3208       bool IsClassScopeExplicitSpecialization =
3209                               OldMethod->isFunctionTemplateSpecialization() &&
3210                               NewMethod->isFunctionTemplateSpecialization();
3211       bool isFriend = NewMethod->getFriendObjectKind();
3212 
3213       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3214           !IsClassScopeExplicitSpecialization) {
3215         //    -- Member function declarations with the same name and the
3216         //       same parameter types cannot be overloaded if any of them
3217         //       is a static member function declaration.
3218         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3219           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3220           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3221           return true;
3222         }
3223 
3224         // C++ [class.mem]p1:
3225         //   [...] A member shall not be declared twice in the
3226         //   member-specification, except that a nested class or member
3227         //   class template can be declared and then later defined.
3228         if (!inTemplateInstantiation()) {
3229           unsigned NewDiag;
3230           if (isa<CXXConstructorDecl>(OldMethod))
3231             NewDiag = diag::err_constructor_redeclared;
3232           else if (isa<CXXDestructorDecl>(NewMethod))
3233             NewDiag = diag::err_destructor_redeclared;
3234           else if (isa<CXXConversionDecl>(NewMethod))
3235             NewDiag = diag::err_conv_function_redeclared;
3236           else
3237             NewDiag = diag::err_member_redeclared;
3238 
3239           Diag(New->getLocation(), NewDiag);
3240         } else {
3241           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3242             << New << New->getType();
3243         }
3244         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3245         return true;
3246 
3247       // Complain if this is an explicit declaration of a special
3248       // member that was initially declared implicitly.
3249       //
3250       // As an exception, it's okay to befriend such methods in order
3251       // to permit the implicit constructor/destructor/operator calls.
3252       } else if (OldMethod->isImplicit()) {
3253         if (isFriend) {
3254           NewMethod->setImplicit();
3255         } else {
3256           Diag(NewMethod->getLocation(),
3257                diag::err_definition_of_implicitly_declared_member)
3258             << New << getSpecialMember(OldMethod);
3259           return true;
3260         }
3261       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3262         Diag(NewMethod->getLocation(),
3263              diag::err_definition_of_explicitly_defaulted_member)
3264           << getSpecialMember(OldMethod);
3265         return true;
3266       }
3267     }
3268 
3269     // C++11 [dcl.attr.noreturn]p1:
3270     //   The first declaration of a function shall specify the noreturn
3271     //   attribute if any declaration of that function specifies the noreturn
3272     //   attribute.
3273     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3274     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3275       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3276       Diag(Old->getFirstDecl()->getLocation(),
3277            diag::note_noreturn_missing_first_decl);
3278     }
3279 
3280     // C++11 [dcl.attr.depend]p2:
3281     //   The first declaration of a function shall specify the
3282     //   carries_dependency attribute for its declarator-id if any declaration
3283     //   of the function specifies the carries_dependency attribute.
3284     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3285     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3286       Diag(CDA->getLocation(),
3287            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3288       Diag(Old->getFirstDecl()->getLocation(),
3289            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3290     }
3291 
3292     // (C++98 8.3.5p3):
3293     //   All declarations for a function shall agree exactly in both the
3294     //   return type and the parameter-type-list.
3295     // We also want to respect all the extended bits except noreturn.
3296 
3297     // noreturn should now match unless the old type info didn't have it.
3298     QualType OldQTypeForComparison = OldQType;
3299     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3300       auto *OldType = OldQType->castAs<FunctionProtoType>();
3301       const FunctionType *OldTypeForComparison
3302         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3303       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3304       assert(OldQTypeForComparison.isCanonical());
3305     }
3306 
3307     if (haveIncompatibleLanguageLinkages(Old, New)) {
3308       // As a special case, retain the language linkage from previous
3309       // declarations of a friend function as an extension.
3310       //
3311       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3312       // and is useful because there's otherwise no way to specify language
3313       // linkage within class scope.
3314       //
3315       // Check cautiously as the friend object kind isn't yet complete.
3316       if (New->getFriendObjectKind() != Decl::FOK_None) {
3317         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3318         Diag(OldLocation, PrevDiag);
3319       } else {
3320         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3321         Diag(OldLocation, PrevDiag);
3322         return true;
3323       }
3324     }
3325 
3326     if (OldQTypeForComparison == NewQType)
3327       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3328 
3329     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3330         New->isLocalExternDecl()) {
3331       // It's OK if we couldn't merge types for a local function declaraton
3332       // if either the old or new type is dependent. We'll merge the types
3333       // when we instantiate the function.
3334       return false;
3335     }
3336 
3337     // Fall through for conflicting redeclarations and redefinitions.
3338   }
3339 
3340   // C: Function types need to be compatible, not identical. This handles
3341   // duplicate function decls like "void f(int); void f(enum X);" properly.
3342   if (!getLangOpts().CPlusPlus &&
3343       Context.typesAreCompatible(OldQType, NewQType)) {
3344     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3345     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3346     const FunctionProtoType *OldProto = nullptr;
3347     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3348         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3349       // The old declaration provided a function prototype, but the
3350       // new declaration does not. Merge in the prototype.
3351       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3352       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3353       NewQType =
3354           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3355                                   OldProto->getExtProtoInfo());
3356       New->setType(NewQType);
3357       New->setHasInheritedPrototype();
3358 
3359       // Synthesize parameters with the same types.
3360       SmallVector<ParmVarDecl*, 16> Params;
3361       for (const auto &ParamType : OldProto->param_types()) {
3362         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3363                                                  SourceLocation(), nullptr,
3364                                                  ParamType, /*TInfo=*/nullptr,
3365                                                  SC_None, nullptr);
3366         Param->setScopeInfo(0, Params.size());
3367         Param->setImplicit();
3368         Params.push_back(Param);
3369       }
3370 
3371       New->setParams(Params);
3372     }
3373 
3374     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3375   }
3376 
3377   // GNU C permits a K&R definition to follow a prototype declaration
3378   // if the declared types of the parameters in the K&R definition
3379   // match the types in the prototype declaration, even when the
3380   // promoted types of the parameters from the K&R definition differ
3381   // from the types in the prototype. GCC then keeps the types from
3382   // the prototype.
3383   //
3384   // If a variadic prototype is followed by a non-variadic K&R definition,
3385   // the K&R definition becomes variadic.  This is sort of an edge case, but
3386   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3387   // C99 6.9.1p8.
3388   if (!getLangOpts().CPlusPlus &&
3389       Old->hasPrototype() && !New->hasPrototype() &&
3390       New->getType()->getAs<FunctionProtoType>() &&
3391       Old->getNumParams() == New->getNumParams()) {
3392     SmallVector<QualType, 16> ArgTypes;
3393     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3394     const FunctionProtoType *OldProto
3395       = Old->getType()->getAs<FunctionProtoType>();
3396     const FunctionProtoType *NewProto
3397       = New->getType()->getAs<FunctionProtoType>();
3398 
3399     // Determine whether this is the GNU C extension.
3400     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3401                                                NewProto->getReturnType());
3402     bool LooseCompatible = !MergedReturn.isNull();
3403     for (unsigned Idx = 0, End = Old->getNumParams();
3404          LooseCompatible && Idx != End; ++Idx) {
3405       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3406       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3407       if (Context.typesAreCompatible(OldParm->getType(),
3408                                      NewProto->getParamType(Idx))) {
3409         ArgTypes.push_back(NewParm->getType());
3410       } else if (Context.typesAreCompatible(OldParm->getType(),
3411                                             NewParm->getType(),
3412                                             /*CompareUnqualified=*/true)) {
3413         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3414                                            NewProto->getParamType(Idx) };
3415         Warnings.push_back(Warn);
3416         ArgTypes.push_back(NewParm->getType());
3417       } else
3418         LooseCompatible = false;
3419     }
3420 
3421     if (LooseCompatible) {
3422       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3423         Diag(Warnings[Warn].NewParm->getLocation(),
3424              diag::ext_param_promoted_not_compatible_with_prototype)
3425           << Warnings[Warn].PromotedType
3426           << Warnings[Warn].OldParm->getType();
3427         if (Warnings[Warn].OldParm->getLocation().isValid())
3428           Diag(Warnings[Warn].OldParm->getLocation(),
3429                diag::note_previous_declaration);
3430       }
3431 
3432       if (MergeTypeWithOld)
3433         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3434                                              OldProto->getExtProtoInfo()));
3435       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3436     }
3437 
3438     // Fall through to diagnose conflicting types.
3439   }
3440 
3441   // A function that has already been declared has been redeclared or
3442   // defined with a different type; show an appropriate diagnostic.
3443 
3444   // If the previous declaration was an implicitly-generated builtin
3445   // declaration, then at the very least we should use a specialized note.
3446   unsigned BuiltinID;
3447   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3448     // If it's actually a library-defined builtin function like 'malloc'
3449     // or 'printf', just warn about the incompatible redeclaration.
3450     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3451       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3452       Diag(OldLocation, diag::note_previous_builtin_declaration)
3453         << Old << Old->getType();
3454 
3455       // If this is a global redeclaration, just forget hereafter
3456       // about the "builtin-ness" of the function.
3457       //
3458       // Doing this for local extern declarations is problematic.  If
3459       // the builtin declaration remains visible, a second invalid
3460       // local declaration will produce a hard error; if it doesn't
3461       // remain visible, a single bogus local redeclaration (which is
3462       // actually only a warning) could break all the downstream code.
3463       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3464         New->getIdentifier()->revertBuiltin();
3465 
3466       return false;
3467     }
3468 
3469     PrevDiag = diag::note_previous_builtin_declaration;
3470   }
3471 
3472   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3473   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3474   return true;
3475 }
3476 
3477 /// \brief Completes the merge of two function declarations that are
3478 /// known to be compatible.
3479 ///
3480 /// This routine handles the merging of attributes and other
3481 /// properties of function declarations from the old declaration to
3482 /// the new declaration, once we know that New is in fact a
3483 /// redeclaration of Old.
3484 ///
3485 /// \returns false
3486 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3487                                         Scope *S, bool MergeTypeWithOld) {
3488   // Merge the attributes
3489   mergeDeclAttributes(New, Old);
3490 
3491   // Merge "pure" flag.
3492   if (Old->isPure())
3493     New->setPure();
3494 
3495   // Merge "used" flag.
3496   if (Old->getMostRecentDecl()->isUsed(false))
3497     New->setIsUsed();
3498 
3499   // Merge attributes from the parameters.  These can mismatch with K&R
3500   // declarations.
3501   if (New->getNumParams() == Old->getNumParams())
3502       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3503         ParmVarDecl *NewParam = New->getParamDecl(i);
3504         ParmVarDecl *OldParam = Old->getParamDecl(i);
3505         mergeParamDeclAttributes(NewParam, OldParam, *this);
3506         mergeParamDeclTypes(NewParam, OldParam, *this);
3507       }
3508 
3509   if (getLangOpts().CPlusPlus)
3510     return MergeCXXFunctionDecl(New, Old, S);
3511 
3512   // Merge the function types so the we get the composite types for the return
3513   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3514   // was visible.
3515   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3516   if (!Merged.isNull() && MergeTypeWithOld)
3517     New->setType(Merged);
3518 
3519   return false;
3520 }
3521 
3522 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3523                                 ObjCMethodDecl *oldMethod) {
3524   // Merge the attributes, including deprecated/unavailable
3525   AvailabilityMergeKind MergeKind =
3526     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3527       ? AMK_ProtocolImplementation
3528       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3529                                                        : AMK_Override;
3530 
3531   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3532 
3533   // Merge attributes from the parameters.
3534   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3535                                        oe = oldMethod->param_end();
3536   for (ObjCMethodDecl::param_iterator
3537          ni = newMethod->param_begin(), ne = newMethod->param_end();
3538        ni != ne && oi != oe; ++ni, ++oi)
3539     mergeParamDeclAttributes(*ni, *oi, *this);
3540 
3541   CheckObjCMethodOverride(newMethod, oldMethod);
3542 }
3543 
3544 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3545   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3546 
3547   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3548          ? diag::err_redefinition_different_type
3549          : diag::err_redeclaration_different_type)
3550     << New->getDeclName() << New->getType() << Old->getType();
3551 
3552   diag::kind PrevDiag;
3553   SourceLocation OldLocation;
3554   std::tie(PrevDiag, OldLocation)
3555     = getNoteDiagForInvalidRedeclaration(Old, New);
3556   S.Diag(OldLocation, PrevDiag);
3557   New->setInvalidDecl();
3558 }
3559 
3560 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3561 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3562 /// emitting diagnostics as appropriate.
3563 ///
3564 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3565 /// to here in AddInitializerToDecl. We can't check them before the initializer
3566 /// is attached.
3567 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3568                              bool MergeTypeWithOld) {
3569   if (New->isInvalidDecl() || Old->isInvalidDecl())
3570     return;
3571 
3572   QualType MergedT;
3573   if (getLangOpts().CPlusPlus) {
3574     if (New->getType()->isUndeducedType()) {
3575       // We don't know what the new type is until the initializer is attached.
3576       return;
3577     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3578       // These could still be something that needs exception specs checked.
3579       return MergeVarDeclExceptionSpecs(New, Old);
3580     }
3581     // C++ [basic.link]p10:
3582     //   [...] the types specified by all declarations referring to a given
3583     //   object or function shall be identical, except that declarations for an
3584     //   array object can specify array types that differ by the presence or
3585     //   absence of a major array bound (8.3.4).
3586     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3587       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3588       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3589 
3590       // We are merging a variable declaration New into Old. If it has an array
3591       // bound, and that bound differs from Old's bound, we should diagnose the
3592       // mismatch.
3593       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3594         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3595              PrevVD = PrevVD->getPreviousDecl()) {
3596           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3597           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3598             continue;
3599 
3600           if (!Context.hasSameType(NewArray, PrevVDTy))
3601             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3602         }
3603       }
3604 
3605       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3606         if (Context.hasSameType(OldArray->getElementType(),
3607                                 NewArray->getElementType()))
3608           MergedT = New->getType();
3609       }
3610       // FIXME: Check visibility. New is hidden but has a complete type. If New
3611       // has no array bound, it should not inherit one from Old, if Old is not
3612       // visible.
3613       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3614         if (Context.hasSameType(OldArray->getElementType(),
3615                                 NewArray->getElementType()))
3616           MergedT = Old->getType();
3617       }
3618     }
3619     else if (New->getType()->isObjCObjectPointerType() &&
3620                Old->getType()->isObjCObjectPointerType()) {
3621       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3622                                               Old->getType());
3623     }
3624   } else {
3625     // C 6.2.7p2:
3626     //   All declarations that refer to the same object or function shall have
3627     //   compatible type.
3628     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3629   }
3630   if (MergedT.isNull()) {
3631     // It's OK if we couldn't merge types if either type is dependent, for a
3632     // block-scope variable. In other cases (static data members of class
3633     // templates, variable templates, ...), we require the types to be
3634     // equivalent.
3635     // FIXME: The C++ standard doesn't say anything about this.
3636     if ((New->getType()->isDependentType() ||
3637          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3638       // If the old type was dependent, we can't merge with it, so the new type
3639       // becomes dependent for now. We'll reproduce the original type when we
3640       // instantiate the TypeSourceInfo for the variable.
3641       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3642         New->setType(Context.DependentTy);
3643       return;
3644     }
3645     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3646   }
3647 
3648   // Don't actually update the type on the new declaration if the old
3649   // declaration was an extern declaration in a different scope.
3650   if (MergeTypeWithOld)
3651     New->setType(MergedT);
3652 }
3653 
3654 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3655                                   LookupResult &Previous) {
3656   // C11 6.2.7p4:
3657   //   For an identifier with internal or external linkage declared
3658   //   in a scope in which a prior declaration of that identifier is
3659   //   visible, if the prior declaration specifies internal or
3660   //   external linkage, the type of the identifier at the later
3661   //   declaration becomes the composite type.
3662   //
3663   // If the variable isn't visible, we do not merge with its type.
3664   if (Previous.isShadowed())
3665     return false;
3666 
3667   if (S.getLangOpts().CPlusPlus) {
3668     // C++11 [dcl.array]p3:
3669     //   If there is a preceding declaration of the entity in the same
3670     //   scope in which the bound was specified, an omitted array bound
3671     //   is taken to be the same as in that earlier declaration.
3672     return NewVD->isPreviousDeclInSameBlockScope() ||
3673            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3674             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3675   } else {
3676     // If the old declaration was function-local, don't merge with its
3677     // type unless we're in the same function.
3678     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3679            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3680   }
3681 }
3682 
3683 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3684 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3685 /// situation, merging decls or emitting diagnostics as appropriate.
3686 ///
3687 /// Tentative definition rules (C99 6.9.2p2) are checked by
3688 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3689 /// definitions here, since the initializer hasn't been attached.
3690 ///
3691 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3692   // If the new decl is already invalid, don't do any other checking.
3693   if (New->isInvalidDecl())
3694     return;
3695 
3696   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3697     return;
3698 
3699   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3700 
3701   // Verify the old decl was also a variable or variable template.
3702   VarDecl *Old = nullptr;
3703   VarTemplateDecl *OldTemplate = nullptr;
3704   if (Previous.isSingleResult()) {
3705     if (NewTemplate) {
3706       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3707       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3708 
3709       if (auto *Shadow =
3710               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3711         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3712           return New->setInvalidDecl();
3713     } else {
3714       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3715 
3716       if (auto *Shadow =
3717               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3718         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3719           return New->setInvalidDecl();
3720     }
3721   }
3722   if (!Old) {
3723     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3724         << New->getDeclName();
3725     notePreviousDefinition(Previous.getRepresentativeDecl(),
3726                            New->getLocation());
3727     return New->setInvalidDecl();
3728   }
3729 
3730   // Ensure the template parameters are compatible.
3731   if (NewTemplate &&
3732       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3733                                       OldTemplate->getTemplateParameters(),
3734                                       /*Complain=*/true, TPL_TemplateMatch))
3735     return New->setInvalidDecl();
3736 
3737   // C++ [class.mem]p1:
3738   //   A member shall not be declared twice in the member-specification [...]
3739   //
3740   // Here, we need only consider static data members.
3741   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3742     Diag(New->getLocation(), diag::err_duplicate_member)
3743       << New->getIdentifier();
3744     Diag(Old->getLocation(), diag::note_previous_declaration);
3745     New->setInvalidDecl();
3746   }
3747 
3748   mergeDeclAttributes(New, Old);
3749   // Warn if an already-declared variable is made a weak_import in a subsequent
3750   // declaration
3751   if (New->hasAttr<WeakImportAttr>() &&
3752       Old->getStorageClass() == SC_None &&
3753       !Old->hasAttr<WeakImportAttr>()) {
3754     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3755     notePreviousDefinition(Old, New->getLocation());
3756     // Remove weak_import attribute on new declaration.
3757     New->dropAttr<WeakImportAttr>();
3758   }
3759 
3760   if (New->hasAttr<InternalLinkageAttr>() &&
3761       !Old->hasAttr<InternalLinkageAttr>()) {
3762     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3763         << New->getDeclName();
3764     notePreviousDefinition(Old, New->getLocation());
3765     New->dropAttr<InternalLinkageAttr>();
3766   }
3767 
3768   // Merge the types.
3769   VarDecl *MostRecent = Old->getMostRecentDecl();
3770   if (MostRecent != Old) {
3771     MergeVarDeclTypes(New, MostRecent,
3772                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3773     if (New->isInvalidDecl())
3774       return;
3775   }
3776 
3777   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3778   if (New->isInvalidDecl())
3779     return;
3780 
3781   diag::kind PrevDiag;
3782   SourceLocation OldLocation;
3783   std::tie(PrevDiag, OldLocation) =
3784       getNoteDiagForInvalidRedeclaration(Old, New);
3785 
3786   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3787   if (New->getStorageClass() == SC_Static &&
3788       !New->isStaticDataMember() &&
3789       Old->hasExternalFormalLinkage()) {
3790     if (getLangOpts().MicrosoftExt) {
3791       Diag(New->getLocation(), diag::ext_static_non_static)
3792           << New->getDeclName();
3793       Diag(OldLocation, PrevDiag);
3794     } else {
3795       Diag(New->getLocation(), diag::err_static_non_static)
3796           << New->getDeclName();
3797       Diag(OldLocation, PrevDiag);
3798       return New->setInvalidDecl();
3799     }
3800   }
3801   // C99 6.2.2p4:
3802   //   For an identifier declared with the storage-class specifier
3803   //   extern in a scope in which a prior declaration of that
3804   //   identifier is visible,23) if the prior declaration specifies
3805   //   internal or external linkage, the linkage of the identifier at
3806   //   the later declaration is the same as the linkage specified at
3807   //   the prior declaration. If no prior declaration is visible, or
3808   //   if the prior declaration specifies no linkage, then the
3809   //   identifier has external linkage.
3810   if (New->hasExternalStorage() && Old->hasLinkage())
3811     /* Okay */;
3812   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3813            !New->isStaticDataMember() &&
3814            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3815     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3816     Diag(OldLocation, PrevDiag);
3817     return New->setInvalidDecl();
3818   }
3819 
3820   // Check if extern is followed by non-extern and vice-versa.
3821   if (New->hasExternalStorage() &&
3822       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3823     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3824     Diag(OldLocation, PrevDiag);
3825     return New->setInvalidDecl();
3826   }
3827   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3828       !New->hasExternalStorage()) {
3829     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3830     Diag(OldLocation, PrevDiag);
3831     return New->setInvalidDecl();
3832   }
3833 
3834   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3835 
3836   // FIXME: The test for external storage here seems wrong? We still
3837   // need to check for mismatches.
3838   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3839       // Don't complain about out-of-line definitions of static members.
3840       !(Old->getLexicalDeclContext()->isRecord() &&
3841         !New->getLexicalDeclContext()->isRecord())) {
3842     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3843     Diag(OldLocation, PrevDiag);
3844     return New->setInvalidDecl();
3845   }
3846 
3847   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3848     if (VarDecl *Def = Old->getDefinition()) {
3849       // C++1z [dcl.fcn.spec]p4:
3850       //   If the definition of a variable appears in a translation unit before
3851       //   its first declaration as inline, the program is ill-formed.
3852       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3853       Diag(Def->getLocation(), diag::note_previous_definition);
3854     }
3855   }
3856 
3857   // If this redeclaration makes the variable inline, we may need to add it to
3858   // UndefinedButUsed.
3859   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3860       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3861     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3862                                            SourceLocation()));
3863 
3864   if (New->getTLSKind() != Old->getTLSKind()) {
3865     if (!Old->getTLSKind()) {
3866       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3867       Diag(OldLocation, PrevDiag);
3868     } else if (!New->getTLSKind()) {
3869       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3870       Diag(OldLocation, PrevDiag);
3871     } else {
3872       // Do not allow redeclaration to change the variable between requiring
3873       // static and dynamic initialization.
3874       // FIXME: GCC allows this, but uses the TLS keyword on the first
3875       // declaration to determine the kind. Do we need to be compatible here?
3876       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3877         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3878       Diag(OldLocation, PrevDiag);
3879     }
3880   }
3881 
3882   // C++ doesn't have tentative definitions, so go right ahead and check here.
3883   if (getLangOpts().CPlusPlus &&
3884       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3885     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3886         Old->getCanonicalDecl()->isConstexpr()) {
3887       // This definition won't be a definition any more once it's been merged.
3888       Diag(New->getLocation(),
3889            diag::warn_deprecated_redundant_constexpr_static_def);
3890     } else if (VarDecl *Def = Old->getDefinition()) {
3891       if (checkVarDeclRedefinition(Def, New))
3892         return;
3893     }
3894   }
3895 
3896   if (haveIncompatibleLanguageLinkages(Old, New)) {
3897     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3898     Diag(OldLocation, PrevDiag);
3899     New->setInvalidDecl();
3900     return;
3901   }
3902 
3903   // Merge "used" flag.
3904   if (Old->getMostRecentDecl()->isUsed(false))
3905     New->setIsUsed();
3906 
3907   // Keep a chain of previous declarations.
3908   New->setPreviousDecl(Old);
3909   if (NewTemplate)
3910     NewTemplate->setPreviousDecl(OldTemplate);
3911 
3912   // Inherit access appropriately.
3913   New->setAccess(Old->getAccess());
3914   if (NewTemplate)
3915     NewTemplate->setAccess(New->getAccess());
3916 
3917   if (Old->isInline())
3918     New->setImplicitlyInline();
3919 }
3920 
3921 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3922   SourceManager &SrcMgr = getSourceManager();
3923   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3924   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3925   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3926   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3927   auto &HSI = PP.getHeaderSearchInfo();
3928   StringRef HdrFilename =
3929       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3930 
3931   auto noteFromModuleOrInclude = [&](Module *Mod,
3932                                      SourceLocation IncLoc) -> bool {
3933     // Redefinition errors with modules are common with non modular mapped
3934     // headers, example: a non-modular header H in module A that also gets
3935     // included directly in a TU. Pointing twice to the same header/definition
3936     // is confusing, try to get better diagnostics when modules is on.
3937     if (IncLoc.isValid()) {
3938       if (Mod) {
3939         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3940             << HdrFilename.str() << Mod->getFullModuleName();
3941         if (!Mod->DefinitionLoc.isInvalid())
3942           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3943               << Mod->getFullModuleName();
3944       } else {
3945         Diag(IncLoc, diag::note_redefinition_include_same_file)
3946             << HdrFilename.str();
3947       }
3948       return true;
3949     }
3950 
3951     return false;
3952   };
3953 
3954   // Is it the same file and same offset? Provide more information on why
3955   // this leads to a redefinition error.
3956   bool EmittedDiag = false;
3957   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3958     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3959     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3960     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3961     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3962 
3963     // If the header has no guards, emit a note suggesting one.
3964     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3965       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3966 
3967     if (EmittedDiag)
3968       return;
3969   }
3970 
3971   // Redefinition coming from different files or couldn't do better above.
3972   Diag(Old->getLocation(), diag::note_previous_definition);
3973 }
3974 
3975 /// We've just determined that \p Old and \p New both appear to be definitions
3976 /// of the same variable. Either diagnose or fix the problem.
3977 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3978   if (!hasVisibleDefinition(Old) &&
3979       (New->getFormalLinkage() == InternalLinkage ||
3980        New->isInline() ||
3981        New->getDescribedVarTemplate() ||
3982        New->getNumTemplateParameterLists() ||
3983        New->getDeclContext()->isDependentContext())) {
3984     // The previous definition is hidden, and multiple definitions are
3985     // permitted (in separate TUs). Demote this to a declaration.
3986     New->demoteThisDefinitionToDeclaration();
3987 
3988     // Make the canonical definition visible.
3989     if (auto *OldTD = Old->getDescribedVarTemplate())
3990       makeMergedDefinitionVisible(OldTD);
3991     makeMergedDefinitionVisible(Old);
3992     return false;
3993   } else {
3994     Diag(New->getLocation(), diag::err_redefinition) << New;
3995     notePreviousDefinition(Old, New->getLocation());
3996     New->setInvalidDecl();
3997     return true;
3998   }
3999 }
4000 
4001 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4002 /// no declarator (e.g. "struct foo;") is parsed.
4003 Decl *
4004 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4005                                  RecordDecl *&AnonRecord) {
4006   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4007                                     AnonRecord);
4008 }
4009 
4010 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4011 // disambiguate entities defined in different scopes.
4012 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4013 // compatibility.
4014 // We will pick our mangling number depending on which version of MSVC is being
4015 // targeted.
4016 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4017   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4018              ? S->getMSCurManglingNumber()
4019              : S->getMSLastManglingNumber();
4020 }
4021 
4022 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4023   if (!Context.getLangOpts().CPlusPlus)
4024     return;
4025 
4026   if (isa<CXXRecordDecl>(Tag->getParent())) {
4027     // If this tag is the direct child of a class, number it if
4028     // it is anonymous.
4029     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4030       return;
4031     MangleNumberingContext &MCtx =
4032         Context.getManglingNumberContext(Tag->getParent());
4033     Context.setManglingNumber(
4034         Tag, MCtx.getManglingNumber(
4035                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4036     return;
4037   }
4038 
4039   // If this tag isn't a direct child of a class, number it if it is local.
4040   Decl *ManglingContextDecl;
4041   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4042           Tag->getDeclContext(), ManglingContextDecl)) {
4043     Context.setManglingNumber(
4044         Tag, MCtx->getManglingNumber(
4045                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4046   }
4047 }
4048 
4049 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4050                                         TypedefNameDecl *NewTD) {
4051   if (TagFromDeclSpec->isInvalidDecl())
4052     return;
4053 
4054   // Do nothing if the tag already has a name for linkage purposes.
4055   if (TagFromDeclSpec->hasNameForLinkage())
4056     return;
4057 
4058   // A well-formed anonymous tag must always be a TUK_Definition.
4059   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4060 
4061   // The type must match the tag exactly;  no qualifiers allowed.
4062   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4063                            Context.getTagDeclType(TagFromDeclSpec))) {
4064     if (getLangOpts().CPlusPlus)
4065       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4066     return;
4067   }
4068 
4069   // If we've already computed linkage for the anonymous tag, then
4070   // adding a typedef name for the anonymous decl can change that
4071   // linkage, which might be a serious problem.  Diagnose this as
4072   // unsupported and ignore the typedef name.  TODO: we should
4073   // pursue this as a language defect and establish a formal rule
4074   // for how to handle it.
4075   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4076     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4077 
4078     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4079     tagLoc = getLocForEndOfToken(tagLoc);
4080 
4081     llvm::SmallString<40> textToInsert;
4082     textToInsert += ' ';
4083     textToInsert += NewTD->getIdentifier()->getName();
4084     Diag(tagLoc, diag::note_typedef_changes_linkage)
4085         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4086     return;
4087   }
4088 
4089   // Otherwise, set this is the anon-decl typedef for the tag.
4090   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4091 }
4092 
4093 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4094   switch (T) {
4095   case DeclSpec::TST_class:
4096     return 0;
4097   case DeclSpec::TST_struct:
4098     return 1;
4099   case DeclSpec::TST_interface:
4100     return 2;
4101   case DeclSpec::TST_union:
4102     return 3;
4103   case DeclSpec::TST_enum:
4104     return 4;
4105   default:
4106     llvm_unreachable("unexpected type specifier");
4107   }
4108 }
4109 
4110 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4111 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4112 /// parameters to cope with template friend declarations.
4113 Decl *
4114 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4115                                  MultiTemplateParamsArg TemplateParams,
4116                                  bool IsExplicitInstantiation,
4117                                  RecordDecl *&AnonRecord) {
4118   Decl *TagD = nullptr;
4119   TagDecl *Tag = nullptr;
4120   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4121       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4122       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4123       DS.getTypeSpecType() == DeclSpec::TST_union ||
4124       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4125     TagD = DS.getRepAsDecl();
4126 
4127     if (!TagD) // We probably had an error
4128       return nullptr;
4129 
4130     // Note that the above type specs guarantee that the
4131     // type rep is a Decl, whereas in many of the others
4132     // it's a Type.
4133     if (isa<TagDecl>(TagD))
4134       Tag = cast<TagDecl>(TagD);
4135     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4136       Tag = CTD->getTemplatedDecl();
4137   }
4138 
4139   if (Tag) {
4140     handleTagNumbering(Tag, S);
4141     Tag->setFreeStanding();
4142     if (Tag->isInvalidDecl())
4143       return Tag;
4144   }
4145 
4146   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4147     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4148     // or incomplete types shall not be restrict-qualified."
4149     if (TypeQuals & DeclSpec::TQ_restrict)
4150       Diag(DS.getRestrictSpecLoc(),
4151            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4152            << DS.getSourceRange();
4153   }
4154 
4155   if (DS.isInlineSpecified())
4156     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4157         << getLangOpts().CPlusPlus1z;
4158 
4159   if (DS.isConstexprSpecified()) {
4160     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4161     // and definitions of functions and variables.
4162     if (Tag)
4163       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4164           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4165     else
4166       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4167     // Don't emit warnings after this error.
4168     return TagD;
4169   }
4170 
4171   if (DS.isConceptSpecified()) {
4172     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4173     // either a function concept and its definition or a variable concept and
4174     // its initializer.
4175     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4176     return TagD;
4177   }
4178 
4179   DiagnoseFunctionSpecifiers(DS);
4180 
4181   if (DS.isFriendSpecified()) {
4182     // If we're dealing with a decl but not a TagDecl, assume that
4183     // whatever routines created it handled the friendship aspect.
4184     if (TagD && !Tag)
4185       return nullptr;
4186     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4187   }
4188 
4189   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4190   bool IsExplicitSpecialization =
4191     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4192   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4193       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4194       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4195     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4196     // nested-name-specifier unless it is an explicit instantiation
4197     // or an explicit specialization.
4198     //
4199     // FIXME: We allow class template partial specializations here too, per the
4200     // obvious intent of DR1819.
4201     //
4202     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4203     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4204         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4205     return nullptr;
4206   }
4207 
4208   // Track whether this decl-specifier declares anything.
4209   bool DeclaresAnything = true;
4210 
4211   // Handle anonymous struct definitions.
4212   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4213     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4214         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4215       if (getLangOpts().CPlusPlus ||
4216           Record->getDeclContext()->isRecord()) {
4217         // If CurContext is a DeclContext that can contain statements,
4218         // RecursiveASTVisitor won't visit the decls that
4219         // BuildAnonymousStructOrUnion() will put into CurContext.
4220         // Also store them here so that they can be part of the
4221         // DeclStmt that gets created in this case.
4222         // FIXME: Also return the IndirectFieldDecls created by
4223         // BuildAnonymousStructOr union, for the same reason?
4224         if (CurContext->isFunctionOrMethod())
4225           AnonRecord = Record;
4226         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4227                                            Context.getPrintingPolicy());
4228       }
4229 
4230       DeclaresAnything = false;
4231     }
4232   }
4233 
4234   // C11 6.7.2.1p2:
4235   //   A struct-declaration that does not declare an anonymous structure or
4236   //   anonymous union shall contain a struct-declarator-list.
4237   //
4238   // This rule also existed in C89 and C99; the grammar for struct-declaration
4239   // did not permit a struct-declaration without a struct-declarator-list.
4240   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4241       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4242     // Check for Microsoft C extension: anonymous struct/union member.
4243     // Handle 2 kinds of anonymous struct/union:
4244     //   struct STRUCT;
4245     //   union UNION;
4246     // and
4247     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4248     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4249     if ((Tag && Tag->getDeclName()) ||
4250         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4251       RecordDecl *Record = nullptr;
4252       if (Tag)
4253         Record = dyn_cast<RecordDecl>(Tag);
4254       else if (const RecordType *RT =
4255                    DS.getRepAsType().get()->getAsStructureType())
4256         Record = RT->getDecl();
4257       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4258         Record = UT->getDecl();
4259 
4260       if (Record && getLangOpts().MicrosoftExt) {
4261         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4262           << Record->isUnion() << DS.getSourceRange();
4263         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4264       }
4265 
4266       DeclaresAnything = false;
4267     }
4268   }
4269 
4270   // Skip all the checks below if we have a type error.
4271   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4272       (TagD && TagD->isInvalidDecl()))
4273     return TagD;
4274 
4275   if (getLangOpts().CPlusPlus &&
4276       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4277     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4278       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4279           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4280         DeclaresAnything = false;
4281 
4282   if (!DS.isMissingDeclaratorOk()) {
4283     // Customize diagnostic for a typedef missing a name.
4284     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4285       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4286         << DS.getSourceRange();
4287     else
4288       DeclaresAnything = false;
4289   }
4290 
4291   if (DS.isModulePrivateSpecified() &&
4292       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4293     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4294       << Tag->getTagKind()
4295       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4296 
4297   ActOnDocumentableDecl(TagD);
4298 
4299   // C 6.7/2:
4300   //   A declaration [...] shall declare at least a declarator [...], a tag,
4301   //   or the members of an enumeration.
4302   // C++ [dcl.dcl]p3:
4303   //   [If there are no declarators], and except for the declaration of an
4304   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4305   //   names into the program, or shall redeclare a name introduced by a
4306   //   previous declaration.
4307   if (!DeclaresAnything) {
4308     // In C, we allow this as a (popular) extension / bug. Don't bother
4309     // producing further diagnostics for redundant qualifiers after this.
4310     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4311     return TagD;
4312   }
4313 
4314   // C++ [dcl.stc]p1:
4315   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4316   //   init-declarator-list of the declaration shall not be empty.
4317   // C++ [dcl.fct.spec]p1:
4318   //   If a cv-qualifier appears in a decl-specifier-seq, the
4319   //   init-declarator-list of the declaration shall not be empty.
4320   //
4321   // Spurious qualifiers here appear to be valid in C.
4322   unsigned DiagID = diag::warn_standalone_specifier;
4323   if (getLangOpts().CPlusPlus)
4324     DiagID = diag::ext_standalone_specifier;
4325 
4326   // Note that a linkage-specification sets a storage class, but
4327   // 'extern "C" struct foo;' is actually valid and not theoretically
4328   // useless.
4329   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4330     if (SCS == DeclSpec::SCS_mutable)
4331       // Since mutable is not a viable storage class specifier in C, there is
4332       // no reason to treat it as an extension. Instead, diagnose as an error.
4333       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4334     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4335       Diag(DS.getStorageClassSpecLoc(), DiagID)
4336         << DeclSpec::getSpecifierName(SCS);
4337   }
4338 
4339   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4340     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4341       << DeclSpec::getSpecifierName(TSCS);
4342   if (DS.getTypeQualifiers()) {
4343     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4344       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4345     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4346       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4347     // Restrict is covered above.
4348     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4349       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4350     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4351       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4352   }
4353 
4354   // Warn about ignored type attributes, for example:
4355   // __attribute__((aligned)) struct A;
4356   // Attributes should be placed after tag to apply to type declaration.
4357   if (!DS.getAttributes().empty()) {
4358     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4359     if (TypeSpecType == DeclSpec::TST_class ||
4360         TypeSpecType == DeclSpec::TST_struct ||
4361         TypeSpecType == DeclSpec::TST_interface ||
4362         TypeSpecType == DeclSpec::TST_union ||
4363         TypeSpecType == DeclSpec::TST_enum) {
4364       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4365            attrs = attrs->getNext())
4366         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4367             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4368     }
4369   }
4370 
4371   return TagD;
4372 }
4373 
4374 /// We are trying to inject an anonymous member into the given scope;
4375 /// check if there's an existing declaration that can't be overloaded.
4376 ///
4377 /// \return true if this is a forbidden redeclaration
4378 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4379                                          Scope *S,
4380                                          DeclContext *Owner,
4381                                          DeclarationName Name,
4382                                          SourceLocation NameLoc,
4383                                          bool IsUnion) {
4384   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4385                  Sema::ForRedeclaration);
4386   if (!SemaRef.LookupName(R, S)) return false;
4387 
4388   // Pick a representative declaration.
4389   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4390   assert(PrevDecl && "Expected a non-null Decl");
4391 
4392   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4393     return false;
4394 
4395   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4396     << IsUnion << Name;
4397   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4398 
4399   return true;
4400 }
4401 
4402 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4403 /// anonymous struct or union AnonRecord into the owning context Owner
4404 /// and scope S. This routine will be invoked just after we realize
4405 /// that an unnamed union or struct is actually an anonymous union or
4406 /// struct, e.g.,
4407 ///
4408 /// @code
4409 /// union {
4410 ///   int i;
4411 ///   float f;
4412 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4413 ///    // f into the surrounding scope.x
4414 /// @endcode
4415 ///
4416 /// This routine is recursive, injecting the names of nested anonymous
4417 /// structs/unions into the owning context and scope as well.
4418 static bool
4419 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4420                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4421                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4422   bool Invalid = false;
4423 
4424   // Look every FieldDecl and IndirectFieldDecl with a name.
4425   for (auto *D : AnonRecord->decls()) {
4426     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4427         cast<NamedDecl>(D)->getDeclName()) {
4428       ValueDecl *VD = cast<ValueDecl>(D);
4429       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4430                                        VD->getLocation(),
4431                                        AnonRecord->isUnion())) {
4432         // C++ [class.union]p2:
4433         //   The names of the members of an anonymous union shall be
4434         //   distinct from the names of any other entity in the
4435         //   scope in which the anonymous union is declared.
4436         Invalid = true;
4437       } else {
4438         // C++ [class.union]p2:
4439         //   For the purpose of name lookup, after the anonymous union
4440         //   definition, the members of the anonymous union are
4441         //   considered to have been defined in the scope in which the
4442         //   anonymous union is declared.
4443         unsigned OldChainingSize = Chaining.size();
4444         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4445           Chaining.append(IF->chain_begin(), IF->chain_end());
4446         else
4447           Chaining.push_back(VD);
4448 
4449         assert(Chaining.size() >= 2);
4450         NamedDecl **NamedChain =
4451           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4452         for (unsigned i = 0; i < Chaining.size(); i++)
4453           NamedChain[i] = Chaining[i];
4454 
4455         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4456             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4457             VD->getType(), {NamedChain, Chaining.size()});
4458 
4459         for (const auto *Attr : VD->attrs())
4460           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4461 
4462         IndirectField->setAccess(AS);
4463         IndirectField->setImplicit();
4464         SemaRef.PushOnScopeChains(IndirectField, S);
4465 
4466         // That includes picking up the appropriate access specifier.
4467         if (AS != AS_none) IndirectField->setAccess(AS);
4468 
4469         Chaining.resize(OldChainingSize);
4470       }
4471     }
4472   }
4473 
4474   return Invalid;
4475 }
4476 
4477 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4478 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4479 /// illegal input values are mapped to SC_None.
4480 static StorageClass
4481 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4482   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4483   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4484          "Parser allowed 'typedef' as storage class VarDecl.");
4485   switch (StorageClassSpec) {
4486   case DeclSpec::SCS_unspecified:    return SC_None;
4487   case DeclSpec::SCS_extern:
4488     if (DS.isExternInLinkageSpec())
4489       return SC_None;
4490     return SC_Extern;
4491   case DeclSpec::SCS_static:         return SC_Static;
4492   case DeclSpec::SCS_auto:           return SC_Auto;
4493   case DeclSpec::SCS_register:       return SC_Register;
4494   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4495     // Illegal SCSs map to None: error reporting is up to the caller.
4496   case DeclSpec::SCS_mutable:        // Fall through.
4497   case DeclSpec::SCS_typedef:        return SC_None;
4498   }
4499   llvm_unreachable("unknown storage class specifier");
4500 }
4501 
4502 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4503   assert(Record->hasInClassInitializer());
4504 
4505   for (const auto *I : Record->decls()) {
4506     const auto *FD = dyn_cast<FieldDecl>(I);
4507     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4508       FD = IFD->getAnonField();
4509     if (FD && FD->hasInClassInitializer())
4510       return FD->getLocation();
4511   }
4512 
4513   llvm_unreachable("couldn't find in-class initializer");
4514 }
4515 
4516 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4517                                       SourceLocation DefaultInitLoc) {
4518   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4519     return;
4520 
4521   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4522   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4523 }
4524 
4525 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4526                                       CXXRecordDecl *AnonUnion) {
4527   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4528     return;
4529 
4530   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4531 }
4532 
4533 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4534 /// anonymous structure or union. Anonymous unions are a C++ feature
4535 /// (C++ [class.union]) and a C11 feature; anonymous structures
4536 /// are a C11 feature and GNU C++ extension.
4537 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4538                                         AccessSpecifier AS,
4539                                         RecordDecl *Record,
4540                                         const PrintingPolicy &Policy) {
4541   DeclContext *Owner = Record->getDeclContext();
4542 
4543   // Diagnose whether this anonymous struct/union is an extension.
4544   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4545     Diag(Record->getLocation(), diag::ext_anonymous_union);
4546   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4547     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4548   else if (!Record->isUnion() && !getLangOpts().C11)
4549     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4550 
4551   // C and C++ require different kinds of checks for anonymous
4552   // structs/unions.
4553   bool Invalid = false;
4554   if (getLangOpts().CPlusPlus) {
4555     const char *PrevSpec = nullptr;
4556     unsigned DiagID;
4557     if (Record->isUnion()) {
4558       // C++ [class.union]p6:
4559       //   Anonymous unions declared in a named namespace or in the
4560       //   global namespace shall be declared static.
4561       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4562           (isa<TranslationUnitDecl>(Owner) ||
4563            (isa<NamespaceDecl>(Owner) &&
4564             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4565         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4566           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4567 
4568         // Recover by adding 'static'.
4569         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4570                                PrevSpec, DiagID, Policy);
4571       }
4572       // C++ [class.union]p6:
4573       //   A storage class is not allowed in a declaration of an
4574       //   anonymous union in a class scope.
4575       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4576                isa<RecordDecl>(Owner)) {
4577         Diag(DS.getStorageClassSpecLoc(),
4578              diag::err_anonymous_union_with_storage_spec)
4579           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4580 
4581         // Recover by removing the storage specifier.
4582         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4583                                SourceLocation(),
4584                                PrevSpec, DiagID, Context.getPrintingPolicy());
4585       }
4586     }
4587 
4588     // Ignore const/volatile/restrict qualifiers.
4589     if (DS.getTypeQualifiers()) {
4590       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4591         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4592           << Record->isUnion() << "const"
4593           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4594       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4595         Diag(DS.getVolatileSpecLoc(),
4596              diag::ext_anonymous_struct_union_qualified)
4597           << Record->isUnion() << "volatile"
4598           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4599       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4600         Diag(DS.getRestrictSpecLoc(),
4601              diag::ext_anonymous_struct_union_qualified)
4602           << Record->isUnion() << "restrict"
4603           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4604       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4605         Diag(DS.getAtomicSpecLoc(),
4606              diag::ext_anonymous_struct_union_qualified)
4607           << Record->isUnion() << "_Atomic"
4608           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4609       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4610         Diag(DS.getUnalignedSpecLoc(),
4611              diag::ext_anonymous_struct_union_qualified)
4612           << Record->isUnion() << "__unaligned"
4613           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4614 
4615       DS.ClearTypeQualifiers();
4616     }
4617 
4618     // C++ [class.union]p2:
4619     //   The member-specification of an anonymous union shall only
4620     //   define non-static data members. [Note: nested types and
4621     //   functions cannot be declared within an anonymous union. ]
4622     for (auto *Mem : Record->decls()) {
4623       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4624         // C++ [class.union]p3:
4625         //   An anonymous union shall not have private or protected
4626         //   members (clause 11).
4627         assert(FD->getAccess() != AS_none);
4628         if (FD->getAccess() != AS_public) {
4629           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4630             << Record->isUnion() << (FD->getAccess() == AS_protected);
4631           Invalid = true;
4632         }
4633 
4634         // C++ [class.union]p1
4635         //   An object of a class with a non-trivial constructor, a non-trivial
4636         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4637         //   assignment operator cannot be a member of a union, nor can an
4638         //   array of such objects.
4639         if (CheckNontrivialField(FD))
4640           Invalid = true;
4641       } else if (Mem->isImplicit()) {
4642         // Any implicit members are fine.
4643       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4644         // This is a type that showed up in an
4645         // elaborated-type-specifier inside the anonymous struct or
4646         // union, but which actually declares a type outside of the
4647         // anonymous struct or union. It's okay.
4648       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4649         if (!MemRecord->isAnonymousStructOrUnion() &&
4650             MemRecord->getDeclName()) {
4651           // Visual C++ allows type definition in anonymous struct or union.
4652           if (getLangOpts().MicrosoftExt)
4653             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4654               << Record->isUnion();
4655           else {
4656             // This is a nested type declaration.
4657             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4658               << Record->isUnion();
4659             Invalid = true;
4660           }
4661         } else {
4662           // This is an anonymous type definition within another anonymous type.
4663           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4664           // not part of standard C++.
4665           Diag(MemRecord->getLocation(),
4666                diag::ext_anonymous_record_with_anonymous_type)
4667             << Record->isUnion();
4668         }
4669       } else if (isa<AccessSpecDecl>(Mem)) {
4670         // Any access specifier is fine.
4671       } else if (isa<StaticAssertDecl>(Mem)) {
4672         // In C++1z, static_assert declarations are also fine.
4673       } else {
4674         // We have something that isn't a non-static data
4675         // member. Complain about it.
4676         unsigned DK = diag::err_anonymous_record_bad_member;
4677         if (isa<TypeDecl>(Mem))
4678           DK = diag::err_anonymous_record_with_type;
4679         else if (isa<FunctionDecl>(Mem))
4680           DK = diag::err_anonymous_record_with_function;
4681         else if (isa<VarDecl>(Mem))
4682           DK = diag::err_anonymous_record_with_static;
4683 
4684         // Visual C++ allows type definition in anonymous struct or union.
4685         if (getLangOpts().MicrosoftExt &&
4686             DK == diag::err_anonymous_record_with_type)
4687           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4688             << Record->isUnion();
4689         else {
4690           Diag(Mem->getLocation(), DK) << Record->isUnion();
4691           Invalid = true;
4692         }
4693       }
4694     }
4695 
4696     // C++11 [class.union]p8 (DR1460):
4697     //   At most one variant member of a union may have a
4698     //   brace-or-equal-initializer.
4699     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4700         Owner->isRecord())
4701       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4702                                 cast<CXXRecordDecl>(Record));
4703   }
4704 
4705   if (!Record->isUnion() && !Owner->isRecord()) {
4706     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4707       << getLangOpts().CPlusPlus;
4708     Invalid = true;
4709   }
4710 
4711   // Mock up a declarator.
4712   Declarator Dc(DS, Declarator::MemberContext);
4713   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4714   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4715 
4716   // Create a declaration for this anonymous struct/union.
4717   NamedDecl *Anon = nullptr;
4718   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4719     Anon = FieldDecl::Create(Context, OwningClass,
4720                              DS.getLocStart(),
4721                              Record->getLocation(),
4722                              /*IdentifierInfo=*/nullptr,
4723                              Context.getTypeDeclType(Record),
4724                              TInfo,
4725                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4726                              /*InitStyle=*/ICIS_NoInit);
4727     Anon->setAccess(AS);
4728     if (getLangOpts().CPlusPlus)
4729       FieldCollector->Add(cast<FieldDecl>(Anon));
4730   } else {
4731     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4732     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4733     if (SCSpec == DeclSpec::SCS_mutable) {
4734       // mutable can only appear on non-static class members, so it's always
4735       // an error here
4736       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4737       Invalid = true;
4738       SC = SC_None;
4739     }
4740 
4741     Anon = VarDecl::Create(Context, Owner,
4742                            DS.getLocStart(),
4743                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4744                            Context.getTypeDeclType(Record),
4745                            TInfo, SC);
4746 
4747     // Default-initialize the implicit variable. This initialization will be
4748     // trivial in almost all cases, except if a union member has an in-class
4749     // initializer:
4750     //   union { int n = 0; };
4751     ActOnUninitializedDecl(Anon);
4752   }
4753   Anon->setImplicit();
4754 
4755   // Mark this as an anonymous struct/union type.
4756   Record->setAnonymousStructOrUnion(true);
4757 
4758   // Add the anonymous struct/union object to the current
4759   // context. We'll be referencing this object when we refer to one of
4760   // its members.
4761   Owner->addDecl(Anon);
4762 
4763   // Inject the members of the anonymous struct/union into the owning
4764   // context and into the identifier resolver chain for name lookup
4765   // purposes.
4766   SmallVector<NamedDecl*, 2> Chain;
4767   Chain.push_back(Anon);
4768 
4769   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4770     Invalid = true;
4771 
4772   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4773     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4774       Decl *ManglingContextDecl;
4775       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4776               NewVD->getDeclContext(), ManglingContextDecl)) {
4777         Context.setManglingNumber(
4778             NewVD, MCtx->getManglingNumber(
4779                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4780         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4781       }
4782     }
4783   }
4784 
4785   if (Invalid)
4786     Anon->setInvalidDecl();
4787 
4788   return Anon;
4789 }
4790 
4791 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4792 /// Microsoft C anonymous structure.
4793 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4794 /// Example:
4795 ///
4796 /// struct A { int a; };
4797 /// struct B { struct A; int b; };
4798 ///
4799 /// void foo() {
4800 ///   B var;
4801 ///   var.a = 3;
4802 /// }
4803 ///
4804 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4805                                            RecordDecl *Record) {
4806   assert(Record && "expected a record!");
4807 
4808   // Mock up a declarator.
4809   Declarator Dc(DS, Declarator::TypeNameContext);
4810   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4811   assert(TInfo && "couldn't build declarator info for anonymous struct");
4812 
4813   auto *ParentDecl = cast<RecordDecl>(CurContext);
4814   QualType RecTy = Context.getTypeDeclType(Record);
4815 
4816   // Create a declaration for this anonymous struct.
4817   NamedDecl *Anon = FieldDecl::Create(Context,
4818                              ParentDecl,
4819                              DS.getLocStart(),
4820                              DS.getLocStart(),
4821                              /*IdentifierInfo=*/nullptr,
4822                              RecTy,
4823                              TInfo,
4824                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4825                              /*InitStyle=*/ICIS_NoInit);
4826   Anon->setImplicit();
4827 
4828   // Add the anonymous struct object to the current context.
4829   CurContext->addDecl(Anon);
4830 
4831   // Inject the members of the anonymous struct into the current
4832   // context and into the identifier resolver chain for name lookup
4833   // purposes.
4834   SmallVector<NamedDecl*, 2> Chain;
4835   Chain.push_back(Anon);
4836 
4837   RecordDecl *RecordDef = Record->getDefinition();
4838   if (RequireCompleteType(Anon->getLocation(), RecTy,
4839                           diag::err_field_incomplete) ||
4840       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4841                                           AS_none, Chain)) {
4842     Anon->setInvalidDecl();
4843     ParentDecl->setInvalidDecl();
4844   }
4845 
4846   return Anon;
4847 }
4848 
4849 /// GetNameForDeclarator - Determine the full declaration name for the
4850 /// given Declarator.
4851 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4852   return GetNameFromUnqualifiedId(D.getName());
4853 }
4854 
4855 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4856 DeclarationNameInfo
4857 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4858   DeclarationNameInfo NameInfo;
4859   NameInfo.setLoc(Name.StartLocation);
4860 
4861   switch (Name.getKind()) {
4862 
4863   case UnqualifiedId::IK_ImplicitSelfParam:
4864   case UnqualifiedId::IK_Identifier:
4865     NameInfo.setName(Name.Identifier);
4866     NameInfo.setLoc(Name.StartLocation);
4867     return NameInfo;
4868 
4869   case UnqualifiedId::IK_DeductionGuideName: {
4870     // C++ [temp.deduct.guide]p3:
4871     //   The simple-template-id shall name a class template specialization.
4872     //   The template-name shall be the same identifier as the template-name
4873     //   of the simple-template-id.
4874     // These together intend to imply that the template-name shall name a
4875     // class template.
4876     // FIXME: template<typename T> struct X {};
4877     //        template<typename T> using Y = X<T>;
4878     //        Y(int) -> Y<int>;
4879     //   satisfies these rules but does not name a class template.
4880     TemplateName TN = Name.TemplateName.get().get();
4881     auto *Template = TN.getAsTemplateDecl();
4882     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4883       Diag(Name.StartLocation,
4884            diag::err_deduction_guide_name_not_class_template)
4885         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4886       if (Template)
4887         Diag(Template->getLocation(), diag::note_template_decl_here);
4888       return DeclarationNameInfo();
4889     }
4890 
4891     NameInfo.setName(
4892         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4893     NameInfo.setLoc(Name.StartLocation);
4894     return NameInfo;
4895   }
4896 
4897   case UnqualifiedId::IK_OperatorFunctionId:
4898     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4899                                            Name.OperatorFunctionId.Operator));
4900     NameInfo.setLoc(Name.StartLocation);
4901     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4902       = Name.OperatorFunctionId.SymbolLocations[0];
4903     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4904       = Name.EndLocation.getRawEncoding();
4905     return NameInfo;
4906 
4907   case UnqualifiedId::IK_LiteralOperatorId:
4908     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4909                                                            Name.Identifier));
4910     NameInfo.setLoc(Name.StartLocation);
4911     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4912     return NameInfo;
4913 
4914   case UnqualifiedId::IK_ConversionFunctionId: {
4915     TypeSourceInfo *TInfo;
4916     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4917     if (Ty.isNull())
4918       return DeclarationNameInfo();
4919     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4920                                                Context.getCanonicalType(Ty)));
4921     NameInfo.setLoc(Name.StartLocation);
4922     NameInfo.setNamedTypeInfo(TInfo);
4923     return NameInfo;
4924   }
4925 
4926   case UnqualifiedId::IK_ConstructorName: {
4927     TypeSourceInfo *TInfo;
4928     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4929     if (Ty.isNull())
4930       return DeclarationNameInfo();
4931     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4932                                               Context.getCanonicalType(Ty)));
4933     NameInfo.setLoc(Name.StartLocation);
4934     NameInfo.setNamedTypeInfo(TInfo);
4935     return NameInfo;
4936   }
4937 
4938   case UnqualifiedId::IK_ConstructorTemplateId: {
4939     // In well-formed code, we can only have a constructor
4940     // template-id that refers to the current context, so go there
4941     // to find the actual type being constructed.
4942     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4943     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4944       return DeclarationNameInfo();
4945 
4946     // Determine the type of the class being constructed.
4947     QualType CurClassType = Context.getTypeDeclType(CurClass);
4948 
4949     // FIXME: Check two things: that the template-id names the same type as
4950     // CurClassType, and that the template-id does not occur when the name
4951     // was qualified.
4952 
4953     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4954                                     Context.getCanonicalType(CurClassType)));
4955     NameInfo.setLoc(Name.StartLocation);
4956     // FIXME: should we retrieve TypeSourceInfo?
4957     NameInfo.setNamedTypeInfo(nullptr);
4958     return NameInfo;
4959   }
4960 
4961   case UnqualifiedId::IK_DestructorName: {
4962     TypeSourceInfo *TInfo;
4963     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4964     if (Ty.isNull())
4965       return DeclarationNameInfo();
4966     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4967                                               Context.getCanonicalType(Ty)));
4968     NameInfo.setLoc(Name.StartLocation);
4969     NameInfo.setNamedTypeInfo(TInfo);
4970     return NameInfo;
4971   }
4972 
4973   case UnqualifiedId::IK_TemplateId: {
4974     TemplateName TName = Name.TemplateId->Template.get();
4975     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4976     return Context.getNameForTemplate(TName, TNameLoc);
4977   }
4978 
4979   } // switch (Name.getKind())
4980 
4981   llvm_unreachable("Unknown name kind");
4982 }
4983 
4984 static QualType getCoreType(QualType Ty) {
4985   do {
4986     if (Ty->isPointerType() || Ty->isReferenceType())
4987       Ty = Ty->getPointeeType();
4988     else if (Ty->isArrayType())
4989       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4990     else
4991       return Ty.withoutLocalFastQualifiers();
4992   } while (true);
4993 }
4994 
4995 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4996 /// and Definition have "nearly" matching parameters. This heuristic is
4997 /// used to improve diagnostics in the case where an out-of-line function
4998 /// definition doesn't match any declaration within the class or namespace.
4999 /// Also sets Params to the list of indices to the parameters that differ
5000 /// between the declaration and the definition. If hasSimilarParameters
5001 /// returns true and Params is empty, then all of the parameters match.
5002 static bool hasSimilarParameters(ASTContext &Context,
5003                                      FunctionDecl *Declaration,
5004                                      FunctionDecl *Definition,
5005                                      SmallVectorImpl<unsigned> &Params) {
5006   Params.clear();
5007   if (Declaration->param_size() != Definition->param_size())
5008     return false;
5009   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5010     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5011     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5012 
5013     // The parameter types are identical
5014     if (Context.hasSameType(DefParamTy, DeclParamTy))
5015       continue;
5016 
5017     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5018     QualType DefParamBaseTy = getCoreType(DefParamTy);
5019     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5020     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5021 
5022     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5023         (DeclTyName && DeclTyName == DefTyName))
5024       Params.push_back(Idx);
5025     else  // The two parameters aren't even close
5026       return false;
5027   }
5028 
5029   return true;
5030 }
5031 
5032 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5033 /// declarator needs to be rebuilt in the current instantiation.
5034 /// Any bits of declarator which appear before the name are valid for
5035 /// consideration here.  That's specifically the type in the decl spec
5036 /// and the base type in any member-pointer chunks.
5037 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5038                                                     DeclarationName Name) {
5039   // The types we specifically need to rebuild are:
5040   //   - typenames, typeofs, and decltypes
5041   //   - types which will become injected class names
5042   // Of course, we also need to rebuild any type referencing such a
5043   // type.  It's safest to just say "dependent", but we call out a
5044   // few cases here.
5045 
5046   DeclSpec &DS = D.getMutableDeclSpec();
5047   switch (DS.getTypeSpecType()) {
5048   case DeclSpec::TST_typename:
5049   case DeclSpec::TST_typeofType:
5050   case DeclSpec::TST_underlyingType:
5051   case DeclSpec::TST_atomic: {
5052     // Grab the type from the parser.
5053     TypeSourceInfo *TSI = nullptr;
5054     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5055     if (T.isNull() || !T->isDependentType()) break;
5056 
5057     // Make sure there's a type source info.  This isn't really much
5058     // of a waste; most dependent types should have type source info
5059     // attached already.
5060     if (!TSI)
5061       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5062 
5063     // Rebuild the type in the current instantiation.
5064     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5065     if (!TSI) return true;
5066 
5067     // Store the new type back in the decl spec.
5068     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5069     DS.UpdateTypeRep(LocType);
5070     break;
5071   }
5072 
5073   case DeclSpec::TST_decltype:
5074   case DeclSpec::TST_typeofExpr: {
5075     Expr *E = DS.getRepAsExpr();
5076     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5077     if (Result.isInvalid()) return true;
5078     DS.UpdateExprRep(Result.get());
5079     break;
5080   }
5081 
5082   default:
5083     // Nothing to do for these decl specs.
5084     break;
5085   }
5086 
5087   // It doesn't matter what order we do this in.
5088   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5089     DeclaratorChunk &Chunk = D.getTypeObject(I);
5090 
5091     // The only type information in the declarator which can come
5092     // before the declaration name is the base type of a member
5093     // pointer.
5094     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5095       continue;
5096 
5097     // Rebuild the scope specifier in-place.
5098     CXXScopeSpec &SS = Chunk.Mem.Scope();
5099     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5100       return true;
5101   }
5102 
5103   return false;
5104 }
5105 
5106 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5107   D.setFunctionDefinitionKind(FDK_Declaration);
5108   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5109 
5110   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5111       Dcl && Dcl->getDeclContext()->isFileContext())
5112     Dcl->setTopLevelDeclInObjCContainer();
5113 
5114   if (getLangOpts().OpenCL)
5115     setCurrentOpenCLExtensionForDecl(Dcl);
5116 
5117   return Dcl;
5118 }
5119 
5120 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5121 ///   If T is the name of a class, then each of the following shall have a
5122 ///   name different from T:
5123 ///     - every static data member of class T;
5124 ///     - every member function of class T
5125 ///     - every member of class T that is itself a type;
5126 /// \returns true if the declaration name violates these rules.
5127 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5128                                    DeclarationNameInfo NameInfo) {
5129   DeclarationName Name = NameInfo.getName();
5130 
5131   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5132   while (Record && Record->isAnonymousStructOrUnion())
5133     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5134   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5135     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5136     return true;
5137   }
5138 
5139   return false;
5140 }
5141 
5142 /// \brief Diagnose a declaration whose declarator-id has the given
5143 /// nested-name-specifier.
5144 ///
5145 /// \param SS The nested-name-specifier of the declarator-id.
5146 ///
5147 /// \param DC The declaration context to which the nested-name-specifier
5148 /// resolves.
5149 ///
5150 /// \param Name The name of the entity being declared.
5151 ///
5152 /// \param Loc The location of the name of the entity being declared.
5153 ///
5154 /// \returns true if we cannot safely recover from this error, false otherwise.
5155 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5156                                         DeclarationName Name,
5157                                         SourceLocation Loc) {
5158   DeclContext *Cur = CurContext;
5159   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5160     Cur = Cur->getParent();
5161 
5162   // If the user provided a superfluous scope specifier that refers back to the
5163   // class in which the entity is already declared, diagnose and ignore it.
5164   //
5165   // class X {
5166   //   void X::f();
5167   // };
5168   //
5169   // Note, it was once ill-formed to give redundant qualification in all
5170   // contexts, but that rule was removed by DR482.
5171   if (Cur->Equals(DC)) {
5172     if (Cur->isRecord()) {
5173       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5174                                       : diag::err_member_extra_qualification)
5175         << Name << FixItHint::CreateRemoval(SS.getRange());
5176       SS.clear();
5177     } else {
5178       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5179     }
5180     return false;
5181   }
5182 
5183   // Check whether the qualifying scope encloses the scope of the original
5184   // declaration.
5185   if (!Cur->Encloses(DC)) {
5186     if (Cur->isRecord())
5187       Diag(Loc, diag::err_member_qualification)
5188         << Name << SS.getRange();
5189     else if (isa<TranslationUnitDecl>(DC))
5190       Diag(Loc, diag::err_invalid_declarator_global_scope)
5191         << Name << SS.getRange();
5192     else if (isa<FunctionDecl>(Cur))
5193       Diag(Loc, diag::err_invalid_declarator_in_function)
5194         << Name << SS.getRange();
5195     else if (isa<BlockDecl>(Cur))
5196       Diag(Loc, diag::err_invalid_declarator_in_block)
5197         << Name << SS.getRange();
5198     else
5199       Diag(Loc, diag::err_invalid_declarator_scope)
5200       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5201 
5202     return true;
5203   }
5204 
5205   if (Cur->isRecord()) {
5206     // Cannot qualify members within a class.
5207     Diag(Loc, diag::err_member_qualification)
5208       << Name << SS.getRange();
5209     SS.clear();
5210 
5211     // C++ constructors and destructors with incorrect scopes can break
5212     // our AST invariants by having the wrong underlying types. If
5213     // that's the case, then drop this declaration entirely.
5214     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5215          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5216         !Context.hasSameType(Name.getCXXNameType(),
5217                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5218       return true;
5219 
5220     return false;
5221   }
5222 
5223   // C++11 [dcl.meaning]p1:
5224   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5225   //   not begin with a decltype-specifer"
5226   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5227   while (SpecLoc.getPrefix())
5228     SpecLoc = SpecLoc.getPrefix();
5229   if (dyn_cast_or_null<DecltypeType>(
5230         SpecLoc.getNestedNameSpecifier()->getAsType()))
5231     Diag(Loc, diag::err_decltype_in_declarator)
5232       << SpecLoc.getTypeLoc().getSourceRange();
5233 
5234   return false;
5235 }
5236 
5237 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5238                                   MultiTemplateParamsArg TemplateParamLists) {
5239   // TODO: consider using NameInfo for diagnostic.
5240   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5241   DeclarationName Name = NameInfo.getName();
5242 
5243   // All of these full declarators require an identifier.  If it doesn't have
5244   // one, the ParsedFreeStandingDeclSpec action should be used.
5245   if (D.isDecompositionDeclarator()) {
5246     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5247   } else if (!Name) {
5248     if (!D.isInvalidType())  // Reject this if we think it is valid.
5249       Diag(D.getDeclSpec().getLocStart(),
5250            diag::err_declarator_need_ident)
5251         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5252     return nullptr;
5253   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5254     return nullptr;
5255 
5256   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5257   // we find one that is.
5258   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5259          (S->getFlags() & Scope::TemplateParamScope) != 0)
5260     S = S->getParent();
5261 
5262   DeclContext *DC = CurContext;
5263   if (D.getCXXScopeSpec().isInvalid())
5264     D.setInvalidType();
5265   else if (D.getCXXScopeSpec().isSet()) {
5266     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5267                                         UPPC_DeclarationQualifier))
5268       return nullptr;
5269 
5270     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5271     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5272     if (!DC || isa<EnumDecl>(DC)) {
5273       // If we could not compute the declaration context, it's because the
5274       // declaration context is dependent but does not refer to a class,
5275       // class template, or class template partial specialization. Complain
5276       // and return early, to avoid the coming semantic disaster.
5277       Diag(D.getIdentifierLoc(),
5278            diag::err_template_qualified_declarator_no_match)
5279         << D.getCXXScopeSpec().getScopeRep()
5280         << D.getCXXScopeSpec().getRange();
5281       return nullptr;
5282     }
5283     bool IsDependentContext = DC->isDependentContext();
5284 
5285     if (!IsDependentContext &&
5286         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5287       return nullptr;
5288 
5289     // If a class is incomplete, do not parse entities inside it.
5290     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5291       Diag(D.getIdentifierLoc(),
5292            diag::err_member_def_undefined_record)
5293         << Name << DC << D.getCXXScopeSpec().getRange();
5294       return nullptr;
5295     }
5296     if (!D.getDeclSpec().isFriendSpecified()) {
5297       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5298                                       Name, D.getIdentifierLoc())) {
5299         if (DC->isRecord())
5300           return nullptr;
5301 
5302         D.setInvalidType();
5303       }
5304     }
5305 
5306     // Check whether we need to rebuild the type of the given
5307     // declaration in the current instantiation.
5308     if (EnteringContext && IsDependentContext &&
5309         TemplateParamLists.size() != 0) {
5310       ContextRAII SavedContext(*this, DC);
5311       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5312         D.setInvalidType();
5313     }
5314   }
5315 
5316   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5317   QualType R = TInfo->getType();
5318 
5319   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5320                                       UPPC_DeclarationType))
5321     D.setInvalidType();
5322 
5323   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5324                         ForRedeclaration);
5325 
5326   // See if this is a redefinition of a variable in the same scope.
5327   if (!D.getCXXScopeSpec().isSet()) {
5328     bool IsLinkageLookup = false;
5329     bool CreateBuiltins = false;
5330 
5331     // If the declaration we're planning to build will be a function
5332     // or object with linkage, then look for another declaration with
5333     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5334     //
5335     // If the declaration we're planning to build will be declared with
5336     // external linkage in the translation unit, create any builtin with
5337     // the same name.
5338     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5339       /* Do nothing*/;
5340     else if (CurContext->isFunctionOrMethod() &&
5341              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5342               R->isFunctionType())) {
5343       IsLinkageLookup = true;
5344       CreateBuiltins =
5345           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5346     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5347                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5348       CreateBuiltins = true;
5349 
5350     if (IsLinkageLookup)
5351       Previous.clear(LookupRedeclarationWithLinkage);
5352 
5353     LookupName(Previous, S, CreateBuiltins);
5354   } else { // Something like "int foo::x;"
5355     LookupQualifiedName(Previous, DC);
5356 
5357     // C++ [dcl.meaning]p1:
5358     //   When the declarator-id is qualified, the declaration shall refer to a
5359     //  previously declared member of the class or namespace to which the
5360     //  qualifier refers (or, in the case of a namespace, of an element of the
5361     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5362     //  thereof; [...]
5363     //
5364     // Note that we already checked the context above, and that we do not have
5365     // enough information to make sure that Previous contains the declaration
5366     // we want to match. For example, given:
5367     //
5368     //   class X {
5369     //     void f();
5370     //     void f(float);
5371     //   };
5372     //
5373     //   void X::f(int) { } // ill-formed
5374     //
5375     // In this case, Previous will point to the overload set
5376     // containing the two f's declared in X, but neither of them
5377     // matches.
5378 
5379     // C++ [dcl.meaning]p1:
5380     //   [...] the member shall not merely have been introduced by a
5381     //   using-declaration in the scope of the class or namespace nominated by
5382     //   the nested-name-specifier of the declarator-id.
5383     RemoveUsingDecls(Previous);
5384   }
5385 
5386   if (Previous.isSingleResult() &&
5387       Previous.getFoundDecl()->isTemplateParameter()) {
5388     // Maybe we will complain about the shadowed template parameter.
5389     if (!D.isInvalidType())
5390       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5391                                       Previous.getFoundDecl());
5392 
5393     // Just pretend that we didn't see the previous declaration.
5394     Previous.clear();
5395   }
5396 
5397   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5398     // Forget that the previous declaration is the injected-class-name.
5399     Previous.clear();
5400 
5401   // In C++, the previous declaration we find might be a tag type
5402   // (class or enum). In this case, the new declaration will hide the
5403   // tag type. Note that this applies to functions, function templates, and
5404   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5405   if (Previous.isSingleTagDecl() &&
5406       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5407       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5408     Previous.clear();
5409 
5410   // Check that there are no default arguments other than in the parameters
5411   // of a function declaration (C++ only).
5412   if (getLangOpts().CPlusPlus)
5413     CheckExtraCXXDefaultArguments(D);
5414 
5415   if (D.getDeclSpec().isConceptSpecified()) {
5416     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5417     // applied only to the definition of a function template or variable
5418     // template, declared in namespace scope
5419     if (!TemplateParamLists.size()) {
5420       Diag(D.getDeclSpec().getConceptSpecLoc(),
5421            diag:: err_concept_wrong_decl_kind);
5422       return nullptr;
5423     }
5424 
5425     if (!DC->getRedeclContext()->isFileContext()) {
5426       Diag(D.getIdentifierLoc(),
5427            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5428       return nullptr;
5429     }
5430   }
5431 
5432   NamedDecl *New;
5433 
5434   bool AddToScope = true;
5435   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5436     if (TemplateParamLists.size()) {
5437       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5438       return nullptr;
5439     }
5440 
5441     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5442   } else if (R->isFunctionType()) {
5443     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5444                                   TemplateParamLists,
5445                                   AddToScope);
5446   } else {
5447     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5448                                   AddToScope);
5449   }
5450 
5451   if (!New)
5452     return nullptr;
5453 
5454   // If this has an identifier and is not a function template specialization,
5455   // add it to the scope stack.
5456   if (New->getDeclName() && AddToScope) {
5457     // Only make a locally-scoped extern declaration visible if it is the first
5458     // declaration of this entity. Qualified lookup for such an entity should
5459     // only find this declaration if there is no visible declaration of it.
5460     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5461     PushOnScopeChains(New, S, AddToContext);
5462     if (!AddToContext)
5463       CurContext->addHiddenDecl(New);
5464   }
5465 
5466   if (isInOpenMPDeclareTargetContext())
5467     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5468 
5469   return New;
5470 }
5471 
5472 /// Helper method to turn variable array types into constant array
5473 /// types in certain situations which would otherwise be errors (for
5474 /// GCC compatibility).
5475 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5476                                                     ASTContext &Context,
5477                                                     bool &SizeIsNegative,
5478                                                     llvm::APSInt &Oversized) {
5479   // This method tries to turn a variable array into a constant
5480   // array even when the size isn't an ICE.  This is necessary
5481   // for compatibility with code that depends on gcc's buggy
5482   // constant expression folding, like struct {char x[(int)(char*)2];}
5483   SizeIsNegative = false;
5484   Oversized = 0;
5485 
5486   if (T->isDependentType())
5487     return QualType();
5488 
5489   QualifierCollector Qs;
5490   const Type *Ty = Qs.strip(T);
5491 
5492   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5493     QualType Pointee = PTy->getPointeeType();
5494     QualType FixedType =
5495         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5496                                             Oversized);
5497     if (FixedType.isNull()) return FixedType;
5498     FixedType = Context.getPointerType(FixedType);
5499     return Qs.apply(Context, FixedType);
5500   }
5501   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5502     QualType Inner = PTy->getInnerType();
5503     QualType FixedType =
5504         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5505                                             Oversized);
5506     if (FixedType.isNull()) return FixedType;
5507     FixedType = Context.getParenType(FixedType);
5508     return Qs.apply(Context, FixedType);
5509   }
5510 
5511   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5512   if (!VLATy)
5513     return QualType();
5514   // FIXME: We should probably handle this case
5515   if (VLATy->getElementType()->isVariablyModifiedType())
5516     return QualType();
5517 
5518   llvm::APSInt Res;
5519   if (!VLATy->getSizeExpr() ||
5520       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5521     return QualType();
5522 
5523   // Check whether the array size is negative.
5524   if (Res.isSigned() && Res.isNegative()) {
5525     SizeIsNegative = true;
5526     return QualType();
5527   }
5528 
5529   // Check whether the array is too large to be addressed.
5530   unsigned ActiveSizeBits
5531     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5532                                               Res);
5533   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5534     Oversized = Res;
5535     return QualType();
5536   }
5537 
5538   return Context.getConstantArrayType(VLATy->getElementType(),
5539                                       Res, ArrayType::Normal, 0);
5540 }
5541 
5542 static void
5543 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5544   SrcTL = SrcTL.getUnqualifiedLoc();
5545   DstTL = DstTL.getUnqualifiedLoc();
5546   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5547     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5548     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5549                                       DstPTL.getPointeeLoc());
5550     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5551     return;
5552   }
5553   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5554     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5555     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5556                                       DstPTL.getInnerLoc());
5557     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5558     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5559     return;
5560   }
5561   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5562   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5563   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5564   TypeLoc DstElemTL = DstATL.getElementLoc();
5565   DstElemTL.initializeFullCopy(SrcElemTL);
5566   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5567   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5568   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5569 }
5570 
5571 /// Helper method to turn variable array types into constant array
5572 /// types in certain situations which would otherwise be errors (for
5573 /// GCC compatibility).
5574 static TypeSourceInfo*
5575 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5576                                               ASTContext &Context,
5577                                               bool &SizeIsNegative,
5578                                               llvm::APSInt &Oversized) {
5579   QualType FixedTy
5580     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5581                                           SizeIsNegative, Oversized);
5582   if (FixedTy.isNull())
5583     return nullptr;
5584   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5585   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5586                                     FixedTInfo->getTypeLoc());
5587   return FixedTInfo;
5588 }
5589 
5590 /// \brief Register the given locally-scoped extern "C" declaration so
5591 /// that it can be found later for redeclarations. We include any extern "C"
5592 /// declaration that is not visible in the translation unit here, not just
5593 /// function-scope declarations.
5594 void
5595 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5596   if (!getLangOpts().CPlusPlus &&
5597       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5598     // Don't need to track declarations in the TU in C.
5599     return;
5600 
5601   // Note that we have a locally-scoped external with this name.
5602   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5603 }
5604 
5605 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5606   // FIXME: We can have multiple results via __attribute__((overloadable)).
5607   auto Result = Context.getExternCContextDecl()->lookup(Name);
5608   return Result.empty() ? nullptr : *Result.begin();
5609 }
5610 
5611 /// \brief Diagnose function specifiers on a declaration of an identifier that
5612 /// does not identify a function.
5613 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5614   // FIXME: We should probably indicate the identifier in question to avoid
5615   // confusion for constructs like "virtual int a(), b;"
5616   if (DS.isVirtualSpecified())
5617     Diag(DS.getVirtualSpecLoc(),
5618          diag::err_virtual_non_function);
5619 
5620   if (DS.isExplicitSpecified())
5621     Diag(DS.getExplicitSpecLoc(),
5622          diag::err_explicit_non_function);
5623 
5624   if (DS.isNoreturnSpecified())
5625     Diag(DS.getNoreturnSpecLoc(),
5626          diag::err_noreturn_non_function);
5627 }
5628 
5629 NamedDecl*
5630 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5631                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5632   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5633   if (D.getCXXScopeSpec().isSet()) {
5634     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5635       << D.getCXXScopeSpec().getRange();
5636     D.setInvalidType();
5637     // Pretend we didn't see the scope specifier.
5638     DC = CurContext;
5639     Previous.clear();
5640   }
5641 
5642   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5643 
5644   if (D.getDeclSpec().isInlineSpecified())
5645     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5646         << getLangOpts().CPlusPlus1z;
5647   if (D.getDeclSpec().isConstexprSpecified())
5648     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5649       << 1;
5650   if (D.getDeclSpec().isConceptSpecified())
5651     Diag(D.getDeclSpec().getConceptSpecLoc(),
5652          diag::err_concept_wrong_decl_kind);
5653 
5654   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5655     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5656       Diag(D.getName().StartLocation,
5657            diag::err_deduction_guide_invalid_specifier)
5658           << "typedef";
5659     else
5660       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5661           << D.getName().getSourceRange();
5662     return nullptr;
5663   }
5664 
5665   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5666   if (!NewTD) return nullptr;
5667 
5668   // Handle attributes prior to checking for duplicates in MergeVarDecl
5669   ProcessDeclAttributes(S, NewTD, D);
5670 
5671   CheckTypedefForVariablyModifiedType(S, NewTD);
5672 
5673   bool Redeclaration = D.isRedeclaration();
5674   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5675   D.setRedeclaration(Redeclaration);
5676   return ND;
5677 }
5678 
5679 void
5680 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5681   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5682   // then it shall have block scope.
5683   // Note that variably modified types must be fixed before merging the decl so
5684   // that redeclarations will match.
5685   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5686   QualType T = TInfo->getType();
5687   if (T->isVariablyModifiedType()) {
5688     getCurFunction()->setHasBranchProtectedScope();
5689 
5690     if (S->getFnParent() == nullptr) {
5691       bool SizeIsNegative;
5692       llvm::APSInt Oversized;
5693       TypeSourceInfo *FixedTInfo =
5694         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5695                                                       SizeIsNegative,
5696                                                       Oversized);
5697       if (FixedTInfo) {
5698         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5699         NewTD->setTypeSourceInfo(FixedTInfo);
5700       } else {
5701         if (SizeIsNegative)
5702           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5703         else if (T->isVariableArrayType())
5704           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5705         else if (Oversized.getBoolValue())
5706           Diag(NewTD->getLocation(), diag::err_array_too_large)
5707             << Oversized.toString(10);
5708         else
5709           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5710         NewTD->setInvalidDecl();
5711       }
5712     }
5713   }
5714 }
5715 
5716 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5717 /// declares a typedef-name, either using the 'typedef' type specifier or via
5718 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5719 NamedDecl*
5720 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5721                            LookupResult &Previous, bool &Redeclaration) {
5722 
5723   // Find the shadowed declaration before filtering for scope.
5724   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5725 
5726   // Merge the decl with the existing one if appropriate. If the decl is
5727   // in an outer scope, it isn't the same thing.
5728   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5729                        /*AllowInlineNamespace*/false);
5730   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5731   if (!Previous.empty()) {
5732     Redeclaration = true;
5733     MergeTypedefNameDecl(S, NewTD, Previous);
5734   }
5735 
5736   if (ShadowedDecl && !Redeclaration)
5737     CheckShadow(NewTD, ShadowedDecl, Previous);
5738 
5739   // If this is the C FILE type, notify the AST context.
5740   if (IdentifierInfo *II = NewTD->getIdentifier())
5741     if (!NewTD->isInvalidDecl() &&
5742         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5743       if (II->isStr("FILE"))
5744         Context.setFILEDecl(NewTD);
5745       else if (II->isStr("jmp_buf"))
5746         Context.setjmp_bufDecl(NewTD);
5747       else if (II->isStr("sigjmp_buf"))
5748         Context.setsigjmp_bufDecl(NewTD);
5749       else if (II->isStr("ucontext_t"))
5750         Context.setucontext_tDecl(NewTD);
5751     }
5752 
5753   return NewTD;
5754 }
5755 
5756 /// \brief Determines whether the given declaration is an out-of-scope
5757 /// previous declaration.
5758 ///
5759 /// This routine should be invoked when name lookup has found a
5760 /// previous declaration (PrevDecl) that is not in the scope where a
5761 /// new declaration by the same name is being introduced. If the new
5762 /// declaration occurs in a local scope, previous declarations with
5763 /// linkage may still be considered previous declarations (C99
5764 /// 6.2.2p4-5, C++ [basic.link]p6).
5765 ///
5766 /// \param PrevDecl the previous declaration found by name
5767 /// lookup
5768 ///
5769 /// \param DC the context in which the new declaration is being
5770 /// declared.
5771 ///
5772 /// \returns true if PrevDecl is an out-of-scope previous declaration
5773 /// for a new delcaration with the same name.
5774 static bool
5775 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5776                                 ASTContext &Context) {
5777   if (!PrevDecl)
5778     return false;
5779 
5780   if (!PrevDecl->hasLinkage())
5781     return false;
5782 
5783   if (Context.getLangOpts().CPlusPlus) {
5784     // C++ [basic.link]p6:
5785     //   If there is a visible declaration of an entity with linkage
5786     //   having the same name and type, ignoring entities declared
5787     //   outside the innermost enclosing namespace scope, the block
5788     //   scope declaration declares that same entity and receives the
5789     //   linkage of the previous declaration.
5790     DeclContext *OuterContext = DC->getRedeclContext();
5791     if (!OuterContext->isFunctionOrMethod())
5792       // This rule only applies to block-scope declarations.
5793       return false;
5794 
5795     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5796     if (PrevOuterContext->isRecord())
5797       // We found a member function: ignore it.
5798       return false;
5799 
5800     // Find the innermost enclosing namespace for the new and
5801     // previous declarations.
5802     OuterContext = OuterContext->getEnclosingNamespaceContext();
5803     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5804 
5805     // The previous declaration is in a different namespace, so it
5806     // isn't the same function.
5807     if (!OuterContext->Equals(PrevOuterContext))
5808       return false;
5809   }
5810 
5811   return true;
5812 }
5813 
5814 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5815   CXXScopeSpec &SS = D.getCXXScopeSpec();
5816   if (!SS.isSet()) return;
5817   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5818 }
5819 
5820 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5821   QualType type = decl->getType();
5822   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5823   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5824     // Various kinds of declaration aren't allowed to be __autoreleasing.
5825     unsigned kind = -1U;
5826     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5827       if (var->hasAttr<BlocksAttr>())
5828         kind = 0; // __block
5829       else if (!var->hasLocalStorage())
5830         kind = 1; // global
5831     } else if (isa<ObjCIvarDecl>(decl)) {
5832       kind = 3; // ivar
5833     } else if (isa<FieldDecl>(decl)) {
5834       kind = 2; // field
5835     }
5836 
5837     if (kind != -1U) {
5838       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5839         << kind;
5840     }
5841   } else if (lifetime == Qualifiers::OCL_None) {
5842     // Try to infer lifetime.
5843     if (!type->isObjCLifetimeType())
5844       return false;
5845 
5846     lifetime = type->getObjCARCImplicitLifetime();
5847     type = Context.getLifetimeQualifiedType(type, lifetime);
5848     decl->setType(type);
5849   }
5850 
5851   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5852     // Thread-local variables cannot have lifetime.
5853     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5854         var->getTLSKind()) {
5855       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5856         << var->getType();
5857       return true;
5858     }
5859   }
5860 
5861   return false;
5862 }
5863 
5864 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5865   // Ensure that an auto decl is deduced otherwise the checks below might cache
5866   // the wrong linkage.
5867   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5868 
5869   // 'weak' only applies to declarations with external linkage.
5870   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5871     if (!ND.isExternallyVisible()) {
5872       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5873       ND.dropAttr<WeakAttr>();
5874     }
5875   }
5876   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5877     if (ND.isExternallyVisible()) {
5878       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5879       ND.dropAttr<WeakRefAttr>();
5880       ND.dropAttr<AliasAttr>();
5881     }
5882   }
5883 
5884   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5885     if (VD->hasInit()) {
5886       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5887         assert(VD->isThisDeclarationADefinition() &&
5888                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5889         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5890         VD->dropAttr<AliasAttr>();
5891       }
5892     }
5893   }
5894 
5895   // 'selectany' only applies to externally visible variable declarations.
5896   // It does not apply to functions.
5897   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5898     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5899       S.Diag(Attr->getLocation(),
5900              diag::err_attribute_selectany_non_extern_data);
5901       ND.dropAttr<SelectAnyAttr>();
5902     }
5903   }
5904 
5905   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5906     // dll attributes require external linkage. Static locals may have external
5907     // linkage but still cannot be explicitly imported or exported.
5908     auto *VD = dyn_cast<VarDecl>(&ND);
5909     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5910       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5911         << &ND << Attr;
5912       ND.setInvalidDecl();
5913     }
5914   }
5915 
5916   // Virtual functions cannot be marked as 'notail'.
5917   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5918     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5919       if (MD->isVirtual()) {
5920         S.Diag(ND.getLocation(),
5921                diag::err_invalid_attribute_on_virtual_function)
5922             << Attr;
5923         ND.dropAttr<NotTailCalledAttr>();
5924       }
5925 }
5926 
5927 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5928                                            NamedDecl *NewDecl,
5929                                            bool IsSpecialization,
5930                                            bool IsDefinition) {
5931   if (OldDecl->isInvalidDecl())
5932     return;
5933 
5934   bool IsTemplate = false;
5935   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5936     OldDecl = OldTD->getTemplatedDecl();
5937     IsTemplate = true;
5938     if (!IsSpecialization)
5939       IsDefinition = false;
5940   }
5941   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5942     NewDecl = NewTD->getTemplatedDecl();
5943     IsTemplate = true;
5944   }
5945 
5946   if (!OldDecl || !NewDecl)
5947     return;
5948 
5949   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5950   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5951   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5952   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5953 
5954   // dllimport and dllexport are inheritable attributes so we have to exclude
5955   // inherited attribute instances.
5956   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5957                     (NewExportAttr && !NewExportAttr->isInherited());
5958 
5959   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5960   // the only exception being explicit specializations.
5961   // Implicitly generated declarations are also excluded for now because there
5962   // is no other way to switch these to use dllimport or dllexport.
5963   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5964 
5965   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5966     // Allow with a warning for free functions and global variables.
5967     bool JustWarn = false;
5968     if (!OldDecl->isCXXClassMember()) {
5969       auto *VD = dyn_cast<VarDecl>(OldDecl);
5970       if (VD && !VD->getDescribedVarTemplate())
5971         JustWarn = true;
5972       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5973       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5974         JustWarn = true;
5975     }
5976 
5977     // We cannot change a declaration that's been used because IR has already
5978     // been emitted. Dllimported functions will still work though (modulo
5979     // address equality) as they can use the thunk.
5980     if (OldDecl->isUsed())
5981       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5982         JustWarn = false;
5983 
5984     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5985                                : diag::err_attribute_dll_redeclaration;
5986     S.Diag(NewDecl->getLocation(), DiagID)
5987         << NewDecl
5988         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5989     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5990     if (!JustWarn) {
5991       NewDecl->setInvalidDecl();
5992       return;
5993     }
5994   }
5995 
5996   // A redeclaration is not allowed to drop a dllimport attribute, the only
5997   // exceptions being inline function definitions (except for function
5998   // templates), local extern declarations, qualified friend declarations or
5999   // special MSVC extension: in the last case, the declaration is treated as if
6000   // it were marked dllexport.
6001   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6002   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6003   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6004     // Ignore static data because out-of-line definitions are diagnosed
6005     // separately.
6006     IsStaticDataMember = VD->isStaticDataMember();
6007     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6008                    VarDecl::DeclarationOnly;
6009   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6010     IsInline = FD->isInlined();
6011     IsQualifiedFriend = FD->getQualifier() &&
6012                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6013   }
6014 
6015   if (OldImportAttr && !HasNewAttr &&
6016       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6017       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6018     if (IsMicrosoft && IsDefinition) {
6019       S.Diag(NewDecl->getLocation(),
6020              diag::warn_redeclaration_without_import_attribute)
6021           << NewDecl;
6022       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6023       NewDecl->dropAttr<DLLImportAttr>();
6024       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6025           NewImportAttr->getRange(), S.Context,
6026           NewImportAttr->getSpellingListIndex()));
6027     } else {
6028       S.Diag(NewDecl->getLocation(),
6029              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6030           << NewDecl << OldImportAttr;
6031       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6032       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6033       OldDecl->dropAttr<DLLImportAttr>();
6034       NewDecl->dropAttr<DLLImportAttr>();
6035     }
6036   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6037     // In MinGW, seeing a function declared inline drops the dllimport attribute.
6038     OldDecl->dropAttr<DLLImportAttr>();
6039     NewDecl->dropAttr<DLLImportAttr>();
6040     S.Diag(NewDecl->getLocation(),
6041            diag::warn_dllimport_dropped_from_inline_function)
6042         << NewDecl << OldImportAttr;
6043   }
6044 }
6045 
6046 /// Given that we are within the definition of the given function,
6047 /// will that definition behave like C99's 'inline', where the
6048 /// definition is discarded except for optimization purposes?
6049 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6050   // Try to avoid calling GetGVALinkageForFunction.
6051 
6052   // All cases of this require the 'inline' keyword.
6053   if (!FD->isInlined()) return false;
6054 
6055   // This is only possible in C++ with the gnu_inline attribute.
6056   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6057     return false;
6058 
6059   // Okay, go ahead and call the relatively-more-expensive function.
6060   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6061 }
6062 
6063 /// Determine whether a variable is extern "C" prior to attaching
6064 /// an initializer. We can't just call isExternC() here, because that
6065 /// will also compute and cache whether the declaration is externally
6066 /// visible, which might change when we attach the initializer.
6067 ///
6068 /// This can only be used if the declaration is known to not be a
6069 /// redeclaration of an internal linkage declaration.
6070 ///
6071 /// For instance:
6072 ///
6073 ///   auto x = []{};
6074 ///
6075 /// Attaching the initializer here makes this declaration not externally
6076 /// visible, because its type has internal linkage.
6077 ///
6078 /// FIXME: This is a hack.
6079 template<typename T>
6080 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6081   if (S.getLangOpts().CPlusPlus) {
6082     // In C++, the overloadable attribute negates the effects of extern "C".
6083     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6084       return false;
6085 
6086     // So do CUDA's host/device attributes.
6087     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6088                                  D->template hasAttr<CUDAHostAttr>()))
6089       return false;
6090   }
6091   return D->isExternC();
6092 }
6093 
6094 static bool shouldConsiderLinkage(const VarDecl *VD) {
6095   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6096   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6097     return VD->hasExternalStorage();
6098   if (DC->isFileContext())
6099     return true;
6100   if (DC->isRecord())
6101     return false;
6102   llvm_unreachable("Unexpected context");
6103 }
6104 
6105 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6106   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6107   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6108       isa<OMPDeclareReductionDecl>(DC))
6109     return true;
6110   if (DC->isRecord())
6111     return false;
6112   llvm_unreachable("Unexpected context");
6113 }
6114 
6115 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6116                           AttributeList::Kind Kind) {
6117   for (const AttributeList *L = AttrList; L; L = L->getNext())
6118     if (L->getKind() == Kind)
6119       return true;
6120   return false;
6121 }
6122 
6123 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6124                           AttributeList::Kind Kind) {
6125   // Check decl attributes on the DeclSpec.
6126   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6127     return true;
6128 
6129   // Walk the declarator structure, checking decl attributes that were in a type
6130   // position to the decl itself.
6131   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6132     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6133       return true;
6134   }
6135 
6136   // Finally, check attributes on the decl itself.
6137   return hasParsedAttr(S, PD.getAttributes(), Kind);
6138 }
6139 
6140 /// Adjust the \c DeclContext for a function or variable that might be a
6141 /// function-local external declaration.
6142 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6143   if (!DC->isFunctionOrMethod())
6144     return false;
6145 
6146   // If this is a local extern function or variable declared within a function
6147   // template, don't add it into the enclosing namespace scope until it is
6148   // instantiated; it might have a dependent type right now.
6149   if (DC->isDependentContext())
6150     return true;
6151 
6152   // C++11 [basic.link]p7:
6153   //   When a block scope declaration of an entity with linkage is not found to
6154   //   refer to some other declaration, then that entity is a member of the
6155   //   innermost enclosing namespace.
6156   //
6157   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6158   // semantically-enclosing namespace, not a lexically-enclosing one.
6159   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6160     DC = DC->getParent();
6161   return true;
6162 }
6163 
6164 /// \brief Returns true if given declaration has external C language linkage.
6165 static bool isDeclExternC(const Decl *D) {
6166   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6167     return FD->isExternC();
6168   if (const auto *VD = dyn_cast<VarDecl>(D))
6169     return VD->isExternC();
6170 
6171   llvm_unreachable("Unknown type of decl!");
6172 }
6173 
6174 NamedDecl *Sema::ActOnVariableDeclarator(
6175     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6176     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6177     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6178   QualType R = TInfo->getType();
6179   DeclarationName Name = GetNameForDeclarator(D).getName();
6180 
6181   IdentifierInfo *II = Name.getAsIdentifierInfo();
6182 
6183   if (D.isDecompositionDeclarator()) {
6184     // Take the name of the first declarator as our name for diagnostic
6185     // purposes.
6186     auto &Decomp = D.getDecompositionDeclarator();
6187     if (!Decomp.bindings().empty()) {
6188       II = Decomp.bindings()[0].Name;
6189       Name = II;
6190     }
6191   } else if (!II) {
6192     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6193     return nullptr;
6194   }
6195 
6196   if (getLangOpts().OpenCL) {
6197     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6198     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6199     // argument.
6200     if (R->isImageType() || R->isPipeType()) {
6201       Diag(D.getIdentifierLoc(),
6202            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6203           << R;
6204       D.setInvalidType();
6205       return nullptr;
6206     }
6207 
6208     // OpenCL v1.2 s6.9.r:
6209     // The event type cannot be used to declare a program scope variable.
6210     // OpenCL v2.0 s6.9.q:
6211     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6212     if (NULL == S->getParent()) {
6213       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6214         Diag(D.getIdentifierLoc(),
6215              diag::err_invalid_type_for_program_scope_var) << R;
6216         D.setInvalidType();
6217         return nullptr;
6218       }
6219     }
6220 
6221     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6222     QualType NR = R;
6223     while (NR->isPointerType()) {
6224       if (NR->isFunctionPointerType()) {
6225         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6226         D.setInvalidType();
6227         break;
6228       }
6229       NR = NR->getPointeeType();
6230     }
6231 
6232     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6233       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6234       // half array type (unless the cl_khr_fp16 extension is enabled).
6235       if (Context.getBaseElementType(R)->isHalfType()) {
6236         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6237         D.setInvalidType();
6238       }
6239     }
6240 
6241     if (R->isSamplerT()) {
6242       // OpenCL v1.2 s6.9.b p4:
6243       // The sampler type cannot be used with the __local and __global address
6244       // space qualifiers.
6245       if (R.getAddressSpace() == LangAS::opencl_local ||
6246           R.getAddressSpace() == LangAS::opencl_global) {
6247         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6248       }
6249 
6250       // OpenCL v1.2 s6.12.14.1:
6251       // A global sampler must be declared with either the constant address
6252       // space qualifier or with the const qualifier.
6253       if (DC->isTranslationUnit() &&
6254           !(R.getAddressSpace() == LangAS::opencl_constant ||
6255           R.isConstQualified())) {
6256         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6257         D.setInvalidType();
6258       }
6259     }
6260 
6261     // OpenCL v1.2 s6.9.r:
6262     // The event type cannot be used with the __local, __constant and __global
6263     // address space qualifiers.
6264     if (R->isEventT()) {
6265       if (R.getAddressSpace()) {
6266         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6267         D.setInvalidType();
6268       }
6269     }
6270   }
6271 
6272   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6273   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6274 
6275   // dllimport globals without explicit storage class are treated as extern. We
6276   // have to change the storage class this early to get the right DeclContext.
6277   if (SC == SC_None && !DC->isRecord() &&
6278       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6279       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6280     SC = SC_Extern;
6281 
6282   DeclContext *OriginalDC = DC;
6283   bool IsLocalExternDecl = SC == SC_Extern &&
6284                            adjustContextForLocalExternDecl(DC);
6285 
6286   if (SCSpec == DeclSpec::SCS_mutable) {
6287     // mutable can only appear on non-static class members, so it's always
6288     // an error here
6289     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6290     D.setInvalidType();
6291     SC = SC_None;
6292   }
6293 
6294   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6295       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6296                               D.getDeclSpec().getStorageClassSpecLoc())) {
6297     // In C++11, the 'register' storage class specifier is deprecated.
6298     // Suppress the warning in system macros, it's used in macros in some
6299     // popular C system headers, such as in glibc's htonl() macro.
6300     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6301          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6302                                    : diag::warn_deprecated_register)
6303       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6304   }
6305 
6306   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6307 
6308   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6309     // C99 6.9p2: The storage-class specifiers auto and register shall not
6310     // appear in the declaration specifiers in an external declaration.
6311     // Global Register+Asm is a GNU extension we support.
6312     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6313       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6314       D.setInvalidType();
6315     }
6316   }
6317 
6318   bool IsMemberSpecialization = false;
6319   bool IsVariableTemplateSpecialization = false;
6320   bool IsPartialSpecialization = false;
6321   bool IsVariableTemplate = false;
6322   VarDecl *NewVD = nullptr;
6323   VarTemplateDecl *NewTemplate = nullptr;
6324   TemplateParameterList *TemplateParams = nullptr;
6325   if (!getLangOpts().CPlusPlus) {
6326     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6327                             D.getIdentifierLoc(), II,
6328                             R, TInfo, SC);
6329 
6330     if (R->getContainedDeducedType())
6331       ParsingInitForAutoVars.insert(NewVD);
6332 
6333     if (D.isInvalidType())
6334       NewVD->setInvalidDecl();
6335   } else {
6336     bool Invalid = false;
6337 
6338     if (DC->isRecord() && !CurContext->isRecord()) {
6339       // This is an out-of-line definition of a static data member.
6340       switch (SC) {
6341       case SC_None:
6342         break;
6343       case SC_Static:
6344         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6345              diag::err_static_out_of_line)
6346           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6347         break;
6348       case SC_Auto:
6349       case SC_Register:
6350       case SC_Extern:
6351         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6352         // to names of variables declared in a block or to function parameters.
6353         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6354         // of class members
6355 
6356         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6357              diag::err_storage_class_for_static_member)
6358           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6359         break;
6360       case SC_PrivateExtern:
6361         llvm_unreachable("C storage class in c++!");
6362       }
6363     }
6364 
6365     if (SC == SC_Static && CurContext->isRecord()) {
6366       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6367         if (RD->isLocalClass())
6368           Diag(D.getIdentifierLoc(),
6369                diag::err_static_data_member_not_allowed_in_local_class)
6370             << Name << RD->getDeclName();
6371 
6372         // C++98 [class.union]p1: If a union contains a static data member,
6373         // the program is ill-formed. C++11 drops this restriction.
6374         if (RD->isUnion())
6375           Diag(D.getIdentifierLoc(),
6376                getLangOpts().CPlusPlus11
6377                  ? diag::warn_cxx98_compat_static_data_member_in_union
6378                  : diag::ext_static_data_member_in_union) << Name;
6379         // We conservatively disallow static data members in anonymous structs.
6380         else if (!RD->getDeclName())
6381           Diag(D.getIdentifierLoc(),
6382                diag::err_static_data_member_not_allowed_in_anon_struct)
6383             << Name << RD->isUnion();
6384       }
6385     }
6386 
6387     // Match up the template parameter lists with the scope specifier, then
6388     // determine whether we have a template or a template specialization.
6389     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6390         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6391         D.getCXXScopeSpec(),
6392         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6393             ? D.getName().TemplateId
6394             : nullptr,
6395         TemplateParamLists,
6396         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6397 
6398     if (TemplateParams) {
6399       if (!TemplateParams->size() &&
6400           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6401         // There is an extraneous 'template<>' for this variable. Complain
6402         // about it, but allow the declaration of the variable.
6403         Diag(TemplateParams->getTemplateLoc(),
6404              diag::err_template_variable_noparams)
6405           << II
6406           << SourceRange(TemplateParams->getTemplateLoc(),
6407                          TemplateParams->getRAngleLoc());
6408         TemplateParams = nullptr;
6409       } else {
6410         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6411           // This is an explicit specialization or a partial specialization.
6412           // FIXME: Check that we can declare a specialization here.
6413           IsVariableTemplateSpecialization = true;
6414           IsPartialSpecialization = TemplateParams->size() > 0;
6415         } else { // if (TemplateParams->size() > 0)
6416           // This is a template declaration.
6417           IsVariableTemplate = true;
6418 
6419           // Check that we can declare a template here.
6420           if (CheckTemplateDeclScope(S, TemplateParams))
6421             return nullptr;
6422 
6423           // Only C++1y supports variable templates (N3651).
6424           Diag(D.getIdentifierLoc(),
6425                getLangOpts().CPlusPlus14
6426                    ? diag::warn_cxx11_compat_variable_template
6427                    : diag::ext_variable_template);
6428         }
6429       }
6430     } else {
6431       assert(
6432           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6433           "should have a 'template<>' for this decl");
6434     }
6435 
6436     if (IsVariableTemplateSpecialization) {
6437       SourceLocation TemplateKWLoc =
6438           TemplateParamLists.size() > 0
6439               ? TemplateParamLists[0]->getTemplateLoc()
6440               : SourceLocation();
6441       DeclResult Res = ActOnVarTemplateSpecialization(
6442           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6443           IsPartialSpecialization);
6444       if (Res.isInvalid())
6445         return nullptr;
6446       NewVD = cast<VarDecl>(Res.get());
6447       AddToScope = false;
6448     } else if (D.isDecompositionDeclarator()) {
6449       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6450                                         D.getIdentifierLoc(), R, TInfo, SC,
6451                                         Bindings);
6452     } else
6453       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6454                               D.getIdentifierLoc(), II, R, TInfo, SC);
6455 
6456     // If this is supposed to be a variable template, create it as such.
6457     if (IsVariableTemplate) {
6458       NewTemplate =
6459           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6460                                   TemplateParams, NewVD);
6461       NewVD->setDescribedVarTemplate(NewTemplate);
6462     }
6463 
6464     // If this decl has an auto type in need of deduction, make a note of the
6465     // Decl so we can diagnose uses of it in its own initializer.
6466     if (R->getContainedDeducedType())
6467       ParsingInitForAutoVars.insert(NewVD);
6468 
6469     if (D.isInvalidType() || Invalid) {
6470       NewVD->setInvalidDecl();
6471       if (NewTemplate)
6472         NewTemplate->setInvalidDecl();
6473     }
6474 
6475     SetNestedNameSpecifier(NewVD, D);
6476 
6477     // If we have any template parameter lists that don't directly belong to
6478     // the variable (matching the scope specifier), store them.
6479     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6480     if (TemplateParamLists.size() > VDTemplateParamLists)
6481       NewVD->setTemplateParameterListsInfo(
6482           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6483 
6484     if (D.getDeclSpec().isConstexprSpecified()) {
6485       NewVD->setConstexpr(true);
6486       // C++1z [dcl.spec.constexpr]p1:
6487       //   A static data member declared with the constexpr specifier is
6488       //   implicitly an inline variable.
6489       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6490         NewVD->setImplicitlyInline();
6491     }
6492 
6493     if (D.getDeclSpec().isConceptSpecified()) {
6494       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6495         VTD->setConcept();
6496 
6497       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6498       // be declared with the thread_local, inline, friend, or constexpr
6499       // specifiers, [...]
6500       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6501         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6502              diag::err_concept_decl_invalid_specifiers)
6503             << 0 << 0;
6504         NewVD->setInvalidDecl(true);
6505       }
6506 
6507       if (D.getDeclSpec().isConstexprSpecified()) {
6508         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6509              diag::err_concept_decl_invalid_specifiers)
6510             << 0 << 3;
6511         NewVD->setInvalidDecl(true);
6512       }
6513 
6514       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6515       // applied only to the definition of a function template or variable
6516       // template, declared in namespace scope.
6517       if (IsVariableTemplateSpecialization) {
6518         Diag(D.getDeclSpec().getConceptSpecLoc(),
6519              diag::err_concept_specified_specialization)
6520             << (IsPartialSpecialization ? 2 : 1);
6521       }
6522 
6523       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6524       // following restrictions:
6525       // - The declared type shall have the type bool.
6526       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6527           !NewVD->isInvalidDecl()) {
6528         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6529         NewVD->setInvalidDecl(true);
6530       }
6531     }
6532   }
6533 
6534   if (D.getDeclSpec().isInlineSpecified()) {
6535     if (!getLangOpts().CPlusPlus) {
6536       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6537           << 0;
6538     } else if (CurContext->isFunctionOrMethod()) {
6539       // 'inline' is not allowed on block scope variable declaration.
6540       Diag(D.getDeclSpec().getInlineSpecLoc(),
6541            diag::err_inline_declaration_block_scope) << Name
6542         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6543     } else {
6544       Diag(D.getDeclSpec().getInlineSpecLoc(),
6545            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6546                                      : diag::ext_inline_variable);
6547       NewVD->setInlineSpecified();
6548     }
6549   }
6550 
6551   // Set the lexical context. If the declarator has a C++ scope specifier, the
6552   // lexical context will be different from the semantic context.
6553   NewVD->setLexicalDeclContext(CurContext);
6554   if (NewTemplate)
6555     NewTemplate->setLexicalDeclContext(CurContext);
6556 
6557   if (IsLocalExternDecl) {
6558     if (D.isDecompositionDeclarator())
6559       for (auto *B : Bindings)
6560         B->setLocalExternDecl();
6561     else
6562       NewVD->setLocalExternDecl();
6563   }
6564 
6565   bool EmitTLSUnsupportedError = false;
6566   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6567     // C++11 [dcl.stc]p4:
6568     //   When thread_local is applied to a variable of block scope the
6569     //   storage-class-specifier static is implied if it does not appear
6570     //   explicitly.
6571     // Core issue: 'static' is not implied if the variable is declared
6572     //   'extern'.
6573     if (NewVD->hasLocalStorage() &&
6574         (SCSpec != DeclSpec::SCS_unspecified ||
6575          TSCS != DeclSpec::TSCS_thread_local ||
6576          !DC->isFunctionOrMethod()))
6577       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6578            diag::err_thread_non_global)
6579         << DeclSpec::getSpecifierName(TSCS);
6580     else if (!Context.getTargetInfo().isTLSSupported()) {
6581       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6582         // Postpone error emission until we've collected attributes required to
6583         // figure out whether it's a host or device variable and whether the
6584         // error should be ignored.
6585         EmitTLSUnsupportedError = true;
6586         // We still need to mark the variable as TLS so it shows up in AST with
6587         // proper storage class for other tools to use even if we're not going
6588         // to emit any code for it.
6589         NewVD->setTSCSpec(TSCS);
6590       } else
6591         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6592              diag::err_thread_unsupported);
6593     } else
6594       NewVD->setTSCSpec(TSCS);
6595   }
6596 
6597   // C99 6.7.4p3
6598   //   An inline definition of a function with external linkage shall
6599   //   not contain a definition of a modifiable object with static or
6600   //   thread storage duration...
6601   // We only apply this when the function is required to be defined
6602   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6603   // that a local variable with thread storage duration still has to
6604   // be marked 'static'.  Also note that it's possible to get these
6605   // semantics in C++ using __attribute__((gnu_inline)).
6606   if (SC == SC_Static && S->getFnParent() != nullptr &&
6607       !NewVD->getType().isConstQualified()) {
6608     FunctionDecl *CurFD = getCurFunctionDecl();
6609     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6610       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6611            diag::warn_static_local_in_extern_inline);
6612       MaybeSuggestAddingStaticToDecl(CurFD);
6613     }
6614   }
6615 
6616   if (D.getDeclSpec().isModulePrivateSpecified()) {
6617     if (IsVariableTemplateSpecialization)
6618       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6619           << (IsPartialSpecialization ? 1 : 0)
6620           << FixItHint::CreateRemoval(
6621                  D.getDeclSpec().getModulePrivateSpecLoc());
6622     else if (IsMemberSpecialization)
6623       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6624         << 2
6625         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6626     else if (NewVD->hasLocalStorage())
6627       Diag(NewVD->getLocation(), diag::err_module_private_local)
6628         << 0 << NewVD->getDeclName()
6629         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6630         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6631     else {
6632       NewVD->setModulePrivate();
6633       if (NewTemplate)
6634         NewTemplate->setModulePrivate();
6635       for (auto *B : Bindings)
6636         B->setModulePrivate();
6637     }
6638   }
6639 
6640   // Handle attributes prior to checking for duplicates in MergeVarDecl
6641   ProcessDeclAttributes(S, NewVD, D);
6642 
6643   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6644     if (EmitTLSUnsupportedError &&
6645         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6646          (getLangOpts().OpenMPIsDevice &&
6647           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6648       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6649            diag::err_thread_unsupported);
6650     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6651     // storage [duration]."
6652     if (SC == SC_None && S->getFnParent() != nullptr &&
6653         (NewVD->hasAttr<CUDASharedAttr>() ||
6654          NewVD->hasAttr<CUDAConstantAttr>())) {
6655       NewVD->setStorageClass(SC_Static);
6656     }
6657   }
6658 
6659   // Ensure that dllimport globals without explicit storage class are treated as
6660   // extern. The storage class is set above using parsed attributes. Now we can
6661   // check the VarDecl itself.
6662   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6663          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6664          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6665 
6666   // In auto-retain/release, infer strong retension for variables of
6667   // retainable type.
6668   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6669     NewVD->setInvalidDecl();
6670 
6671   // Handle GNU asm-label extension (encoded as an attribute).
6672   if (Expr *E = (Expr*)D.getAsmLabel()) {
6673     // The parser guarantees this is a string.
6674     StringLiteral *SE = cast<StringLiteral>(E);
6675     StringRef Label = SE->getString();
6676     if (S->getFnParent() != nullptr) {
6677       switch (SC) {
6678       case SC_None:
6679       case SC_Auto:
6680         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6681         break;
6682       case SC_Register:
6683         // Local Named register
6684         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6685             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6686           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6687         break;
6688       case SC_Static:
6689       case SC_Extern:
6690       case SC_PrivateExtern:
6691         break;
6692       }
6693     } else if (SC == SC_Register) {
6694       // Global Named register
6695       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6696         const auto &TI = Context.getTargetInfo();
6697         bool HasSizeMismatch;
6698 
6699         if (!TI.isValidGCCRegisterName(Label))
6700           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6701         else if (!TI.validateGlobalRegisterVariable(Label,
6702                                                     Context.getTypeSize(R),
6703                                                     HasSizeMismatch))
6704           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6705         else if (HasSizeMismatch)
6706           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6707       }
6708 
6709       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6710         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6711         NewVD->setInvalidDecl(true);
6712       }
6713     }
6714 
6715     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6716                                                 Context, Label, 0));
6717   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6718     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6719       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6720     if (I != ExtnameUndeclaredIdentifiers.end()) {
6721       if (isDeclExternC(NewVD)) {
6722         NewVD->addAttr(I->second);
6723         ExtnameUndeclaredIdentifiers.erase(I);
6724       } else
6725         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6726             << /*Variable*/1 << NewVD;
6727     }
6728   }
6729 
6730   // Find the shadowed declaration before filtering for scope.
6731   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6732                                 ? getShadowedDeclaration(NewVD, Previous)
6733                                 : nullptr;
6734 
6735   // Don't consider existing declarations that are in a different
6736   // scope and are out-of-semantic-context declarations (if the new
6737   // declaration has linkage).
6738   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6739                        D.getCXXScopeSpec().isNotEmpty() ||
6740                        IsMemberSpecialization ||
6741                        IsVariableTemplateSpecialization);
6742 
6743   // Check whether the previous declaration is in the same block scope. This
6744   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6745   if (getLangOpts().CPlusPlus &&
6746       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6747     NewVD->setPreviousDeclInSameBlockScope(
6748         Previous.isSingleResult() && !Previous.isShadowed() &&
6749         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6750 
6751   if (!getLangOpts().CPlusPlus) {
6752     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6753   } else {
6754     // If this is an explicit specialization of a static data member, check it.
6755     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6756         CheckMemberSpecialization(NewVD, Previous))
6757       NewVD->setInvalidDecl();
6758 
6759     // Merge the decl with the existing one if appropriate.
6760     if (!Previous.empty()) {
6761       if (Previous.isSingleResult() &&
6762           isa<FieldDecl>(Previous.getFoundDecl()) &&
6763           D.getCXXScopeSpec().isSet()) {
6764         // The user tried to define a non-static data member
6765         // out-of-line (C++ [dcl.meaning]p1).
6766         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6767           << D.getCXXScopeSpec().getRange();
6768         Previous.clear();
6769         NewVD->setInvalidDecl();
6770       }
6771     } else if (D.getCXXScopeSpec().isSet()) {
6772       // No previous declaration in the qualifying scope.
6773       Diag(D.getIdentifierLoc(), diag::err_no_member)
6774         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6775         << D.getCXXScopeSpec().getRange();
6776       NewVD->setInvalidDecl();
6777     }
6778 
6779     if (!IsVariableTemplateSpecialization)
6780       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6781 
6782     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6783     // an explicit specialization (14.8.3) or a partial specialization of a
6784     // concept definition.
6785     if (IsVariableTemplateSpecialization &&
6786         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6787         Previous.isSingleResult()) {
6788       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6789       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6790         if (VarTmpl->isConcept()) {
6791           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6792               << 1                            /*variable*/
6793               << (IsPartialSpecialization ? 2 /*partially specialized*/
6794                                           : 1 /*explicitly specialized*/);
6795           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6796           NewVD->setInvalidDecl();
6797         }
6798       }
6799     }
6800 
6801     if (NewTemplate) {
6802       VarTemplateDecl *PrevVarTemplate =
6803           NewVD->getPreviousDecl()
6804               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6805               : nullptr;
6806 
6807       // Check the template parameter list of this declaration, possibly
6808       // merging in the template parameter list from the previous variable
6809       // template declaration.
6810       if (CheckTemplateParameterList(
6811               TemplateParams,
6812               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6813                               : nullptr,
6814               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6815                DC->isDependentContext())
6816                   ? TPC_ClassTemplateMember
6817                   : TPC_VarTemplate))
6818         NewVD->setInvalidDecl();
6819 
6820       // If we are providing an explicit specialization of a static variable
6821       // template, make a note of that.
6822       if (PrevVarTemplate &&
6823           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6824         PrevVarTemplate->setMemberSpecialization();
6825     }
6826   }
6827 
6828   // Diagnose shadowed variables iff this isn't a redeclaration.
6829   if (ShadowedDecl && !D.isRedeclaration())
6830     CheckShadow(NewVD, ShadowedDecl, Previous);
6831 
6832   ProcessPragmaWeak(S, NewVD);
6833 
6834   // If this is the first declaration of an extern C variable, update
6835   // the map of such variables.
6836   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6837       isIncompleteDeclExternC(*this, NewVD))
6838     RegisterLocallyScopedExternCDecl(NewVD, S);
6839 
6840   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6841     Decl *ManglingContextDecl;
6842     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6843             NewVD->getDeclContext(), ManglingContextDecl)) {
6844       Context.setManglingNumber(
6845           NewVD, MCtx->getManglingNumber(
6846                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6847       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6848     }
6849   }
6850 
6851   // Special handling of variable named 'main'.
6852   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6853       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6854       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6855 
6856     // C++ [basic.start.main]p3
6857     // A program that declares a variable main at global scope is ill-formed.
6858     if (getLangOpts().CPlusPlus)
6859       Diag(D.getLocStart(), diag::err_main_global_variable);
6860 
6861     // In C, and external-linkage variable named main results in undefined
6862     // behavior.
6863     else if (NewVD->hasExternalFormalLinkage())
6864       Diag(D.getLocStart(), diag::warn_main_redefined);
6865   }
6866 
6867   if (D.isRedeclaration() && !Previous.empty()) {
6868     checkDLLAttributeRedeclaration(
6869         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6870         IsMemberSpecialization, D.isFunctionDefinition());
6871   }
6872 
6873   if (NewTemplate) {
6874     if (NewVD->isInvalidDecl())
6875       NewTemplate->setInvalidDecl();
6876     ActOnDocumentableDecl(NewTemplate);
6877     return NewTemplate;
6878   }
6879 
6880   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6881     CompleteMemberSpecialization(NewVD, Previous);
6882 
6883   return NewVD;
6884 }
6885 
6886 /// Enum describing the %select options in diag::warn_decl_shadow.
6887 enum ShadowedDeclKind {
6888   SDK_Local,
6889   SDK_Global,
6890   SDK_StaticMember,
6891   SDK_Field,
6892   SDK_Typedef,
6893   SDK_Using
6894 };
6895 
6896 /// Determine what kind of declaration we're shadowing.
6897 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6898                                                 const DeclContext *OldDC) {
6899   if (isa<TypeAliasDecl>(ShadowedDecl))
6900     return SDK_Using;
6901   else if (isa<TypedefDecl>(ShadowedDecl))
6902     return SDK_Typedef;
6903   else if (isa<RecordDecl>(OldDC))
6904     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6905 
6906   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6907 }
6908 
6909 /// Return the location of the capture if the given lambda captures the given
6910 /// variable \p VD, or an invalid source location otherwise.
6911 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6912                                          const VarDecl *VD) {
6913   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6914     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6915       return Capture.getLocation();
6916   }
6917   return SourceLocation();
6918 }
6919 
6920 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6921                                      const LookupResult &R) {
6922   // Only diagnose if we're shadowing an unambiguous field or variable.
6923   if (R.getResultKind() != LookupResult::Found)
6924     return false;
6925 
6926   // Return false if warning is ignored.
6927   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6928 }
6929 
6930 /// \brief Return the declaration shadowed by the given variable \p D, or null
6931 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6932 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6933                                         const LookupResult &R) {
6934   if (!shouldWarnIfShadowedDecl(Diags, R))
6935     return nullptr;
6936 
6937   // Don't diagnose declarations at file scope.
6938   if (D->hasGlobalStorage())
6939     return nullptr;
6940 
6941   NamedDecl *ShadowedDecl = R.getFoundDecl();
6942   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6943              ? ShadowedDecl
6944              : nullptr;
6945 }
6946 
6947 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6948 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6949 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6950                                         const LookupResult &R) {
6951   // Don't warn if typedef declaration is part of a class
6952   if (D->getDeclContext()->isRecord())
6953     return nullptr;
6954 
6955   if (!shouldWarnIfShadowedDecl(Diags, R))
6956     return nullptr;
6957 
6958   NamedDecl *ShadowedDecl = R.getFoundDecl();
6959   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6960 }
6961 
6962 /// \brief Diagnose variable or built-in function shadowing.  Implements
6963 /// -Wshadow.
6964 ///
6965 /// This method is called whenever a VarDecl is added to a "useful"
6966 /// scope.
6967 ///
6968 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6969 /// \param R the lookup of the name
6970 ///
6971 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6972                        const LookupResult &R) {
6973   DeclContext *NewDC = D->getDeclContext();
6974 
6975   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6976     // Fields are not shadowed by variables in C++ static methods.
6977     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6978       if (MD->isStatic())
6979         return;
6980 
6981     // Fields shadowed by constructor parameters are a special case. Usually
6982     // the constructor initializes the field with the parameter.
6983     if (isa<CXXConstructorDecl>(NewDC))
6984       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6985         // Remember that this was shadowed so we can either warn about its
6986         // modification or its existence depending on warning settings.
6987         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6988         return;
6989       }
6990   }
6991 
6992   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6993     if (shadowedVar->isExternC()) {
6994       // For shadowing external vars, make sure that we point to the global
6995       // declaration, not a locally scoped extern declaration.
6996       for (auto I : shadowedVar->redecls())
6997         if (I->isFileVarDecl()) {
6998           ShadowedDecl = I;
6999           break;
7000         }
7001     }
7002 
7003   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7004 
7005   unsigned WarningDiag = diag::warn_decl_shadow;
7006   SourceLocation CaptureLoc;
7007   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7008       isa<CXXMethodDecl>(NewDC)) {
7009     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7010       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7011         if (RD->getLambdaCaptureDefault() == LCD_None) {
7012           // Try to avoid warnings for lambdas with an explicit capture list.
7013           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7014           // Warn only when the lambda captures the shadowed decl explicitly.
7015           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7016           if (CaptureLoc.isInvalid())
7017             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7018         } else {
7019           // Remember that this was shadowed so we can avoid the warning if the
7020           // shadowed decl isn't captured and the warning settings allow it.
7021           cast<LambdaScopeInfo>(getCurFunction())
7022               ->ShadowingDecls.push_back(
7023                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7024           return;
7025         }
7026       }
7027 
7028       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7029         // A variable can't shadow a local variable in an enclosing scope, if
7030         // they are separated by a non-capturing declaration context.
7031         for (DeclContext *ParentDC = NewDC;
7032              ParentDC && !ParentDC->Equals(OldDC);
7033              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7034           // Only block literals, captured statements, and lambda expressions
7035           // can capture; other scopes don't.
7036           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7037               !isLambdaCallOperator(ParentDC)) {
7038             return;
7039           }
7040         }
7041       }
7042     }
7043   }
7044 
7045   // Only warn about certain kinds of shadowing for class members.
7046   if (NewDC && NewDC->isRecord()) {
7047     // In particular, don't warn about shadowing non-class members.
7048     if (!OldDC->isRecord())
7049       return;
7050 
7051     // TODO: should we warn about static data members shadowing
7052     // static data members from base classes?
7053 
7054     // TODO: don't diagnose for inaccessible shadowed members.
7055     // This is hard to do perfectly because we might friend the
7056     // shadowing context, but that's just a false negative.
7057   }
7058 
7059 
7060   DeclarationName Name = R.getLookupName();
7061 
7062   // Emit warning and note.
7063   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7064     return;
7065   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7066   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7067   if (!CaptureLoc.isInvalid())
7068     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7069         << Name << /*explicitly*/ 1;
7070   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7071 }
7072 
7073 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7074 /// when these variables are captured by the lambda.
7075 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7076   for (const auto &Shadow : LSI->ShadowingDecls) {
7077     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7078     // Try to avoid the warning when the shadowed decl isn't captured.
7079     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7080     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7081     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7082                                        ? diag::warn_decl_shadow_uncaptured_local
7083                                        : diag::warn_decl_shadow)
7084         << Shadow.VD->getDeclName()
7085         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7086     if (!CaptureLoc.isInvalid())
7087       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7088           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7089     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7090   }
7091 }
7092 
7093 /// \brief Check -Wshadow without the advantage of a previous lookup.
7094 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7095   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7096     return;
7097 
7098   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7099                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7100   LookupName(R, S);
7101   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7102     CheckShadow(D, ShadowedDecl, R);
7103 }
7104 
7105 /// Check if 'E', which is an expression that is about to be modified, refers
7106 /// to a constructor parameter that shadows a field.
7107 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7108   // Quickly ignore expressions that can't be shadowing ctor parameters.
7109   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7110     return;
7111   E = E->IgnoreParenImpCasts();
7112   auto *DRE = dyn_cast<DeclRefExpr>(E);
7113   if (!DRE)
7114     return;
7115   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7116   auto I = ShadowingDecls.find(D);
7117   if (I == ShadowingDecls.end())
7118     return;
7119   const NamedDecl *ShadowedDecl = I->second;
7120   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7121   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7122   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7123   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7124 
7125   // Avoid issuing multiple warnings about the same decl.
7126   ShadowingDecls.erase(I);
7127 }
7128 
7129 /// Check for conflict between this global or extern "C" declaration and
7130 /// previous global or extern "C" declarations. This is only used in C++.
7131 template<typename T>
7132 static bool checkGlobalOrExternCConflict(
7133     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7134   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7135   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7136 
7137   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7138     // The common case: this global doesn't conflict with any extern "C"
7139     // declaration.
7140     return false;
7141   }
7142 
7143   if (Prev) {
7144     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7145       // Both the old and new declarations have C language linkage. This is a
7146       // redeclaration.
7147       Previous.clear();
7148       Previous.addDecl(Prev);
7149       return true;
7150     }
7151 
7152     // This is a global, non-extern "C" declaration, and there is a previous
7153     // non-global extern "C" declaration. Diagnose if this is a variable
7154     // declaration.
7155     if (!isa<VarDecl>(ND))
7156       return false;
7157   } else {
7158     // The declaration is extern "C". Check for any declaration in the
7159     // translation unit which might conflict.
7160     if (IsGlobal) {
7161       // We have already performed the lookup into the translation unit.
7162       IsGlobal = false;
7163       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7164            I != E; ++I) {
7165         if (isa<VarDecl>(*I)) {
7166           Prev = *I;
7167           break;
7168         }
7169       }
7170     } else {
7171       DeclContext::lookup_result R =
7172           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7173       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7174            I != E; ++I) {
7175         if (isa<VarDecl>(*I)) {
7176           Prev = *I;
7177           break;
7178         }
7179         // FIXME: If we have any other entity with this name in global scope,
7180         // the declaration is ill-formed, but that is a defect: it breaks the
7181         // 'stat' hack, for instance. Only variables can have mangled name
7182         // clashes with extern "C" declarations, so only they deserve a
7183         // diagnostic.
7184       }
7185     }
7186 
7187     if (!Prev)
7188       return false;
7189   }
7190 
7191   // Use the first declaration's location to ensure we point at something which
7192   // is lexically inside an extern "C" linkage-spec.
7193   assert(Prev && "should have found a previous declaration to diagnose");
7194   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7195     Prev = FD->getFirstDecl();
7196   else
7197     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7198 
7199   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7200     << IsGlobal << ND;
7201   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7202     << IsGlobal;
7203   return false;
7204 }
7205 
7206 /// Apply special rules for handling extern "C" declarations. Returns \c true
7207 /// if we have found that this is a redeclaration of some prior entity.
7208 ///
7209 /// Per C++ [dcl.link]p6:
7210 ///   Two declarations [for a function or variable] with C language linkage
7211 ///   with the same name that appear in different scopes refer to the same
7212 ///   [entity]. An entity with C language linkage shall not be declared with
7213 ///   the same name as an entity in global scope.
7214 template<typename T>
7215 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7216                                                   LookupResult &Previous) {
7217   if (!S.getLangOpts().CPlusPlus) {
7218     // In C, when declaring a global variable, look for a corresponding 'extern'
7219     // variable declared in function scope. We don't need this in C++, because
7220     // we find local extern decls in the surrounding file-scope DeclContext.
7221     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7222       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7223         Previous.clear();
7224         Previous.addDecl(Prev);
7225         return true;
7226       }
7227     }
7228     return false;
7229   }
7230 
7231   // A declaration in the translation unit can conflict with an extern "C"
7232   // declaration.
7233   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7234     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7235 
7236   // An extern "C" declaration can conflict with a declaration in the
7237   // translation unit or can be a redeclaration of an extern "C" declaration
7238   // in another scope.
7239   if (isIncompleteDeclExternC(S,ND))
7240     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7241 
7242   // Neither global nor extern "C": nothing to do.
7243   return false;
7244 }
7245 
7246 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7247   // If the decl is already known invalid, don't check it.
7248   if (NewVD->isInvalidDecl())
7249     return;
7250 
7251   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7252   QualType T = TInfo->getType();
7253 
7254   // Defer checking an 'auto' type until its initializer is attached.
7255   if (T->isUndeducedType())
7256     return;
7257 
7258   if (NewVD->hasAttrs())
7259     CheckAlignasUnderalignment(NewVD);
7260 
7261   if (T->isObjCObjectType()) {
7262     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7263       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7264     T = Context.getObjCObjectPointerType(T);
7265     NewVD->setType(T);
7266   }
7267 
7268   // Emit an error if an address space was applied to decl with local storage.
7269   // This includes arrays of objects with address space qualifiers, but not
7270   // automatic variables that point to other address spaces.
7271   // ISO/IEC TR 18037 S5.1.2
7272   if (!getLangOpts().OpenCL
7273       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7274     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7275     NewVD->setInvalidDecl();
7276     return;
7277   }
7278 
7279   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7280   // scope.
7281   if (getLangOpts().OpenCLVersion == 120 &&
7282       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7283       NewVD->isStaticLocal()) {
7284     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7285     NewVD->setInvalidDecl();
7286     return;
7287   }
7288 
7289   if (getLangOpts().OpenCL) {
7290     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7291     if (NewVD->hasAttr<BlocksAttr>()) {
7292       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7293       return;
7294     }
7295 
7296     if (T->isBlockPointerType()) {
7297       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7298       // can't use 'extern' storage class.
7299       if (!T.isConstQualified()) {
7300         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7301             << 0 /*const*/;
7302         NewVD->setInvalidDecl();
7303         return;
7304       }
7305       if (NewVD->hasExternalStorage()) {
7306         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7307         NewVD->setInvalidDecl();
7308         return;
7309       }
7310     }
7311     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7312     // __constant address space.
7313     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7314     // variables inside a function can also be declared in the global
7315     // address space.
7316     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7317         NewVD->hasExternalStorage()) {
7318       if (!T->isSamplerT() &&
7319           !(T.getAddressSpace() == LangAS::opencl_constant ||
7320             (T.getAddressSpace() == LangAS::opencl_global &&
7321              getLangOpts().OpenCLVersion == 200))) {
7322         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7323         if (getLangOpts().OpenCLVersion == 200)
7324           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7325               << Scope << "global or constant";
7326         else
7327           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7328               << Scope << "constant";
7329         NewVD->setInvalidDecl();
7330         return;
7331       }
7332     } else {
7333       if (T.getAddressSpace() == LangAS::opencl_global) {
7334         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7335             << 1 /*is any function*/ << "global";
7336         NewVD->setInvalidDecl();
7337         return;
7338       }
7339       if (T.getAddressSpace() == LangAS::opencl_constant ||
7340           T.getAddressSpace() == LangAS::opencl_local) {
7341         FunctionDecl *FD = getCurFunctionDecl();
7342         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7343         // in functions.
7344         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7345           if (T.getAddressSpace() == LangAS::opencl_constant)
7346             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7347                 << 0 /*non-kernel only*/ << "constant";
7348           else
7349             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7350                 << 0 /*non-kernel only*/ << "local";
7351           NewVD->setInvalidDecl();
7352           return;
7353         }
7354         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7355         // in the outermost scope of a kernel function.
7356         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7357           if (!getCurScope()->isFunctionScope()) {
7358             if (T.getAddressSpace() == LangAS::opencl_constant)
7359               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7360                   << "constant";
7361             else
7362               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7363                   << "local";
7364             NewVD->setInvalidDecl();
7365             return;
7366           }
7367         }
7368       } else if (T.getAddressSpace() != LangAS::Default) {
7369         // Do not allow other address spaces on automatic variable.
7370         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7371         NewVD->setInvalidDecl();
7372         return;
7373       }
7374     }
7375   }
7376 
7377   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7378       && !NewVD->hasAttr<BlocksAttr>()) {
7379     if (getLangOpts().getGC() != LangOptions::NonGC)
7380       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7381     else {
7382       assert(!getLangOpts().ObjCAutoRefCount);
7383       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7384     }
7385   }
7386 
7387   bool isVM = T->isVariablyModifiedType();
7388   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7389       NewVD->hasAttr<BlocksAttr>())
7390     getCurFunction()->setHasBranchProtectedScope();
7391 
7392   if ((isVM && NewVD->hasLinkage()) ||
7393       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7394     bool SizeIsNegative;
7395     llvm::APSInt Oversized;
7396     TypeSourceInfo *FixedTInfo =
7397       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7398                                                     SizeIsNegative, Oversized);
7399     if (!FixedTInfo && T->isVariableArrayType()) {
7400       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7401       // FIXME: This won't give the correct result for
7402       // int a[10][n];
7403       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7404 
7405       if (NewVD->isFileVarDecl())
7406         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7407         << SizeRange;
7408       else if (NewVD->isStaticLocal())
7409         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7410         << SizeRange;
7411       else
7412         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7413         << SizeRange;
7414       NewVD->setInvalidDecl();
7415       return;
7416     }
7417 
7418     if (!FixedTInfo) {
7419       if (NewVD->isFileVarDecl())
7420         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7421       else
7422         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7423       NewVD->setInvalidDecl();
7424       return;
7425     }
7426 
7427     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7428     NewVD->setType(FixedTInfo->getType());
7429     NewVD->setTypeSourceInfo(FixedTInfo);
7430   }
7431 
7432   if (T->isVoidType()) {
7433     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7434     //                    of objects and functions.
7435     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7436       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7437         << T;
7438       NewVD->setInvalidDecl();
7439       return;
7440     }
7441   }
7442 
7443   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7444     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7445     NewVD->setInvalidDecl();
7446     return;
7447   }
7448 
7449   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7450     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7451     NewVD->setInvalidDecl();
7452     return;
7453   }
7454 
7455   if (NewVD->isConstexpr() && !T->isDependentType() &&
7456       RequireLiteralType(NewVD->getLocation(), T,
7457                          diag::err_constexpr_var_non_literal)) {
7458     NewVD->setInvalidDecl();
7459     return;
7460   }
7461 }
7462 
7463 /// \brief Perform semantic checking on a newly-created variable
7464 /// declaration.
7465 ///
7466 /// This routine performs all of the type-checking required for a
7467 /// variable declaration once it has been built. It is used both to
7468 /// check variables after they have been parsed and their declarators
7469 /// have been translated into a declaration, and to check variables
7470 /// that have been instantiated from a template.
7471 ///
7472 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7473 ///
7474 /// Returns true if the variable declaration is a redeclaration.
7475 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7476   CheckVariableDeclarationType(NewVD);
7477 
7478   // If the decl is already known invalid, don't check it.
7479   if (NewVD->isInvalidDecl())
7480     return false;
7481 
7482   // If we did not find anything by this name, look for a non-visible
7483   // extern "C" declaration with the same name.
7484   if (Previous.empty() &&
7485       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7486     Previous.setShadowed();
7487 
7488   if (!Previous.empty()) {
7489     MergeVarDecl(NewVD, Previous);
7490     return true;
7491   }
7492   return false;
7493 }
7494 
7495 namespace {
7496 struct FindOverriddenMethod {
7497   Sema *S;
7498   CXXMethodDecl *Method;
7499 
7500   /// Member lookup function that determines whether a given C++
7501   /// method overrides a method in a base class, to be used with
7502   /// CXXRecordDecl::lookupInBases().
7503   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7504     RecordDecl *BaseRecord =
7505         Specifier->getType()->getAs<RecordType>()->getDecl();
7506 
7507     DeclarationName Name = Method->getDeclName();
7508 
7509     // FIXME: Do we care about other names here too?
7510     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7511       // We really want to find the base class destructor here.
7512       QualType T = S->Context.getTypeDeclType(BaseRecord);
7513       CanQualType CT = S->Context.getCanonicalType(T);
7514 
7515       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7516     }
7517 
7518     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7519          Path.Decls = Path.Decls.slice(1)) {
7520       NamedDecl *D = Path.Decls.front();
7521       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7522         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7523           return true;
7524       }
7525     }
7526 
7527     return false;
7528   }
7529 };
7530 
7531 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7532 } // end anonymous namespace
7533 
7534 /// \brief Report an error regarding overriding, along with any relevant
7535 /// overriden methods.
7536 ///
7537 /// \param DiagID the primary error to report.
7538 /// \param MD the overriding method.
7539 /// \param OEK which overrides to include as notes.
7540 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7541                             OverrideErrorKind OEK = OEK_All) {
7542   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7543   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7544                                       E = MD->end_overridden_methods();
7545        I != E; ++I) {
7546     // This check (& the OEK parameter) could be replaced by a predicate, but
7547     // without lambdas that would be overkill. This is still nicer than writing
7548     // out the diag loop 3 times.
7549     if ((OEK == OEK_All) ||
7550         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7551         (OEK == OEK_Deleted && (*I)->isDeleted()))
7552       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7553   }
7554 }
7555 
7556 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7557 /// and if so, check that it's a valid override and remember it.
7558 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7559   // Look for methods in base classes that this method might override.
7560   CXXBasePaths Paths;
7561   FindOverriddenMethod FOM;
7562   FOM.Method = MD;
7563   FOM.S = this;
7564   bool hasDeletedOverridenMethods = false;
7565   bool hasNonDeletedOverridenMethods = false;
7566   bool AddedAny = false;
7567   if (DC->lookupInBases(FOM, Paths)) {
7568     for (auto *I : Paths.found_decls()) {
7569       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7570         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7571         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7572             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7573             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7574             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7575           hasDeletedOverridenMethods |= OldMD->isDeleted();
7576           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7577           AddedAny = true;
7578         }
7579       }
7580     }
7581   }
7582 
7583   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7584     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7585   }
7586   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7587     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7588   }
7589 
7590   return AddedAny;
7591 }
7592 
7593 namespace {
7594   // Struct for holding all of the extra arguments needed by
7595   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7596   struct ActOnFDArgs {
7597     Scope *S;
7598     Declarator &D;
7599     MultiTemplateParamsArg TemplateParamLists;
7600     bool AddToScope;
7601   };
7602 } // end anonymous namespace
7603 
7604 namespace {
7605 
7606 // Callback to only accept typo corrections that have a non-zero edit distance.
7607 // Also only accept corrections that have the same parent decl.
7608 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7609  public:
7610   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7611                             CXXRecordDecl *Parent)
7612       : Context(Context), OriginalFD(TypoFD),
7613         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7614 
7615   bool ValidateCandidate(const TypoCorrection &candidate) override {
7616     if (candidate.getEditDistance() == 0)
7617       return false;
7618 
7619     SmallVector<unsigned, 1> MismatchedParams;
7620     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7621                                           CDeclEnd = candidate.end();
7622          CDecl != CDeclEnd; ++CDecl) {
7623       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7624 
7625       if (FD && !FD->hasBody() &&
7626           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7627         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7628           CXXRecordDecl *Parent = MD->getParent();
7629           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7630             return true;
7631         } else if (!ExpectedParent) {
7632           return true;
7633         }
7634       }
7635     }
7636 
7637     return false;
7638   }
7639 
7640  private:
7641   ASTContext &Context;
7642   FunctionDecl *OriginalFD;
7643   CXXRecordDecl *ExpectedParent;
7644 };
7645 
7646 } // end anonymous namespace
7647 
7648 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7649   TypoCorrectedFunctionDefinitions.insert(F);
7650 }
7651 
7652 /// \brief Generate diagnostics for an invalid function redeclaration.
7653 ///
7654 /// This routine handles generating the diagnostic messages for an invalid
7655 /// function redeclaration, including finding possible similar declarations
7656 /// or performing typo correction if there are no previous declarations with
7657 /// the same name.
7658 ///
7659 /// Returns a NamedDecl iff typo correction was performed and substituting in
7660 /// the new declaration name does not cause new errors.
7661 static NamedDecl *DiagnoseInvalidRedeclaration(
7662     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7663     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7664   DeclarationName Name = NewFD->getDeclName();
7665   DeclContext *NewDC = NewFD->getDeclContext();
7666   SmallVector<unsigned, 1> MismatchedParams;
7667   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7668   TypoCorrection Correction;
7669   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7670   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7671                                    : diag::err_member_decl_does_not_match;
7672   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7673                     IsLocalFriend ? Sema::LookupLocalFriendName
7674                                   : Sema::LookupOrdinaryName,
7675                     Sema::ForRedeclaration);
7676 
7677   NewFD->setInvalidDecl();
7678   if (IsLocalFriend)
7679     SemaRef.LookupName(Prev, S);
7680   else
7681     SemaRef.LookupQualifiedName(Prev, NewDC);
7682   assert(!Prev.isAmbiguous() &&
7683          "Cannot have an ambiguity in previous-declaration lookup");
7684   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7685   if (!Prev.empty()) {
7686     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7687          Func != FuncEnd; ++Func) {
7688       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7689       if (FD &&
7690           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7691         // Add 1 to the index so that 0 can mean the mismatch didn't
7692         // involve a parameter
7693         unsigned ParamNum =
7694             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7695         NearMatches.push_back(std::make_pair(FD, ParamNum));
7696       }
7697     }
7698   // If the qualified name lookup yielded nothing, try typo correction
7699   } else if ((Correction = SemaRef.CorrectTypo(
7700                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7701                   &ExtraArgs.D.getCXXScopeSpec(),
7702                   llvm::make_unique<DifferentNameValidatorCCC>(
7703                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7704                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7705     // Set up everything for the call to ActOnFunctionDeclarator
7706     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7707                               ExtraArgs.D.getIdentifierLoc());
7708     Previous.clear();
7709     Previous.setLookupName(Correction.getCorrection());
7710     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7711                                     CDeclEnd = Correction.end();
7712          CDecl != CDeclEnd; ++CDecl) {
7713       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7714       if (FD && !FD->hasBody() &&
7715           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7716         Previous.addDecl(FD);
7717       }
7718     }
7719     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7720 
7721     NamedDecl *Result;
7722     // Retry building the function declaration with the new previous
7723     // declarations, and with errors suppressed.
7724     {
7725       // Trap errors.
7726       Sema::SFINAETrap Trap(SemaRef);
7727 
7728       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7729       // pieces need to verify the typo-corrected C++ declaration and hopefully
7730       // eliminate the need for the parameter pack ExtraArgs.
7731       Result = SemaRef.ActOnFunctionDeclarator(
7732           ExtraArgs.S, ExtraArgs.D,
7733           Correction.getCorrectionDecl()->getDeclContext(),
7734           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7735           ExtraArgs.AddToScope);
7736 
7737       if (Trap.hasErrorOccurred())
7738         Result = nullptr;
7739     }
7740 
7741     if (Result) {
7742       // Determine which correction we picked.
7743       Decl *Canonical = Result->getCanonicalDecl();
7744       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7745            I != E; ++I)
7746         if ((*I)->getCanonicalDecl() == Canonical)
7747           Correction.setCorrectionDecl(*I);
7748 
7749       // Let Sema know about the correction.
7750       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7751       SemaRef.diagnoseTypo(
7752           Correction,
7753           SemaRef.PDiag(IsLocalFriend
7754                           ? diag::err_no_matching_local_friend_suggest
7755                           : diag::err_member_decl_does_not_match_suggest)
7756             << Name << NewDC << IsDefinition);
7757       return Result;
7758     }
7759 
7760     // Pretend the typo correction never occurred
7761     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7762                               ExtraArgs.D.getIdentifierLoc());
7763     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7764     Previous.clear();
7765     Previous.setLookupName(Name);
7766   }
7767 
7768   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7769       << Name << NewDC << IsDefinition << NewFD->getLocation();
7770 
7771   bool NewFDisConst = false;
7772   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7773     NewFDisConst = NewMD->isConst();
7774 
7775   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7776        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7777        NearMatch != NearMatchEnd; ++NearMatch) {
7778     FunctionDecl *FD = NearMatch->first;
7779     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7780     bool FDisConst = MD && MD->isConst();
7781     bool IsMember = MD || !IsLocalFriend;
7782 
7783     // FIXME: These notes are poorly worded for the local friend case.
7784     if (unsigned Idx = NearMatch->second) {
7785       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7786       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7787       if (Loc.isInvalid()) Loc = FD->getLocation();
7788       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7789                                  : diag::note_local_decl_close_param_match)
7790         << Idx << FDParam->getType()
7791         << NewFD->getParamDecl(Idx - 1)->getType();
7792     } else if (FDisConst != NewFDisConst) {
7793       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7794           << NewFDisConst << FD->getSourceRange().getEnd();
7795     } else
7796       SemaRef.Diag(FD->getLocation(),
7797                    IsMember ? diag::note_member_def_close_match
7798                             : diag::note_local_decl_close_match);
7799   }
7800   return nullptr;
7801 }
7802 
7803 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7804   switch (D.getDeclSpec().getStorageClassSpec()) {
7805   default: llvm_unreachable("Unknown storage class!");
7806   case DeclSpec::SCS_auto:
7807   case DeclSpec::SCS_register:
7808   case DeclSpec::SCS_mutable:
7809     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7810                  diag::err_typecheck_sclass_func);
7811     D.getMutableDeclSpec().ClearStorageClassSpecs();
7812     D.setInvalidType();
7813     break;
7814   case DeclSpec::SCS_unspecified: break;
7815   case DeclSpec::SCS_extern:
7816     if (D.getDeclSpec().isExternInLinkageSpec())
7817       return SC_None;
7818     return SC_Extern;
7819   case DeclSpec::SCS_static: {
7820     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7821       // C99 6.7.1p5:
7822       //   The declaration of an identifier for a function that has
7823       //   block scope shall have no explicit storage-class specifier
7824       //   other than extern
7825       // See also (C++ [dcl.stc]p4).
7826       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7827                    diag::err_static_block_func);
7828       break;
7829     } else
7830       return SC_Static;
7831   }
7832   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7833   }
7834 
7835   // No explicit storage class has already been returned
7836   return SC_None;
7837 }
7838 
7839 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7840                                            DeclContext *DC, QualType &R,
7841                                            TypeSourceInfo *TInfo,
7842                                            StorageClass SC,
7843                                            bool &IsVirtualOkay) {
7844   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7845   DeclarationName Name = NameInfo.getName();
7846 
7847   FunctionDecl *NewFD = nullptr;
7848   bool isInline = D.getDeclSpec().isInlineSpecified();
7849 
7850   if (!SemaRef.getLangOpts().CPlusPlus) {
7851     // Determine whether the function was written with a
7852     // prototype. This true when:
7853     //   - there is a prototype in the declarator, or
7854     //   - the type R of the function is some kind of typedef or other non-
7855     //     attributed reference to a type name (which eventually refers to a
7856     //     function type).
7857     bool HasPrototype =
7858       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7859       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7860 
7861     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7862                                  D.getLocStart(), NameInfo, R,
7863                                  TInfo, SC, isInline,
7864                                  HasPrototype, false);
7865     if (D.isInvalidType())
7866       NewFD->setInvalidDecl();
7867 
7868     return NewFD;
7869   }
7870 
7871   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7872   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7873 
7874   // Check that the return type is not an abstract class type.
7875   // For record types, this is done by the AbstractClassUsageDiagnoser once
7876   // the class has been completely parsed.
7877   if (!DC->isRecord() &&
7878       SemaRef.RequireNonAbstractType(
7879           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7880           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7881     D.setInvalidType();
7882 
7883   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7884     // This is a C++ constructor declaration.
7885     assert(DC->isRecord() &&
7886            "Constructors can only be declared in a member context");
7887 
7888     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7889     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7890                                       D.getLocStart(), NameInfo,
7891                                       R, TInfo, isExplicit, isInline,
7892                                       /*isImplicitlyDeclared=*/false,
7893                                       isConstexpr);
7894 
7895   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7896     // This is a C++ destructor declaration.
7897     if (DC->isRecord()) {
7898       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7899       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7900       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7901                                         SemaRef.Context, Record,
7902                                         D.getLocStart(),
7903                                         NameInfo, R, TInfo, isInline,
7904                                         /*isImplicitlyDeclared=*/false);
7905 
7906       // If the class is complete, then we now create the implicit exception
7907       // specification. If the class is incomplete or dependent, we can't do
7908       // it yet.
7909       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7910           Record->getDefinition() && !Record->isBeingDefined() &&
7911           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7912         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7913       }
7914 
7915       IsVirtualOkay = true;
7916       return NewDD;
7917 
7918     } else {
7919       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7920       D.setInvalidType();
7921 
7922       // Create a FunctionDecl to satisfy the function definition parsing
7923       // code path.
7924       return FunctionDecl::Create(SemaRef.Context, DC,
7925                                   D.getLocStart(),
7926                                   D.getIdentifierLoc(), Name, R, TInfo,
7927                                   SC, isInline,
7928                                   /*hasPrototype=*/true, isConstexpr);
7929     }
7930 
7931   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7932     if (!DC->isRecord()) {
7933       SemaRef.Diag(D.getIdentifierLoc(),
7934            diag::err_conv_function_not_member);
7935       return nullptr;
7936     }
7937 
7938     SemaRef.CheckConversionDeclarator(D, R, SC);
7939     IsVirtualOkay = true;
7940     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7941                                      D.getLocStart(), NameInfo,
7942                                      R, TInfo, isInline, isExplicit,
7943                                      isConstexpr, SourceLocation());
7944 
7945   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7946     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7947 
7948     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7949                                          isExplicit, NameInfo, R, TInfo,
7950                                          D.getLocEnd());
7951   } else if (DC->isRecord()) {
7952     // If the name of the function is the same as the name of the record,
7953     // then this must be an invalid constructor that has a return type.
7954     // (The parser checks for a return type and makes the declarator a
7955     // constructor if it has no return type).
7956     if (Name.getAsIdentifierInfo() &&
7957         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7958       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7959         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7960         << SourceRange(D.getIdentifierLoc());
7961       return nullptr;
7962     }
7963 
7964     // This is a C++ method declaration.
7965     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7966                                                cast<CXXRecordDecl>(DC),
7967                                                D.getLocStart(), NameInfo, R,
7968                                                TInfo, SC, isInline,
7969                                                isConstexpr, SourceLocation());
7970     IsVirtualOkay = !Ret->isStatic();
7971     return Ret;
7972   } else {
7973     bool isFriend =
7974         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7975     if (!isFriend && SemaRef.CurContext->isRecord())
7976       return nullptr;
7977 
7978     // Determine whether the function was written with a
7979     // prototype. This true when:
7980     //   - we're in C++ (where every function has a prototype),
7981     return FunctionDecl::Create(SemaRef.Context, DC,
7982                                 D.getLocStart(),
7983                                 NameInfo, R, TInfo, SC, isInline,
7984                                 true/*HasPrototype*/, isConstexpr);
7985   }
7986 }
7987 
7988 enum OpenCLParamType {
7989   ValidKernelParam,
7990   PtrPtrKernelParam,
7991   PtrKernelParam,
7992   InvalidAddrSpacePtrKernelParam,
7993   InvalidKernelParam,
7994   RecordKernelParam
7995 };
7996 
7997 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7998   if (PT->isPointerType()) {
7999     QualType PointeeType = PT->getPointeeType();
8000     if (PointeeType->isPointerType())
8001       return PtrPtrKernelParam;
8002     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8003         PointeeType.getAddressSpace() == 0)
8004       return InvalidAddrSpacePtrKernelParam;
8005     return PtrKernelParam;
8006   }
8007 
8008   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8009   // be used as builtin types.
8010 
8011   if (PT->isImageType())
8012     return PtrKernelParam;
8013 
8014   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8015     return InvalidKernelParam;
8016 
8017   // OpenCL extension spec v1.2 s9.5:
8018   // This extension adds support for half scalar and vector types as built-in
8019   // types that can be used for arithmetic operations, conversions etc.
8020   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8021     return InvalidKernelParam;
8022 
8023   if (PT->isRecordType())
8024     return RecordKernelParam;
8025 
8026   return ValidKernelParam;
8027 }
8028 
8029 static void checkIsValidOpenCLKernelParameter(
8030   Sema &S,
8031   Declarator &D,
8032   ParmVarDecl *Param,
8033   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8034   QualType PT = Param->getType();
8035 
8036   // Cache the valid types we encounter to avoid rechecking structs that are
8037   // used again
8038   if (ValidTypes.count(PT.getTypePtr()))
8039     return;
8040 
8041   switch (getOpenCLKernelParameterType(S, PT)) {
8042   case PtrPtrKernelParam:
8043     // OpenCL v1.2 s6.9.a:
8044     // A kernel function argument cannot be declared as a
8045     // pointer to a pointer type.
8046     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8047     D.setInvalidType();
8048     return;
8049 
8050   case InvalidAddrSpacePtrKernelParam:
8051     // OpenCL v1.0 s6.5:
8052     // __kernel function arguments declared to be a pointer of a type can point
8053     // to one of the following address spaces only : __global, __local or
8054     // __constant.
8055     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8056     D.setInvalidType();
8057     return;
8058 
8059     // OpenCL v1.2 s6.9.k:
8060     // Arguments to kernel functions in a program cannot be declared with the
8061     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8062     // uintptr_t or a struct and/or union that contain fields declared to be
8063     // one of these built-in scalar types.
8064 
8065   case InvalidKernelParam:
8066     // OpenCL v1.2 s6.8 n:
8067     // A kernel function argument cannot be declared
8068     // of event_t type.
8069     // Do not diagnose half type since it is diagnosed as invalid argument
8070     // type for any function elsewhere.
8071     if (!PT->isHalfType())
8072       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8073     D.setInvalidType();
8074     return;
8075 
8076   case PtrKernelParam:
8077   case ValidKernelParam:
8078     ValidTypes.insert(PT.getTypePtr());
8079     return;
8080 
8081   case RecordKernelParam:
8082     break;
8083   }
8084 
8085   // Track nested structs we will inspect
8086   SmallVector<const Decl *, 4> VisitStack;
8087 
8088   // Track where we are in the nested structs. Items will migrate from
8089   // VisitStack to HistoryStack as we do the DFS for bad field.
8090   SmallVector<const FieldDecl *, 4> HistoryStack;
8091   HistoryStack.push_back(nullptr);
8092 
8093   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8094   VisitStack.push_back(PD);
8095 
8096   assert(VisitStack.back() && "First decl null?");
8097 
8098   do {
8099     const Decl *Next = VisitStack.pop_back_val();
8100     if (!Next) {
8101       assert(!HistoryStack.empty());
8102       // Found a marker, we have gone up a level
8103       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8104         ValidTypes.insert(Hist->getType().getTypePtr());
8105 
8106       continue;
8107     }
8108 
8109     // Adds everything except the original parameter declaration (which is not a
8110     // field itself) to the history stack.
8111     const RecordDecl *RD;
8112     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8113       HistoryStack.push_back(Field);
8114       RD = Field->getType()->castAs<RecordType>()->getDecl();
8115     } else {
8116       RD = cast<RecordDecl>(Next);
8117     }
8118 
8119     // Add a null marker so we know when we've gone back up a level
8120     VisitStack.push_back(nullptr);
8121 
8122     for (const auto *FD : RD->fields()) {
8123       QualType QT = FD->getType();
8124 
8125       if (ValidTypes.count(QT.getTypePtr()))
8126         continue;
8127 
8128       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8129       if (ParamType == ValidKernelParam)
8130         continue;
8131 
8132       if (ParamType == RecordKernelParam) {
8133         VisitStack.push_back(FD);
8134         continue;
8135       }
8136 
8137       // OpenCL v1.2 s6.9.p:
8138       // Arguments to kernel functions that are declared to be a struct or union
8139       // do not allow OpenCL objects to be passed as elements of the struct or
8140       // union.
8141       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8142           ParamType == InvalidAddrSpacePtrKernelParam) {
8143         S.Diag(Param->getLocation(),
8144                diag::err_record_with_pointers_kernel_param)
8145           << PT->isUnionType()
8146           << PT;
8147       } else {
8148         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8149       }
8150 
8151       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8152         << PD->getDeclName();
8153 
8154       // We have an error, now let's go back up through history and show where
8155       // the offending field came from
8156       for (ArrayRef<const FieldDecl *>::const_iterator
8157                I = HistoryStack.begin() + 1,
8158                E = HistoryStack.end();
8159            I != E; ++I) {
8160         const FieldDecl *OuterField = *I;
8161         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8162           << OuterField->getType();
8163       }
8164 
8165       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8166         << QT->isPointerType()
8167         << QT;
8168       D.setInvalidType();
8169       return;
8170     }
8171   } while (!VisitStack.empty());
8172 }
8173 
8174 /// Find the DeclContext in which a tag is implicitly declared if we see an
8175 /// elaborated type specifier in the specified context, and lookup finds
8176 /// nothing.
8177 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8178   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8179     DC = DC->getParent();
8180   return DC;
8181 }
8182 
8183 /// Find the Scope in which a tag is implicitly declared if we see an
8184 /// elaborated type specifier in the specified context, and lookup finds
8185 /// nothing.
8186 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8187   while (S->isClassScope() ||
8188          (LangOpts.CPlusPlus &&
8189           S->isFunctionPrototypeScope()) ||
8190          ((S->getFlags() & Scope::DeclScope) == 0) ||
8191          (S->getEntity() && S->getEntity()->isTransparentContext()))
8192     S = S->getParent();
8193   return S;
8194 }
8195 
8196 NamedDecl*
8197 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8198                               TypeSourceInfo *TInfo, LookupResult &Previous,
8199                               MultiTemplateParamsArg TemplateParamLists,
8200                               bool &AddToScope) {
8201   QualType R = TInfo->getType();
8202 
8203   assert(R.getTypePtr()->isFunctionType());
8204 
8205   // TODO: consider using NameInfo for diagnostic.
8206   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8207   DeclarationName Name = NameInfo.getName();
8208   StorageClass SC = getFunctionStorageClass(*this, D);
8209 
8210   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8211     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8212          diag::err_invalid_thread)
8213       << DeclSpec::getSpecifierName(TSCS);
8214 
8215   if (D.isFirstDeclarationOfMember())
8216     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8217                            D.getIdentifierLoc());
8218 
8219   bool isFriend = false;
8220   FunctionTemplateDecl *FunctionTemplate = nullptr;
8221   bool isMemberSpecialization = false;
8222   bool isFunctionTemplateSpecialization = false;
8223 
8224   bool isDependentClassScopeExplicitSpecialization = false;
8225   bool HasExplicitTemplateArgs = false;
8226   TemplateArgumentListInfo TemplateArgs;
8227 
8228   bool isVirtualOkay = false;
8229 
8230   DeclContext *OriginalDC = DC;
8231   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8232 
8233   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8234                                               isVirtualOkay);
8235   if (!NewFD) return nullptr;
8236 
8237   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8238     NewFD->setTopLevelDeclInObjCContainer();
8239 
8240   // Set the lexical context. If this is a function-scope declaration, or has a
8241   // C++ scope specifier, or is the object of a friend declaration, the lexical
8242   // context will be different from the semantic context.
8243   NewFD->setLexicalDeclContext(CurContext);
8244 
8245   if (IsLocalExternDecl)
8246     NewFD->setLocalExternDecl();
8247 
8248   if (getLangOpts().CPlusPlus) {
8249     bool isInline = D.getDeclSpec().isInlineSpecified();
8250     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8251     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8252     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8253     bool isConcept = D.getDeclSpec().isConceptSpecified();
8254     isFriend = D.getDeclSpec().isFriendSpecified();
8255     if (isFriend && !isInline && D.isFunctionDefinition()) {
8256       // C++ [class.friend]p5
8257       //   A function can be defined in a friend declaration of a
8258       //   class . . . . Such a function is implicitly inline.
8259       NewFD->setImplicitlyInline();
8260     }
8261 
8262     // If this is a method defined in an __interface, and is not a constructor
8263     // or an overloaded operator, then set the pure flag (isVirtual will already
8264     // return true).
8265     if (const CXXRecordDecl *Parent =
8266           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8267       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8268         NewFD->setPure(true);
8269 
8270       // C++ [class.union]p2
8271       //   A union can have member functions, but not virtual functions.
8272       if (isVirtual && Parent->isUnion())
8273         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8274     }
8275 
8276     SetNestedNameSpecifier(NewFD, D);
8277     isMemberSpecialization = false;
8278     isFunctionTemplateSpecialization = false;
8279     if (D.isInvalidType())
8280       NewFD->setInvalidDecl();
8281 
8282     // Match up the template parameter lists with the scope specifier, then
8283     // determine whether we have a template or a template specialization.
8284     bool Invalid = false;
8285     if (TemplateParameterList *TemplateParams =
8286             MatchTemplateParametersToScopeSpecifier(
8287                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8288                 D.getCXXScopeSpec(),
8289                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8290                     ? D.getName().TemplateId
8291                     : nullptr,
8292                 TemplateParamLists, isFriend, isMemberSpecialization,
8293                 Invalid)) {
8294       if (TemplateParams->size() > 0) {
8295         // This is a function template
8296 
8297         // Check that we can declare a template here.
8298         if (CheckTemplateDeclScope(S, TemplateParams))
8299           NewFD->setInvalidDecl();
8300 
8301         // A destructor cannot be a template.
8302         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8303           Diag(NewFD->getLocation(), diag::err_destructor_template);
8304           NewFD->setInvalidDecl();
8305         }
8306 
8307         // If we're adding a template to a dependent context, we may need to
8308         // rebuilding some of the types used within the template parameter list,
8309         // now that we know what the current instantiation is.
8310         if (DC->isDependentContext()) {
8311           ContextRAII SavedContext(*this, DC);
8312           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8313             Invalid = true;
8314         }
8315 
8316         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8317                                                         NewFD->getLocation(),
8318                                                         Name, TemplateParams,
8319                                                         NewFD);
8320         FunctionTemplate->setLexicalDeclContext(CurContext);
8321         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8322 
8323         // For source fidelity, store the other template param lists.
8324         if (TemplateParamLists.size() > 1) {
8325           NewFD->setTemplateParameterListsInfo(Context,
8326                                                TemplateParamLists.drop_back(1));
8327         }
8328       } else {
8329         // This is a function template specialization.
8330         isFunctionTemplateSpecialization = true;
8331         // For source fidelity, store all the template param lists.
8332         if (TemplateParamLists.size() > 0)
8333           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8334 
8335         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8336         if (isFriend) {
8337           // We want to remove the "template<>", found here.
8338           SourceRange RemoveRange = TemplateParams->getSourceRange();
8339 
8340           // If we remove the template<> and the name is not a
8341           // template-id, we're actually silently creating a problem:
8342           // the friend declaration will refer to an untemplated decl,
8343           // and clearly the user wants a template specialization.  So
8344           // we need to insert '<>' after the name.
8345           SourceLocation InsertLoc;
8346           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8347             InsertLoc = D.getName().getSourceRange().getEnd();
8348             InsertLoc = getLocForEndOfToken(InsertLoc);
8349           }
8350 
8351           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8352             << Name << RemoveRange
8353             << FixItHint::CreateRemoval(RemoveRange)
8354             << FixItHint::CreateInsertion(InsertLoc, "<>");
8355         }
8356       }
8357     }
8358     else {
8359       // All template param lists were matched against the scope specifier:
8360       // this is NOT (an explicit specialization of) a template.
8361       if (TemplateParamLists.size() > 0)
8362         // For source fidelity, store all the template param lists.
8363         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8364     }
8365 
8366     if (Invalid) {
8367       NewFD->setInvalidDecl();
8368       if (FunctionTemplate)
8369         FunctionTemplate->setInvalidDecl();
8370     }
8371 
8372     // C++ [dcl.fct.spec]p5:
8373     //   The virtual specifier shall only be used in declarations of
8374     //   nonstatic class member functions that appear within a
8375     //   member-specification of a class declaration; see 10.3.
8376     //
8377     if (isVirtual && !NewFD->isInvalidDecl()) {
8378       if (!isVirtualOkay) {
8379         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8380              diag::err_virtual_non_function);
8381       } else if (!CurContext->isRecord()) {
8382         // 'virtual' was specified outside of the class.
8383         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8384              diag::err_virtual_out_of_class)
8385           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8386       } else if (NewFD->getDescribedFunctionTemplate()) {
8387         // C++ [temp.mem]p3:
8388         //  A member function template shall not be virtual.
8389         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8390              diag::err_virtual_member_function_template)
8391           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8392       } else {
8393         // Okay: Add virtual to the method.
8394         NewFD->setVirtualAsWritten(true);
8395       }
8396 
8397       if (getLangOpts().CPlusPlus14 &&
8398           NewFD->getReturnType()->isUndeducedType())
8399         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8400     }
8401 
8402     if (getLangOpts().CPlusPlus14 &&
8403         (NewFD->isDependentContext() ||
8404          (isFriend && CurContext->isDependentContext())) &&
8405         NewFD->getReturnType()->isUndeducedType()) {
8406       // If the function template is referenced directly (for instance, as a
8407       // member of the current instantiation), pretend it has a dependent type.
8408       // This is not really justified by the standard, but is the only sane
8409       // thing to do.
8410       // FIXME: For a friend function, we have not marked the function as being
8411       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8412       const FunctionProtoType *FPT =
8413           NewFD->getType()->castAs<FunctionProtoType>();
8414       QualType Result =
8415           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8416       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8417                                              FPT->getExtProtoInfo()));
8418     }
8419 
8420     // C++ [dcl.fct.spec]p3:
8421     //  The inline specifier shall not appear on a block scope function
8422     //  declaration.
8423     if (isInline && !NewFD->isInvalidDecl()) {
8424       if (CurContext->isFunctionOrMethod()) {
8425         // 'inline' is not allowed on block scope function declaration.
8426         Diag(D.getDeclSpec().getInlineSpecLoc(),
8427              diag::err_inline_declaration_block_scope) << Name
8428           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8429       }
8430     }
8431 
8432     // C++ [dcl.fct.spec]p6:
8433     //  The explicit specifier shall be used only in the declaration of a
8434     //  constructor or conversion function within its class definition;
8435     //  see 12.3.1 and 12.3.2.
8436     if (isExplicit && !NewFD->isInvalidDecl() &&
8437         !isa<CXXDeductionGuideDecl>(NewFD)) {
8438       if (!CurContext->isRecord()) {
8439         // 'explicit' was specified outside of the class.
8440         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8441              diag::err_explicit_out_of_class)
8442           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8443       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8444                  !isa<CXXConversionDecl>(NewFD)) {
8445         // 'explicit' was specified on a function that wasn't a constructor
8446         // or conversion function.
8447         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8448              diag::err_explicit_non_ctor_or_conv_function)
8449           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8450       }
8451     }
8452 
8453     if (isConstexpr) {
8454       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8455       // are implicitly inline.
8456       NewFD->setImplicitlyInline();
8457 
8458       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8459       // be either constructors or to return a literal type. Therefore,
8460       // destructors cannot be declared constexpr.
8461       if (isa<CXXDestructorDecl>(NewFD))
8462         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8463     }
8464 
8465     if (isConcept) {
8466       // This is a function concept.
8467       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8468         FTD->setConcept();
8469 
8470       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8471       // applied only to the definition of a function template [...]
8472       if (!D.isFunctionDefinition()) {
8473         Diag(D.getDeclSpec().getConceptSpecLoc(),
8474              diag::err_function_concept_not_defined);
8475         NewFD->setInvalidDecl();
8476       }
8477 
8478       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8479       // have no exception-specification and is treated as if it were specified
8480       // with noexcept(true) (15.4). [...]
8481       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8482         if (FPT->hasExceptionSpec()) {
8483           SourceRange Range;
8484           if (D.isFunctionDeclarator())
8485             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8486           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8487               << FixItHint::CreateRemoval(Range);
8488           NewFD->setInvalidDecl();
8489         } else {
8490           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8491         }
8492 
8493         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8494         // following restrictions:
8495         // - The declared return type shall have the type bool.
8496         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8497           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8498           NewFD->setInvalidDecl();
8499         }
8500 
8501         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8502         // following restrictions:
8503         // - The declaration's parameter list shall be equivalent to an empty
8504         //   parameter list.
8505         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8506           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8507       }
8508 
8509       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8510       // implicity defined to be a constexpr declaration (implicitly inline)
8511       NewFD->setImplicitlyInline();
8512 
8513       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8514       // be declared with the thread_local, inline, friend, or constexpr
8515       // specifiers, [...]
8516       if (isInline) {
8517         Diag(D.getDeclSpec().getInlineSpecLoc(),
8518              diag::err_concept_decl_invalid_specifiers)
8519             << 1 << 1;
8520         NewFD->setInvalidDecl(true);
8521       }
8522 
8523       if (isFriend) {
8524         Diag(D.getDeclSpec().getFriendSpecLoc(),
8525              diag::err_concept_decl_invalid_specifiers)
8526             << 1 << 2;
8527         NewFD->setInvalidDecl(true);
8528       }
8529 
8530       if (isConstexpr) {
8531         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8532              diag::err_concept_decl_invalid_specifiers)
8533             << 1 << 3;
8534         NewFD->setInvalidDecl(true);
8535       }
8536 
8537       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8538       // applied only to the definition of a function template or variable
8539       // template, declared in namespace scope.
8540       if (isFunctionTemplateSpecialization) {
8541         Diag(D.getDeclSpec().getConceptSpecLoc(),
8542              diag::err_concept_specified_specialization) << 1;
8543         NewFD->setInvalidDecl(true);
8544         return NewFD;
8545       }
8546     }
8547 
8548     // If __module_private__ was specified, mark the function accordingly.
8549     if (D.getDeclSpec().isModulePrivateSpecified()) {
8550       if (isFunctionTemplateSpecialization) {
8551         SourceLocation ModulePrivateLoc
8552           = D.getDeclSpec().getModulePrivateSpecLoc();
8553         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8554           << 0
8555           << FixItHint::CreateRemoval(ModulePrivateLoc);
8556       } else {
8557         NewFD->setModulePrivate();
8558         if (FunctionTemplate)
8559           FunctionTemplate->setModulePrivate();
8560       }
8561     }
8562 
8563     if (isFriend) {
8564       if (FunctionTemplate) {
8565         FunctionTemplate->setObjectOfFriendDecl();
8566         FunctionTemplate->setAccess(AS_public);
8567       }
8568       NewFD->setObjectOfFriendDecl();
8569       NewFD->setAccess(AS_public);
8570     }
8571 
8572     // If a function is defined as defaulted or deleted, mark it as such now.
8573     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8574     // definition kind to FDK_Definition.
8575     switch (D.getFunctionDefinitionKind()) {
8576       case FDK_Declaration:
8577       case FDK_Definition:
8578         break;
8579 
8580       case FDK_Defaulted:
8581         NewFD->setDefaulted();
8582         break;
8583 
8584       case FDK_Deleted:
8585         NewFD->setDeletedAsWritten();
8586         break;
8587     }
8588 
8589     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8590         D.isFunctionDefinition()) {
8591       // C++ [class.mfct]p2:
8592       //   A member function may be defined (8.4) in its class definition, in
8593       //   which case it is an inline member function (7.1.2)
8594       NewFD->setImplicitlyInline();
8595     }
8596 
8597     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8598         !CurContext->isRecord()) {
8599       // C++ [class.static]p1:
8600       //   A data or function member of a class may be declared static
8601       //   in a class definition, in which case it is a static member of
8602       //   the class.
8603 
8604       // Complain about the 'static' specifier if it's on an out-of-line
8605       // member function definition.
8606       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8607            diag::err_static_out_of_line)
8608         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8609     }
8610 
8611     // C++11 [except.spec]p15:
8612     //   A deallocation function with no exception-specification is treated
8613     //   as if it were specified with noexcept(true).
8614     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8615     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8616          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8617         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8618       NewFD->setType(Context.getFunctionType(
8619           FPT->getReturnType(), FPT->getParamTypes(),
8620           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8621   }
8622 
8623   // Filter out previous declarations that don't match the scope.
8624   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8625                        D.getCXXScopeSpec().isNotEmpty() ||
8626                        isMemberSpecialization ||
8627                        isFunctionTemplateSpecialization);
8628 
8629   // Handle GNU asm-label extension (encoded as an attribute).
8630   if (Expr *E = (Expr*) D.getAsmLabel()) {
8631     // The parser guarantees this is a string.
8632     StringLiteral *SE = cast<StringLiteral>(E);
8633     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8634                                                 SE->getString(), 0));
8635   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8636     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8637       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8638     if (I != ExtnameUndeclaredIdentifiers.end()) {
8639       if (isDeclExternC(NewFD)) {
8640         NewFD->addAttr(I->second);
8641         ExtnameUndeclaredIdentifiers.erase(I);
8642       } else
8643         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8644             << /*Variable*/0 << NewFD;
8645     }
8646   }
8647 
8648   // Copy the parameter declarations from the declarator D to the function
8649   // declaration NewFD, if they are available.  First scavenge them into Params.
8650   SmallVector<ParmVarDecl*, 16> Params;
8651   unsigned FTIIdx;
8652   if (D.isFunctionDeclarator(FTIIdx)) {
8653     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8654 
8655     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8656     // function that takes no arguments, not a function that takes a
8657     // single void argument.
8658     // We let through "const void" here because Sema::GetTypeForDeclarator
8659     // already checks for that case.
8660     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8661       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8662         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8663         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8664         Param->setDeclContext(NewFD);
8665         Params.push_back(Param);
8666 
8667         if (Param->isInvalidDecl())
8668           NewFD->setInvalidDecl();
8669       }
8670     }
8671 
8672     if (!getLangOpts().CPlusPlus) {
8673       // In C, find all the tag declarations from the prototype and move them
8674       // into the function DeclContext. Remove them from the surrounding tag
8675       // injection context of the function, which is typically but not always
8676       // the TU.
8677       DeclContext *PrototypeTagContext =
8678           getTagInjectionContext(NewFD->getLexicalDeclContext());
8679       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8680         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8681 
8682         // We don't want to reparent enumerators. Look at their parent enum
8683         // instead.
8684         if (!TD) {
8685           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8686             TD = cast<EnumDecl>(ECD->getDeclContext());
8687         }
8688         if (!TD)
8689           continue;
8690         DeclContext *TagDC = TD->getLexicalDeclContext();
8691         if (!TagDC->containsDecl(TD))
8692           continue;
8693         TagDC->removeDecl(TD);
8694         TD->setDeclContext(NewFD);
8695         NewFD->addDecl(TD);
8696 
8697         // Preserve the lexical DeclContext if it is not the surrounding tag
8698         // injection context of the FD. In this example, the semantic context of
8699         // E will be f and the lexical context will be S, while both the
8700         // semantic and lexical contexts of S will be f:
8701         //   void f(struct S { enum E { a } f; } s);
8702         if (TagDC != PrototypeTagContext)
8703           TD->setLexicalDeclContext(TagDC);
8704       }
8705     }
8706   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8707     // When we're declaring a function with a typedef, typeof, etc as in the
8708     // following example, we'll need to synthesize (unnamed)
8709     // parameters for use in the declaration.
8710     //
8711     // @code
8712     // typedef void fn(int);
8713     // fn f;
8714     // @endcode
8715 
8716     // Synthesize a parameter for each argument type.
8717     for (const auto &AI : FT->param_types()) {
8718       ParmVarDecl *Param =
8719           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8720       Param->setScopeInfo(0, Params.size());
8721       Params.push_back(Param);
8722     }
8723   } else {
8724     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8725            "Should not need args for typedef of non-prototype fn");
8726   }
8727 
8728   // Finally, we know we have the right number of parameters, install them.
8729   NewFD->setParams(Params);
8730 
8731   if (D.getDeclSpec().isNoreturnSpecified())
8732     NewFD->addAttr(
8733         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8734                                        Context, 0));
8735 
8736   // Functions returning a variably modified type violate C99 6.7.5.2p2
8737   // because all functions have linkage.
8738   if (!NewFD->isInvalidDecl() &&
8739       NewFD->getReturnType()->isVariablyModifiedType()) {
8740     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8741     NewFD->setInvalidDecl();
8742   }
8743 
8744   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8745   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8746       !NewFD->hasAttr<SectionAttr>()) {
8747     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8748                                                  PragmaClangTextSection.SectionName,
8749                                                  PragmaClangTextSection.PragmaLocation));
8750   }
8751 
8752   // Apply an implicit SectionAttr if #pragma code_seg is active.
8753   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8754       !NewFD->hasAttr<SectionAttr>()) {
8755     NewFD->addAttr(
8756         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8757                                     CodeSegStack.CurrentValue->getString(),
8758                                     CodeSegStack.CurrentPragmaLocation));
8759     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8760                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8761                          ASTContext::PSF_Read,
8762                      NewFD))
8763       NewFD->dropAttr<SectionAttr>();
8764   }
8765 
8766   // Handle attributes.
8767   ProcessDeclAttributes(S, NewFD, D);
8768 
8769   if (getLangOpts().OpenCL) {
8770     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8771     // type declaration will generate a compilation error.
8772     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8773     if (AddressSpace == LangAS::opencl_local ||
8774         AddressSpace == LangAS::opencl_global ||
8775         AddressSpace == LangAS::opencl_constant) {
8776       Diag(NewFD->getLocation(),
8777            diag::err_opencl_return_value_with_address_space);
8778       NewFD->setInvalidDecl();
8779     }
8780   }
8781 
8782   if (!getLangOpts().CPlusPlus) {
8783     // Perform semantic checking on the function declaration.
8784     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8785       CheckMain(NewFD, D.getDeclSpec());
8786 
8787     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8788       CheckMSVCRTEntryPoint(NewFD);
8789 
8790     if (!NewFD->isInvalidDecl())
8791       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8792                                                   isMemberSpecialization));
8793     else if (!Previous.empty())
8794       // Recover gracefully from an invalid redeclaration.
8795       D.setRedeclaration(true);
8796     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8797             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8798            "previous declaration set still overloaded");
8799 
8800     // Diagnose no-prototype function declarations with calling conventions that
8801     // don't support variadic calls. Only do this in C and do it after merging
8802     // possibly prototyped redeclarations.
8803     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8804     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8805       CallingConv CC = FT->getExtInfo().getCC();
8806       if (!supportsVariadicCall(CC)) {
8807         // Windows system headers sometimes accidentally use stdcall without
8808         // (void) parameters, so we relax this to a warning.
8809         int DiagID =
8810             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8811         Diag(NewFD->getLocation(), DiagID)
8812             << FunctionType::getNameForCallConv(CC);
8813       }
8814     }
8815   } else {
8816     // C++11 [replacement.functions]p3:
8817     //  The program's definitions shall not be specified as inline.
8818     //
8819     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8820     //
8821     // Suppress the diagnostic if the function is __attribute__((used)), since
8822     // that forces an external definition to be emitted.
8823     if (D.getDeclSpec().isInlineSpecified() &&
8824         NewFD->isReplaceableGlobalAllocationFunction() &&
8825         !NewFD->hasAttr<UsedAttr>())
8826       Diag(D.getDeclSpec().getInlineSpecLoc(),
8827            diag::ext_operator_new_delete_declared_inline)
8828         << NewFD->getDeclName();
8829 
8830     // If the declarator is a template-id, translate the parser's template
8831     // argument list into our AST format.
8832     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8833       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8834       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8835       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8836       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8837                                          TemplateId->NumArgs);
8838       translateTemplateArguments(TemplateArgsPtr,
8839                                  TemplateArgs);
8840 
8841       HasExplicitTemplateArgs = true;
8842 
8843       if (NewFD->isInvalidDecl()) {
8844         HasExplicitTemplateArgs = false;
8845       } else if (FunctionTemplate) {
8846         // Function template with explicit template arguments.
8847         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8848           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8849 
8850         HasExplicitTemplateArgs = false;
8851       } else {
8852         assert((isFunctionTemplateSpecialization ||
8853                 D.getDeclSpec().isFriendSpecified()) &&
8854                "should have a 'template<>' for this decl");
8855         // "friend void foo<>(int);" is an implicit specialization decl.
8856         isFunctionTemplateSpecialization = true;
8857       }
8858     } else if (isFriend && isFunctionTemplateSpecialization) {
8859       // This combination is only possible in a recovery case;  the user
8860       // wrote something like:
8861       //   template <> friend void foo(int);
8862       // which we're recovering from as if the user had written:
8863       //   friend void foo<>(int);
8864       // Go ahead and fake up a template id.
8865       HasExplicitTemplateArgs = true;
8866       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8867       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8868     }
8869 
8870     // We do not add HD attributes to specializations here because
8871     // they may have different constexpr-ness compared to their
8872     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8873     // may end up with different effective targets. Instead, a
8874     // specialization inherits its target attributes from its template
8875     // in the CheckFunctionTemplateSpecialization() call below.
8876     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8877       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8878 
8879     // If it's a friend (and only if it's a friend), it's possible
8880     // that either the specialized function type or the specialized
8881     // template is dependent, and therefore matching will fail.  In
8882     // this case, don't check the specialization yet.
8883     bool InstantiationDependent = false;
8884     if (isFunctionTemplateSpecialization && isFriend &&
8885         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8886          TemplateSpecializationType::anyDependentTemplateArguments(
8887             TemplateArgs,
8888             InstantiationDependent))) {
8889       assert(HasExplicitTemplateArgs &&
8890              "friend function specialization without template args");
8891       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8892                                                        Previous))
8893         NewFD->setInvalidDecl();
8894     } else if (isFunctionTemplateSpecialization) {
8895       if (CurContext->isDependentContext() && CurContext->isRecord()
8896           && !isFriend) {
8897         isDependentClassScopeExplicitSpecialization = true;
8898         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8899           diag::ext_function_specialization_in_class :
8900           diag::err_function_specialization_in_class)
8901           << NewFD->getDeclName();
8902       } else if (CheckFunctionTemplateSpecialization(NewFD,
8903                                   (HasExplicitTemplateArgs ? &TemplateArgs
8904                                                            : nullptr),
8905                                                      Previous))
8906         NewFD->setInvalidDecl();
8907 
8908       // C++ [dcl.stc]p1:
8909       //   A storage-class-specifier shall not be specified in an explicit
8910       //   specialization (14.7.3)
8911       FunctionTemplateSpecializationInfo *Info =
8912           NewFD->getTemplateSpecializationInfo();
8913       if (Info && SC != SC_None) {
8914         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8915           Diag(NewFD->getLocation(),
8916                diag::err_explicit_specialization_inconsistent_storage_class)
8917             << SC
8918             << FixItHint::CreateRemoval(
8919                                       D.getDeclSpec().getStorageClassSpecLoc());
8920 
8921         else
8922           Diag(NewFD->getLocation(),
8923                diag::ext_explicit_specialization_storage_class)
8924             << FixItHint::CreateRemoval(
8925                                       D.getDeclSpec().getStorageClassSpecLoc());
8926       }
8927     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8928       if (CheckMemberSpecialization(NewFD, Previous))
8929           NewFD->setInvalidDecl();
8930     }
8931 
8932     // Perform semantic checking on the function declaration.
8933     if (!isDependentClassScopeExplicitSpecialization) {
8934       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8935         CheckMain(NewFD, D.getDeclSpec());
8936 
8937       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8938         CheckMSVCRTEntryPoint(NewFD);
8939 
8940       if (!NewFD->isInvalidDecl())
8941         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8942                                                     isMemberSpecialization));
8943       else if (!Previous.empty())
8944         // Recover gracefully from an invalid redeclaration.
8945         D.setRedeclaration(true);
8946     }
8947 
8948     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8949             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8950            "previous declaration set still overloaded");
8951 
8952     NamedDecl *PrincipalDecl = (FunctionTemplate
8953                                 ? cast<NamedDecl>(FunctionTemplate)
8954                                 : NewFD);
8955 
8956     if (isFriend && NewFD->getPreviousDecl()) {
8957       AccessSpecifier Access = AS_public;
8958       if (!NewFD->isInvalidDecl())
8959         Access = NewFD->getPreviousDecl()->getAccess();
8960 
8961       NewFD->setAccess(Access);
8962       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8963     }
8964 
8965     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8966         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8967       PrincipalDecl->setNonMemberOperator();
8968 
8969     // If we have a function template, check the template parameter
8970     // list. This will check and merge default template arguments.
8971     if (FunctionTemplate) {
8972       FunctionTemplateDecl *PrevTemplate =
8973                                      FunctionTemplate->getPreviousDecl();
8974       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8975                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8976                                     : nullptr,
8977                             D.getDeclSpec().isFriendSpecified()
8978                               ? (D.isFunctionDefinition()
8979                                    ? TPC_FriendFunctionTemplateDefinition
8980                                    : TPC_FriendFunctionTemplate)
8981                               : (D.getCXXScopeSpec().isSet() &&
8982                                  DC && DC->isRecord() &&
8983                                  DC->isDependentContext())
8984                                   ? TPC_ClassTemplateMember
8985                                   : TPC_FunctionTemplate);
8986     }
8987 
8988     if (NewFD->isInvalidDecl()) {
8989       // Ignore all the rest of this.
8990     } else if (!D.isRedeclaration()) {
8991       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8992                                        AddToScope };
8993       // Fake up an access specifier if it's supposed to be a class member.
8994       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8995         NewFD->setAccess(AS_public);
8996 
8997       // Qualified decls generally require a previous declaration.
8998       if (D.getCXXScopeSpec().isSet()) {
8999         // ...with the major exception of templated-scope or
9000         // dependent-scope friend declarations.
9001 
9002         // TODO: we currently also suppress this check in dependent
9003         // contexts because (1) the parameter depth will be off when
9004         // matching friend templates and (2) we might actually be
9005         // selecting a friend based on a dependent factor.  But there
9006         // are situations where these conditions don't apply and we
9007         // can actually do this check immediately.
9008         if (isFriend &&
9009             (TemplateParamLists.size() ||
9010              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9011              CurContext->isDependentContext())) {
9012           // ignore these
9013         } else {
9014           // The user tried to provide an out-of-line definition for a
9015           // function that is a member of a class or namespace, but there
9016           // was no such member function declared (C++ [class.mfct]p2,
9017           // C++ [namespace.memdef]p2). For example:
9018           //
9019           // class X {
9020           //   void f() const;
9021           // };
9022           //
9023           // void X::f() { } // ill-formed
9024           //
9025           // Complain about this problem, and attempt to suggest close
9026           // matches (e.g., those that differ only in cv-qualifiers and
9027           // whether the parameter types are references).
9028 
9029           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9030                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9031             AddToScope = ExtraArgs.AddToScope;
9032             return Result;
9033           }
9034         }
9035 
9036         // Unqualified local friend declarations are required to resolve
9037         // to something.
9038       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9039         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9040                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9041           AddToScope = ExtraArgs.AddToScope;
9042           return Result;
9043         }
9044       }
9045     } else if (!D.isFunctionDefinition() &&
9046                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9047                !isFriend && !isFunctionTemplateSpecialization &&
9048                !isMemberSpecialization) {
9049       // An out-of-line member function declaration must also be a
9050       // definition (C++ [class.mfct]p2).
9051       // Note that this is not the case for explicit specializations of
9052       // function templates or member functions of class templates, per
9053       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9054       // extension for compatibility with old SWIG code which likes to
9055       // generate them.
9056       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9057         << D.getCXXScopeSpec().getRange();
9058     }
9059   }
9060 
9061   ProcessPragmaWeak(S, NewFD);
9062   checkAttributesAfterMerging(*this, *NewFD);
9063 
9064   AddKnownFunctionAttributes(NewFD);
9065 
9066   if (NewFD->hasAttr<OverloadableAttr>() &&
9067       !NewFD->getType()->getAs<FunctionProtoType>()) {
9068     Diag(NewFD->getLocation(),
9069          diag::err_attribute_overloadable_no_prototype)
9070       << NewFD;
9071 
9072     // Turn this into a variadic function with no parameters.
9073     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9074     FunctionProtoType::ExtProtoInfo EPI(
9075         Context.getDefaultCallingConvention(true, false));
9076     EPI.Variadic = true;
9077     EPI.ExtInfo = FT->getExtInfo();
9078 
9079     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9080     NewFD->setType(R);
9081   }
9082 
9083   // If there's a #pragma GCC visibility in scope, and this isn't a class
9084   // member, set the visibility of this function.
9085   if (!DC->isRecord() && NewFD->isExternallyVisible())
9086     AddPushedVisibilityAttribute(NewFD);
9087 
9088   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9089   // marking the function.
9090   AddCFAuditedAttribute(NewFD);
9091 
9092   // If this is a function definition, check if we have to apply optnone due to
9093   // a pragma.
9094   if(D.isFunctionDefinition())
9095     AddRangeBasedOptnone(NewFD);
9096 
9097   // If this is the first declaration of an extern C variable, update
9098   // the map of such variables.
9099   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9100       isIncompleteDeclExternC(*this, NewFD))
9101     RegisterLocallyScopedExternCDecl(NewFD, S);
9102 
9103   // Set this FunctionDecl's range up to the right paren.
9104   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9105 
9106   if (D.isRedeclaration() && !Previous.empty()) {
9107     checkDLLAttributeRedeclaration(
9108         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9109         isMemberSpecialization || isFunctionTemplateSpecialization,
9110         D.isFunctionDefinition());
9111   }
9112 
9113   if (getLangOpts().CUDA) {
9114     IdentifierInfo *II = NewFD->getIdentifier();
9115     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9116         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9117       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9118         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9119 
9120       Context.setcudaConfigureCallDecl(NewFD);
9121     }
9122 
9123     // Variadic functions, other than a *declaration* of printf, are not allowed
9124     // in device-side CUDA code, unless someone passed
9125     // -fcuda-allow-variadic-functions.
9126     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9127         (NewFD->hasAttr<CUDADeviceAttr>() ||
9128          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9129         !(II && II->isStr("printf") && NewFD->isExternC() &&
9130           !D.isFunctionDefinition())) {
9131       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9132     }
9133   }
9134 
9135   MarkUnusedFileScopedDecl(NewFD);
9136 
9137   if (getLangOpts().CPlusPlus) {
9138     if (FunctionTemplate) {
9139       if (NewFD->isInvalidDecl())
9140         FunctionTemplate->setInvalidDecl();
9141       return FunctionTemplate;
9142     }
9143 
9144     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9145       CompleteMemberSpecialization(NewFD, Previous);
9146   }
9147 
9148   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9149     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9150     if ((getLangOpts().OpenCLVersion >= 120)
9151         && (SC == SC_Static)) {
9152       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9153       D.setInvalidType();
9154     }
9155 
9156     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9157     if (!NewFD->getReturnType()->isVoidType()) {
9158       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9159       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9160           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9161                                 : FixItHint());
9162       D.setInvalidType();
9163     }
9164 
9165     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9166     for (auto Param : NewFD->parameters())
9167       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9168   }
9169   for (const ParmVarDecl *Param : NewFD->parameters()) {
9170     QualType PT = Param->getType();
9171 
9172     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9173     // types.
9174     if (getLangOpts().OpenCLVersion >= 200) {
9175       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9176         QualType ElemTy = PipeTy->getElementType();
9177           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9178             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9179             D.setInvalidType();
9180           }
9181       }
9182     }
9183   }
9184 
9185   // Here we have an function template explicit specialization at class scope.
9186   // The actually specialization will be postponed to template instatiation
9187   // time via the ClassScopeFunctionSpecializationDecl node.
9188   if (isDependentClassScopeExplicitSpecialization) {
9189     ClassScopeFunctionSpecializationDecl *NewSpec =
9190                          ClassScopeFunctionSpecializationDecl::Create(
9191                                 Context, CurContext, SourceLocation(),
9192                                 cast<CXXMethodDecl>(NewFD),
9193                                 HasExplicitTemplateArgs, TemplateArgs);
9194     CurContext->addDecl(NewSpec);
9195     AddToScope = false;
9196   }
9197 
9198   return NewFD;
9199 }
9200 
9201 /// \brief Checks if the new declaration declared in dependent context must be
9202 /// put in the same redeclaration chain as the specified declaration.
9203 ///
9204 /// \param D Declaration that is checked.
9205 /// \param PrevDecl Previous declaration found with proper lookup method for the
9206 ///                 same declaration name.
9207 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9208 ///          belongs to.
9209 ///
9210 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9211   // Any declarations should be put into redeclaration chains except for
9212   // friend declaration in a dependent context that names a function in
9213   // namespace scope.
9214   //
9215   // This allows to compile code like:
9216   //
9217   //       void func();
9218   //       template<typename T> class C1 { friend void func() { } };
9219   //       template<typename T> class C2 { friend void func() { } };
9220   //
9221   // This code snippet is a valid code unless both templates are instantiated.
9222   return !(D->getLexicalDeclContext()->isDependentContext() &&
9223            D->getDeclContext()->isFileContext() &&
9224            D->getFriendObjectKind() != Decl::FOK_None);
9225 }
9226 
9227 /// \brief Perform semantic checking of a new function declaration.
9228 ///
9229 /// Performs semantic analysis of the new function declaration
9230 /// NewFD. This routine performs all semantic checking that does not
9231 /// require the actual declarator involved in the declaration, and is
9232 /// used both for the declaration of functions as they are parsed
9233 /// (called via ActOnDeclarator) and for the declaration of functions
9234 /// that have been instantiated via C++ template instantiation (called
9235 /// via InstantiateDecl).
9236 ///
9237 /// \param IsMemberSpecialization whether this new function declaration is
9238 /// a member specialization (that replaces any definition provided by the
9239 /// previous declaration).
9240 ///
9241 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9242 ///
9243 /// \returns true if the function declaration is a redeclaration.
9244 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9245                                     LookupResult &Previous,
9246                                     bool IsMemberSpecialization) {
9247   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9248          "Variably modified return types are not handled here");
9249 
9250   // Determine whether the type of this function should be merged with
9251   // a previous visible declaration. This never happens for functions in C++,
9252   // and always happens in C if the previous declaration was visible.
9253   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9254                                !Previous.isShadowed();
9255 
9256   bool Redeclaration = false;
9257   NamedDecl *OldDecl = nullptr;
9258   bool MayNeedOverloadableChecks = false;
9259 
9260   // Merge or overload the declaration with an existing declaration of
9261   // the same name, if appropriate.
9262   if (!Previous.empty()) {
9263     // Determine whether NewFD is an overload of PrevDecl or
9264     // a declaration that requires merging. If it's an overload,
9265     // there's no more work to do here; we'll just add the new
9266     // function to the scope.
9267     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9268       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9269       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9270         Redeclaration = true;
9271         OldDecl = Candidate;
9272       }
9273     } else {
9274       MayNeedOverloadableChecks = true;
9275       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9276                             /*NewIsUsingDecl*/ false)) {
9277       case Ovl_Match:
9278         Redeclaration = true;
9279         break;
9280 
9281       case Ovl_NonFunction:
9282         Redeclaration = true;
9283         break;
9284 
9285       case Ovl_Overload:
9286         Redeclaration = false;
9287         break;
9288       }
9289     }
9290   }
9291 
9292   // Check for a previous extern "C" declaration with this name.
9293   if (!Redeclaration &&
9294       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9295     if (!Previous.empty()) {
9296       // This is an extern "C" declaration with the same name as a previous
9297       // declaration, and thus redeclares that entity...
9298       Redeclaration = true;
9299       OldDecl = Previous.getFoundDecl();
9300       MergeTypeWithPrevious = false;
9301 
9302       // ... except in the presence of __attribute__((overloadable)).
9303       if (OldDecl->hasAttr<OverloadableAttr>() ||
9304           NewFD->hasAttr<OverloadableAttr>()) {
9305         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9306           MayNeedOverloadableChecks = true;
9307           Redeclaration = false;
9308           OldDecl = nullptr;
9309         }
9310       }
9311     }
9312   }
9313 
9314   // C++11 [dcl.constexpr]p8:
9315   //   A constexpr specifier for a non-static member function that is not
9316   //   a constructor declares that member function to be const.
9317   //
9318   // This needs to be delayed until we know whether this is an out-of-line
9319   // definition of a static member function.
9320   //
9321   // This rule is not present in C++1y, so we produce a backwards
9322   // compatibility warning whenever it happens in C++11.
9323   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9324   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9325       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9326       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9327     CXXMethodDecl *OldMD = nullptr;
9328     if (OldDecl)
9329       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9330     if (!OldMD || !OldMD->isStatic()) {
9331       const FunctionProtoType *FPT =
9332         MD->getType()->castAs<FunctionProtoType>();
9333       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9334       EPI.TypeQuals |= Qualifiers::Const;
9335       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9336                                           FPT->getParamTypes(), EPI));
9337 
9338       // Warn that we did this, if we're not performing template instantiation.
9339       // In that case, we'll have warned already when the template was defined.
9340       if (!inTemplateInstantiation()) {
9341         SourceLocation AddConstLoc;
9342         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9343                 .IgnoreParens().getAs<FunctionTypeLoc>())
9344           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9345 
9346         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9347           << FixItHint::CreateInsertion(AddConstLoc, " const");
9348       }
9349     }
9350   }
9351 
9352   if (Redeclaration) {
9353     // NewFD and OldDecl represent declarations that need to be
9354     // merged.
9355     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9356       NewFD->setInvalidDecl();
9357       return Redeclaration;
9358     }
9359 
9360     Previous.clear();
9361     Previous.addDecl(OldDecl);
9362 
9363     if (FunctionTemplateDecl *OldTemplateDecl
9364                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9365       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9366       FunctionTemplateDecl *NewTemplateDecl
9367         = NewFD->getDescribedFunctionTemplate();
9368       assert(NewTemplateDecl && "Template/non-template mismatch");
9369       if (CXXMethodDecl *Method
9370             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9371         Method->setAccess(OldTemplateDecl->getAccess());
9372         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9373       }
9374 
9375       // If this is an explicit specialization of a member that is a function
9376       // template, mark it as a member specialization.
9377       if (IsMemberSpecialization &&
9378           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9379         NewTemplateDecl->setMemberSpecialization();
9380         assert(OldTemplateDecl->isMemberSpecialization());
9381         // Explicit specializations of a member template do not inherit deleted
9382         // status from the parent member template that they are specializing.
9383         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9384           FunctionDecl *const OldTemplatedDecl =
9385               OldTemplateDecl->getTemplatedDecl();
9386           // FIXME: This assert will not hold in the presence of modules.
9387           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9388           // FIXME: We need an update record for this AST mutation.
9389           OldTemplatedDecl->setDeletedAsWritten(false);
9390         }
9391       }
9392 
9393     } else {
9394       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9395         // This needs to happen first so that 'inline' propagates.
9396         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9397         if (isa<CXXMethodDecl>(NewFD))
9398           NewFD->setAccess(OldDecl->getAccess());
9399       }
9400     }
9401   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9402              !NewFD->getAttr<OverloadableAttr>()) {
9403     assert((Previous.empty() ||
9404             llvm::any_of(Previous,
9405                          [](const NamedDecl *ND) {
9406                            return ND->hasAttr<OverloadableAttr>();
9407                          })) &&
9408            "Non-redecls shouldn't happen without overloadable present");
9409 
9410     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9411       const auto *FD = dyn_cast<FunctionDecl>(ND);
9412       return FD && !FD->hasAttr<OverloadableAttr>();
9413     });
9414 
9415     if (OtherUnmarkedIter != Previous.end()) {
9416       Diag(NewFD->getLocation(),
9417            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9418       Diag((*OtherUnmarkedIter)->getLocation(),
9419            diag::note_attribute_overloadable_prev_overload)
9420           << false;
9421 
9422       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9423     }
9424   }
9425 
9426   // Semantic checking for this function declaration (in isolation).
9427 
9428   if (getLangOpts().CPlusPlus) {
9429     // C++-specific checks.
9430     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9431       CheckConstructor(Constructor);
9432     } else if (CXXDestructorDecl *Destructor =
9433                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9434       CXXRecordDecl *Record = Destructor->getParent();
9435       QualType ClassType = Context.getTypeDeclType(Record);
9436 
9437       // FIXME: Shouldn't we be able to perform this check even when the class
9438       // type is dependent? Both gcc and edg can handle that.
9439       if (!ClassType->isDependentType()) {
9440         DeclarationName Name
9441           = Context.DeclarationNames.getCXXDestructorName(
9442                                         Context.getCanonicalType(ClassType));
9443         if (NewFD->getDeclName() != Name) {
9444           Diag(NewFD->getLocation(), diag::err_destructor_name);
9445           NewFD->setInvalidDecl();
9446           return Redeclaration;
9447         }
9448       }
9449     } else if (CXXConversionDecl *Conversion
9450                = dyn_cast<CXXConversionDecl>(NewFD)) {
9451       ActOnConversionDeclarator(Conversion);
9452     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9453       if (auto *TD = Guide->getDescribedFunctionTemplate())
9454         CheckDeductionGuideTemplate(TD);
9455 
9456       // A deduction guide is not on the list of entities that can be
9457       // explicitly specialized.
9458       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9459         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9460             << /*explicit specialization*/ 1;
9461     }
9462 
9463     // Find any virtual functions that this function overrides.
9464     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9465       if (!Method->isFunctionTemplateSpecialization() &&
9466           !Method->getDescribedFunctionTemplate() &&
9467           Method->isCanonicalDecl()) {
9468         if (AddOverriddenMethods(Method->getParent(), Method)) {
9469           // If the function was marked as "static", we have a problem.
9470           if (NewFD->getStorageClass() == SC_Static) {
9471             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9472           }
9473         }
9474       }
9475 
9476       if (Method->isStatic())
9477         checkThisInStaticMemberFunctionType(Method);
9478     }
9479 
9480     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9481     if (NewFD->isOverloadedOperator() &&
9482         CheckOverloadedOperatorDeclaration(NewFD)) {
9483       NewFD->setInvalidDecl();
9484       return Redeclaration;
9485     }
9486 
9487     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9488     if (NewFD->getLiteralIdentifier() &&
9489         CheckLiteralOperatorDeclaration(NewFD)) {
9490       NewFD->setInvalidDecl();
9491       return Redeclaration;
9492     }
9493 
9494     // In C++, check default arguments now that we have merged decls. Unless
9495     // the lexical context is the class, because in this case this is done
9496     // during delayed parsing anyway.
9497     if (!CurContext->isRecord())
9498       CheckCXXDefaultArguments(NewFD);
9499 
9500     // If this function declares a builtin function, check the type of this
9501     // declaration against the expected type for the builtin.
9502     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9503       ASTContext::GetBuiltinTypeError Error;
9504       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9505       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9506       // If the type of the builtin differs only in its exception
9507       // specification, that's OK.
9508       // FIXME: If the types do differ in this way, it would be better to
9509       // retain the 'noexcept' form of the type.
9510       if (!T.isNull() &&
9511           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9512                                                             NewFD->getType()))
9513         // The type of this function differs from the type of the builtin,
9514         // so forget about the builtin entirely.
9515         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9516     }
9517 
9518     // If this function is declared as being extern "C", then check to see if
9519     // the function returns a UDT (class, struct, or union type) that is not C
9520     // compatible, and if it does, warn the user.
9521     // But, issue any diagnostic on the first declaration only.
9522     if (Previous.empty() && NewFD->isExternC()) {
9523       QualType R = NewFD->getReturnType();
9524       if (R->isIncompleteType() && !R->isVoidType())
9525         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9526             << NewFD << R;
9527       else if (!R.isPODType(Context) && !R->isVoidType() &&
9528                !R->isObjCObjectPointerType())
9529         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9530     }
9531 
9532     // C++1z [dcl.fct]p6:
9533     //   [...] whether the function has a non-throwing exception-specification
9534     //   [is] part of the function type
9535     //
9536     // This results in an ABI break between C++14 and C++17 for functions whose
9537     // declared type includes an exception-specification in a parameter or
9538     // return type. (Exception specifications on the function itself are OK in
9539     // most cases, and exception specifications are not permitted in most other
9540     // contexts where they could make it into a mangling.)
9541     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9542       auto HasNoexcept = [&](QualType T) -> bool {
9543         // Strip off declarator chunks that could be between us and a function
9544         // type. We don't need to look far, exception specifications are very
9545         // restricted prior to C++17.
9546         if (auto *RT = T->getAs<ReferenceType>())
9547           T = RT->getPointeeType();
9548         else if (T->isAnyPointerType())
9549           T = T->getPointeeType();
9550         else if (auto *MPT = T->getAs<MemberPointerType>())
9551           T = MPT->getPointeeType();
9552         if (auto *FPT = T->getAs<FunctionProtoType>())
9553           if (FPT->isNothrow(Context))
9554             return true;
9555         return false;
9556       };
9557 
9558       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9559       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9560       for (QualType T : FPT->param_types())
9561         AnyNoexcept |= HasNoexcept(T);
9562       if (AnyNoexcept)
9563         Diag(NewFD->getLocation(),
9564              diag::warn_cxx17_compat_exception_spec_in_signature)
9565             << NewFD;
9566     }
9567 
9568     if (!Redeclaration && LangOpts.CUDA)
9569       checkCUDATargetOverload(NewFD, Previous);
9570   }
9571   return Redeclaration;
9572 }
9573 
9574 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9575   // C++11 [basic.start.main]p3:
9576   //   A program that [...] declares main to be inline, static or
9577   //   constexpr is ill-formed.
9578   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9579   //   appear in a declaration of main.
9580   // static main is not an error under C99, but we should warn about it.
9581   // We accept _Noreturn main as an extension.
9582   if (FD->getStorageClass() == SC_Static)
9583     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9584          ? diag::err_static_main : diag::warn_static_main)
9585       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9586   if (FD->isInlineSpecified())
9587     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9588       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9589   if (DS.isNoreturnSpecified()) {
9590     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9591     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9592     Diag(NoreturnLoc, diag::ext_noreturn_main);
9593     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9594       << FixItHint::CreateRemoval(NoreturnRange);
9595   }
9596   if (FD->isConstexpr()) {
9597     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9598       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9599     FD->setConstexpr(false);
9600   }
9601 
9602   if (getLangOpts().OpenCL) {
9603     Diag(FD->getLocation(), diag::err_opencl_no_main)
9604         << FD->hasAttr<OpenCLKernelAttr>();
9605     FD->setInvalidDecl();
9606     return;
9607   }
9608 
9609   QualType T = FD->getType();
9610   assert(T->isFunctionType() && "function decl is not of function type");
9611   const FunctionType* FT = T->castAs<FunctionType>();
9612 
9613   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9614     // In C with GNU extensions we allow main() to have non-integer return
9615     // type, but we should warn about the extension, and we disable the
9616     // implicit-return-zero rule.
9617 
9618     // GCC in C mode accepts qualified 'int'.
9619     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9620       FD->setHasImplicitReturnZero(true);
9621     else {
9622       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9623       SourceRange RTRange = FD->getReturnTypeSourceRange();
9624       if (RTRange.isValid())
9625         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9626             << FixItHint::CreateReplacement(RTRange, "int");
9627     }
9628   } else {
9629     // In C and C++, main magically returns 0 if you fall off the end;
9630     // set the flag which tells us that.
9631     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9632 
9633     // All the standards say that main() should return 'int'.
9634     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9635       FD->setHasImplicitReturnZero(true);
9636     else {
9637       // Otherwise, this is just a flat-out error.
9638       SourceRange RTRange = FD->getReturnTypeSourceRange();
9639       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9640           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9641                                 : FixItHint());
9642       FD->setInvalidDecl(true);
9643     }
9644   }
9645 
9646   // Treat protoless main() as nullary.
9647   if (isa<FunctionNoProtoType>(FT)) return;
9648 
9649   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9650   unsigned nparams = FTP->getNumParams();
9651   assert(FD->getNumParams() == nparams);
9652 
9653   bool HasExtraParameters = (nparams > 3);
9654 
9655   if (FTP->isVariadic()) {
9656     Diag(FD->getLocation(), diag::ext_variadic_main);
9657     // FIXME: if we had information about the location of the ellipsis, we
9658     // could add a FixIt hint to remove it as a parameter.
9659   }
9660 
9661   // Darwin passes an undocumented fourth argument of type char**.  If
9662   // other platforms start sprouting these, the logic below will start
9663   // getting shifty.
9664   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9665     HasExtraParameters = false;
9666 
9667   if (HasExtraParameters) {
9668     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9669     FD->setInvalidDecl(true);
9670     nparams = 3;
9671   }
9672 
9673   // FIXME: a lot of the following diagnostics would be improved
9674   // if we had some location information about types.
9675 
9676   QualType CharPP =
9677     Context.getPointerType(Context.getPointerType(Context.CharTy));
9678   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9679 
9680   for (unsigned i = 0; i < nparams; ++i) {
9681     QualType AT = FTP->getParamType(i);
9682 
9683     bool mismatch = true;
9684 
9685     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9686       mismatch = false;
9687     else if (Expected[i] == CharPP) {
9688       // As an extension, the following forms are okay:
9689       //   char const **
9690       //   char const * const *
9691       //   char * const *
9692 
9693       QualifierCollector qs;
9694       const PointerType* PT;
9695       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9696           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9697           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9698                               Context.CharTy)) {
9699         qs.removeConst();
9700         mismatch = !qs.empty();
9701       }
9702     }
9703 
9704     if (mismatch) {
9705       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9706       // TODO: suggest replacing given type with expected type
9707       FD->setInvalidDecl(true);
9708     }
9709   }
9710 
9711   if (nparams == 1 && !FD->isInvalidDecl()) {
9712     Diag(FD->getLocation(), diag::warn_main_one_arg);
9713   }
9714 
9715   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9716     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9717     FD->setInvalidDecl();
9718   }
9719 }
9720 
9721 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9722   QualType T = FD->getType();
9723   assert(T->isFunctionType() && "function decl is not of function type");
9724   const FunctionType *FT = T->castAs<FunctionType>();
9725 
9726   // Set an implicit return of 'zero' if the function can return some integral,
9727   // enumeration, pointer or nullptr type.
9728   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9729       FT->getReturnType()->isAnyPointerType() ||
9730       FT->getReturnType()->isNullPtrType())
9731     // DllMain is exempt because a return value of zero means it failed.
9732     if (FD->getName() != "DllMain")
9733       FD->setHasImplicitReturnZero(true);
9734 
9735   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9736     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9737     FD->setInvalidDecl();
9738   }
9739 }
9740 
9741 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9742   // FIXME: Need strict checking.  In C89, we need to check for
9743   // any assignment, increment, decrement, function-calls, or
9744   // commas outside of a sizeof.  In C99, it's the same list,
9745   // except that the aforementioned are allowed in unevaluated
9746   // expressions.  Everything else falls under the
9747   // "may accept other forms of constant expressions" exception.
9748   // (We never end up here for C++, so the constant expression
9749   // rules there don't matter.)
9750   const Expr *Culprit;
9751   if (Init->isConstantInitializer(Context, false, &Culprit))
9752     return false;
9753   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9754     << Culprit->getSourceRange();
9755   return true;
9756 }
9757 
9758 namespace {
9759   // Visits an initialization expression to see if OrigDecl is evaluated in
9760   // its own initialization and throws a warning if it does.
9761   class SelfReferenceChecker
9762       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9763     Sema &S;
9764     Decl *OrigDecl;
9765     bool isRecordType;
9766     bool isPODType;
9767     bool isReferenceType;
9768 
9769     bool isInitList;
9770     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9771 
9772   public:
9773     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9774 
9775     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9776                                                     S(S), OrigDecl(OrigDecl) {
9777       isPODType = false;
9778       isRecordType = false;
9779       isReferenceType = false;
9780       isInitList = false;
9781       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9782         isPODType = VD->getType().isPODType(S.Context);
9783         isRecordType = VD->getType()->isRecordType();
9784         isReferenceType = VD->getType()->isReferenceType();
9785       }
9786     }
9787 
9788     // For most expressions, just call the visitor.  For initializer lists,
9789     // track the index of the field being initialized since fields are
9790     // initialized in order allowing use of previously initialized fields.
9791     void CheckExpr(Expr *E) {
9792       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9793       if (!InitList) {
9794         Visit(E);
9795         return;
9796       }
9797 
9798       // Track and increment the index here.
9799       isInitList = true;
9800       InitFieldIndex.push_back(0);
9801       for (auto Child : InitList->children()) {
9802         CheckExpr(cast<Expr>(Child));
9803         ++InitFieldIndex.back();
9804       }
9805       InitFieldIndex.pop_back();
9806     }
9807 
9808     // Returns true if MemberExpr is checked and no further checking is needed.
9809     // Returns false if additional checking is required.
9810     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9811       llvm::SmallVector<FieldDecl*, 4> Fields;
9812       Expr *Base = E;
9813       bool ReferenceField = false;
9814 
9815       // Get the field memebers used.
9816       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9817         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9818         if (!FD)
9819           return false;
9820         Fields.push_back(FD);
9821         if (FD->getType()->isReferenceType())
9822           ReferenceField = true;
9823         Base = ME->getBase()->IgnoreParenImpCasts();
9824       }
9825 
9826       // Keep checking only if the base Decl is the same.
9827       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9828       if (!DRE || DRE->getDecl() != OrigDecl)
9829         return false;
9830 
9831       // A reference field can be bound to an unininitialized field.
9832       if (CheckReference && !ReferenceField)
9833         return true;
9834 
9835       // Convert FieldDecls to their index number.
9836       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9837       for (const FieldDecl *I : llvm::reverse(Fields))
9838         UsedFieldIndex.push_back(I->getFieldIndex());
9839 
9840       // See if a warning is needed by checking the first difference in index
9841       // numbers.  If field being used has index less than the field being
9842       // initialized, then the use is safe.
9843       for (auto UsedIter = UsedFieldIndex.begin(),
9844                 UsedEnd = UsedFieldIndex.end(),
9845                 OrigIter = InitFieldIndex.begin(),
9846                 OrigEnd = InitFieldIndex.end();
9847            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9848         if (*UsedIter < *OrigIter)
9849           return true;
9850         if (*UsedIter > *OrigIter)
9851           break;
9852       }
9853 
9854       // TODO: Add a different warning which will print the field names.
9855       HandleDeclRefExpr(DRE);
9856       return true;
9857     }
9858 
9859     // For most expressions, the cast is directly above the DeclRefExpr.
9860     // For conditional operators, the cast can be outside the conditional
9861     // operator if both expressions are DeclRefExpr's.
9862     void HandleValue(Expr *E) {
9863       E = E->IgnoreParens();
9864       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9865         HandleDeclRefExpr(DRE);
9866         return;
9867       }
9868 
9869       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9870         Visit(CO->getCond());
9871         HandleValue(CO->getTrueExpr());
9872         HandleValue(CO->getFalseExpr());
9873         return;
9874       }
9875 
9876       if (BinaryConditionalOperator *BCO =
9877               dyn_cast<BinaryConditionalOperator>(E)) {
9878         Visit(BCO->getCond());
9879         HandleValue(BCO->getFalseExpr());
9880         return;
9881       }
9882 
9883       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9884         HandleValue(OVE->getSourceExpr());
9885         return;
9886       }
9887 
9888       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9889         if (BO->getOpcode() == BO_Comma) {
9890           Visit(BO->getLHS());
9891           HandleValue(BO->getRHS());
9892           return;
9893         }
9894       }
9895 
9896       if (isa<MemberExpr>(E)) {
9897         if (isInitList) {
9898           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9899                                       false /*CheckReference*/))
9900             return;
9901         }
9902 
9903         Expr *Base = E->IgnoreParenImpCasts();
9904         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9905           // Check for static member variables and don't warn on them.
9906           if (!isa<FieldDecl>(ME->getMemberDecl()))
9907             return;
9908           Base = ME->getBase()->IgnoreParenImpCasts();
9909         }
9910         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9911           HandleDeclRefExpr(DRE);
9912         return;
9913       }
9914 
9915       Visit(E);
9916     }
9917 
9918     // Reference types not handled in HandleValue are handled here since all
9919     // uses of references are bad, not just r-value uses.
9920     void VisitDeclRefExpr(DeclRefExpr *E) {
9921       if (isReferenceType)
9922         HandleDeclRefExpr(E);
9923     }
9924 
9925     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9926       if (E->getCastKind() == CK_LValueToRValue) {
9927         HandleValue(E->getSubExpr());
9928         return;
9929       }
9930 
9931       Inherited::VisitImplicitCastExpr(E);
9932     }
9933 
9934     void VisitMemberExpr(MemberExpr *E) {
9935       if (isInitList) {
9936         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9937           return;
9938       }
9939 
9940       // Don't warn on arrays since they can be treated as pointers.
9941       if (E->getType()->canDecayToPointerType()) return;
9942 
9943       // Warn when a non-static method call is followed by non-static member
9944       // field accesses, which is followed by a DeclRefExpr.
9945       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9946       bool Warn = (MD && !MD->isStatic());
9947       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9948       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9949         if (!isa<FieldDecl>(ME->getMemberDecl()))
9950           Warn = false;
9951         Base = ME->getBase()->IgnoreParenImpCasts();
9952       }
9953 
9954       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9955         if (Warn)
9956           HandleDeclRefExpr(DRE);
9957         return;
9958       }
9959 
9960       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9961       // Visit that expression.
9962       Visit(Base);
9963     }
9964 
9965     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9966       Expr *Callee = E->getCallee();
9967 
9968       if (isa<UnresolvedLookupExpr>(Callee))
9969         return Inherited::VisitCXXOperatorCallExpr(E);
9970 
9971       Visit(Callee);
9972       for (auto Arg: E->arguments())
9973         HandleValue(Arg->IgnoreParenImpCasts());
9974     }
9975 
9976     void VisitUnaryOperator(UnaryOperator *E) {
9977       // For POD record types, addresses of its own members are well-defined.
9978       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9979           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9980         if (!isPODType)
9981           HandleValue(E->getSubExpr());
9982         return;
9983       }
9984 
9985       if (E->isIncrementDecrementOp()) {
9986         HandleValue(E->getSubExpr());
9987         return;
9988       }
9989 
9990       Inherited::VisitUnaryOperator(E);
9991     }
9992 
9993     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9994 
9995     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9996       if (E->getConstructor()->isCopyConstructor()) {
9997         Expr *ArgExpr = E->getArg(0);
9998         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9999           if (ILE->getNumInits() == 1)
10000             ArgExpr = ILE->getInit(0);
10001         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10002           if (ICE->getCastKind() == CK_NoOp)
10003             ArgExpr = ICE->getSubExpr();
10004         HandleValue(ArgExpr);
10005         return;
10006       }
10007       Inherited::VisitCXXConstructExpr(E);
10008     }
10009 
10010     void VisitCallExpr(CallExpr *E) {
10011       // Treat std::move as a use.
10012       if (E->isCallToStdMove()) {
10013         HandleValue(E->getArg(0));
10014         return;
10015       }
10016 
10017       Inherited::VisitCallExpr(E);
10018     }
10019 
10020     void VisitBinaryOperator(BinaryOperator *E) {
10021       if (E->isCompoundAssignmentOp()) {
10022         HandleValue(E->getLHS());
10023         Visit(E->getRHS());
10024         return;
10025       }
10026 
10027       Inherited::VisitBinaryOperator(E);
10028     }
10029 
10030     // A custom visitor for BinaryConditionalOperator is needed because the
10031     // regular visitor would check the condition and true expression separately
10032     // but both point to the same place giving duplicate diagnostics.
10033     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10034       Visit(E->getCond());
10035       Visit(E->getFalseExpr());
10036     }
10037 
10038     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10039       Decl* ReferenceDecl = DRE->getDecl();
10040       if (OrigDecl != ReferenceDecl) return;
10041       unsigned diag;
10042       if (isReferenceType) {
10043         diag = diag::warn_uninit_self_reference_in_reference_init;
10044       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10045         diag = diag::warn_static_self_reference_in_init;
10046       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10047                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10048                  DRE->getDecl()->getType()->isRecordType()) {
10049         diag = diag::warn_uninit_self_reference_in_init;
10050       } else {
10051         // Local variables will be handled by the CFG analysis.
10052         return;
10053       }
10054 
10055       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10056                             S.PDiag(diag)
10057                               << DRE->getNameInfo().getName()
10058                               << OrigDecl->getLocation()
10059                               << DRE->getSourceRange());
10060     }
10061   };
10062 
10063   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10064   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10065                                  bool DirectInit) {
10066     // Parameters arguments are occassionially constructed with itself,
10067     // for instance, in recursive functions.  Skip them.
10068     if (isa<ParmVarDecl>(OrigDecl))
10069       return;
10070 
10071     E = E->IgnoreParens();
10072 
10073     // Skip checking T a = a where T is not a record or reference type.
10074     // Doing so is a way to silence uninitialized warnings.
10075     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10076       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10077         if (ICE->getCastKind() == CK_LValueToRValue)
10078           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10079             if (DRE->getDecl() == OrigDecl)
10080               return;
10081 
10082     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10083   }
10084 } // end anonymous namespace
10085 
10086 namespace {
10087   // Simple wrapper to add the name of a variable or (if no variable is
10088   // available) a DeclarationName into a diagnostic.
10089   struct VarDeclOrName {
10090     VarDecl *VDecl;
10091     DeclarationName Name;
10092 
10093     friend const Sema::SemaDiagnosticBuilder &
10094     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10095       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10096     }
10097   };
10098 } // end anonymous namespace
10099 
10100 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10101                                             DeclarationName Name, QualType Type,
10102                                             TypeSourceInfo *TSI,
10103                                             SourceRange Range, bool DirectInit,
10104                                             Expr *Init) {
10105   bool IsInitCapture = !VDecl;
10106   assert((!VDecl || !VDecl->isInitCapture()) &&
10107          "init captures are expected to be deduced prior to initialization");
10108 
10109   VarDeclOrName VN{VDecl, Name};
10110 
10111   DeducedType *Deduced = Type->getContainedDeducedType();
10112   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10113 
10114   // C++11 [dcl.spec.auto]p3
10115   if (!Init) {
10116     assert(VDecl && "no init for init capture deduction?");
10117     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10118       << VDecl->getDeclName() << Type;
10119     return QualType();
10120   }
10121 
10122   ArrayRef<Expr*> DeduceInits = Init;
10123   if (DirectInit) {
10124     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10125       DeduceInits = PL->exprs();
10126   }
10127 
10128   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10129     assert(VDecl && "non-auto type for init capture deduction?");
10130     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10131     InitializationKind Kind = InitializationKind::CreateForInit(
10132         VDecl->getLocation(), DirectInit, Init);
10133     // FIXME: Initialization should not be taking a mutable list of inits.
10134     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10135     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10136                                                        InitsCopy);
10137   }
10138 
10139   if (DirectInit) {
10140     if (auto *IL = dyn_cast<InitListExpr>(Init))
10141       DeduceInits = IL->inits();
10142   }
10143 
10144   // Deduction only works if we have exactly one source expression.
10145   if (DeduceInits.empty()) {
10146     // It isn't possible to write this directly, but it is possible to
10147     // end up in this situation with "auto x(some_pack...);"
10148     Diag(Init->getLocStart(), IsInitCapture
10149                                   ? diag::err_init_capture_no_expression
10150                                   : diag::err_auto_var_init_no_expression)
10151         << VN << Type << Range;
10152     return QualType();
10153   }
10154 
10155   if (DeduceInits.size() > 1) {
10156     Diag(DeduceInits[1]->getLocStart(),
10157          IsInitCapture ? diag::err_init_capture_multiple_expressions
10158                        : diag::err_auto_var_init_multiple_expressions)
10159         << VN << Type << Range;
10160     return QualType();
10161   }
10162 
10163   Expr *DeduceInit = DeduceInits[0];
10164   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10165     Diag(Init->getLocStart(), IsInitCapture
10166                                   ? diag::err_init_capture_paren_braces
10167                                   : diag::err_auto_var_init_paren_braces)
10168         << isa<InitListExpr>(Init) << VN << Type << Range;
10169     return QualType();
10170   }
10171 
10172   // Expressions default to 'id' when we're in a debugger.
10173   bool DefaultedAnyToId = false;
10174   if (getLangOpts().DebuggerCastResultToId &&
10175       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10176     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10177     if (Result.isInvalid()) {
10178       return QualType();
10179     }
10180     Init = Result.get();
10181     DefaultedAnyToId = true;
10182   }
10183 
10184   // C++ [dcl.decomp]p1:
10185   //   If the assignment-expression [...] has array type A and no ref-qualifier
10186   //   is present, e has type cv A
10187   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10188       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10189       DeduceInit->getType()->isConstantArrayType())
10190     return Context.getQualifiedType(DeduceInit->getType(),
10191                                     Type.getQualifiers());
10192 
10193   QualType DeducedType;
10194   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10195     if (!IsInitCapture)
10196       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10197     else if (isa<InitListExpr>(Init))
10198       Diag(Range.getBegin(),
10199            diag::err_init_capture_deduction_failure_from_init_list)
10200           << VN
10201           << (DeduceInit->getType().isNull() ? TSI->getType()
10202                                              : DeduceInit->getType())
10203           << DeduceInit->getSourceRange();
10204     else
10205       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10206           << VN << TSI->getType()
10207           << (DeduceInit->getType().isNull() ? TSI->getType()
10208                                              : DeduceInit->getType())
10209           << DeduceInit->getSourceRange();
10210   }
10211 
10212   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10213   // 'id' instead of a specific object type prevents most of our usual
10214   // checks.
10215   // We only want to warn outside of template instantiations, though:
10216   // inside a template, the 'id' could have come from a parameter.
10217   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10218       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10219     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10220     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10221   }
10222 
10223   return DeducedType;
10224 }
10225 
10226 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10227                                          Expr *Init) {
10228   QualType DeducedType = deduceVarTypeFromInitializer(
10229       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10230       VDecl->getSourceRange(), DirectInit, Init);
10231   if (DeducedType.isNull()) {
10232     VDecl->setInvalidDecl();
10233     return true;
10234   }
10235 
10236   VDecl->setType(DeducedType);
10237   assert(VDecl->isLinkageValid());
10238 
10239   // In ARC, infer lifetime.
10240   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10241     VDecl->setInvalidDecl();
10242 
10243   // If this is a redeclaration, check that the type we just deduced matches
10244   // the previously declared type.
10245   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10246     // We never need to merge the type, because we cannot form an incomplete
10247     // array of auto, nor deduce such a type.
10248     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10249   }
10250 
10251   // Check the deduced type is valid for a variable declaration.
10252   CheckVariableDeclarationType(VDecl);
10253   return VDecl->isInvalidDecl();
10254 }
10255 
10256 /// AddInitializerToDecl - Adds the initializer Init to the
10257 /// declaration dcl. If DirectInit is true, this is C++ direct
10258 /// initialization rather than copy initialization.
10259 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10260   // If there is no declaration, there was an error parsing it.  Just ignore
10261   // the initializer.
10262   if (!RealDecl || RealDecl->isInvalidDecl()) {
10263     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10264     return;
10265   }
10266 
10267   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10268     // Pure-specifiers are handled in ActOnPureSpecifier.
10269     Diag(Method->getLocation(), diag::err_member_function_initialization)
10270       << Method->getDeclName() << Init->getSourceRange();
10271     Method->setInvalidDecl();
10272     return;
10273   }
10274 
10275   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10276   if (!VDecl) {
10277     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10278     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10279     RealDecl->setInvalidDecl();
10280     return;
10281   }
10282 
10283   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10284   if (VDecl->getType()->isUndeducedType()) {
10285     // Attempt typo correction early so that the type of the init expression can
10286     // be deduced based on the chosen correction if the original init contains a
10287     // TypoExpr.
10288     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10289     if (!Res.isUsable()) {
10290       RealDecl->setInvalidDecl();
10291       return;
10292     }
10293     Init = Res.get();
10294 
10295     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10296       return;
10297   }
10298 
10299   // dllimport cannot be used on variable definitions.
10300   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10301     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10302     VDecl->setInvalidDecl();
10303     return;
10304   }
10305 
10306   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10307     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10308     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10309     VDecl->setInvalidDecl();
10310     return;
10311   }
10312 
10313   if (!VDecl->getType()->isDependentType()) {
10314     // A definition must end up with a complete type, which means it must be
10315     // complete with the restriction that an array type might be completed by
10316     // the initializer; note that later code assumes this restriction.
10317     QualType BaseDeclType = VDecl->getType();
10318     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10319       BaseDeclType = Array->getElementType();
10320     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10321                             diag::err_typecheck_decl_incomplete_type)) {
10322       RealDecl->setInvalidDecl();
10323       return;
10324     }
10325 
10326     // The variable can not have an abstract class type.
10327     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10328                                diag::err_abstract_type_in_decl,
10329                                AbstractVariableType))
10330       VDecl->setInvalidDecl();
10331   }
10332 
10333   // If adding the initializer will turn this declaration into a definition,
10334   // and we already have a definition for this variable, diagnose or otherwise
10335   // handle the situation.
10336   VarDecl *Def;
10337   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10338       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10339       !VDecl->isThisDeclarationADemotedDefinition() &&
10340       checkVarDeclRedefinition(Def, VDecl))
10341     return;
10342 
10343   if (getLangOpts().CPlusPlus) {
10344     // C++ [class.static.data]p4
10345     //   If a static data member is of const integral or const
10346     //   enumeration type, its declaration in the class definition can
10347     //   specify a constant-initializer which shall be an integral
10348     //   constant expression (5.19). In that case, the member can appear
10349     //   in integral constant expressions. The member shall still be
10350     //   defined in a namespace scope if it is used in the program and the
10351     //   namespace scope definition shall not contain an initializer.
10352     //
10353     // We already performed a redefinition check above, but for static
10354     // data members we also need to check whether there was an in-class
10355     // declaration with an initializer.
10356     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10357       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10358           << VDecl->getDeclName();
10359       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10360            diag::note_previous_initializer)
10361           << 0;
10362       return;
10363     }
10364 
10365     if (VDecl->hasLocalStorage())
10366       getCurFunction()->setHasBranchProtectedScope();
10367 
10368     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10369       VDecl->setInvalidDecl();
10370       return;
10371     }
10372   }
10373 
10374   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10375   // a kernel function cannot be initialized."
10376   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10377     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10378     VDecl->setInvalidDecl();
10379     return;
10380   }
10381 
10382   // Get the decls type and save a reference for later, since
10383   // CheckInitializerTypes may change it.
10384   QualType DclT = VDecl->getType(), SavT = DclT;
10385 
10386   // Expressions default to 'id' when we're in a debugger
10387   // and we are assigning it to a variable of Objective-C pointer type.
10388   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10389       Init->getType() == Context.UnknownAnyTy) {
10390     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10391     if (Result.isInvalid()) {
10392       VDecl->setInvalidDecl();
10393       return;
10394     }
10395     Init = Result.get();
10396   }
10397 
10398   // Perform the initialization.
10399   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10400   if (!VDecl->isInvalidDecl()) {
10401     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10402     InitializationKind Kind = InitializationKind::CreateForInit(
10403         VDecl->getLocation(), DirectInit, Init);
10404 
10405     MultiExprArg Args = Init;
10406     if (CXXDirectInit)
10407       Args = MultiExprArg(CXXDirectInit->getExprs(),
10408                           CXXDirectInit->getNumExprs());
10409 
10410     // Try to correct any TypoExprs in the initialization arguments.
10411     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10412       ExprResult Res = CorrectDelayedTyposInExpr(
10413           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10414             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10415             return Init.Failed() ? ExprError() : E;
10416           });
10417       if (Res.isInvalid()) {
10418         VDecl->setInvalidDecl();
10419       } else if (Res.get() != Args[Idx]) {
10420         Args[Idx] = Res.get();
10421       }
10422     }
10423     if (VDecl->isInvalidDecl())
10424       return;
10425 
10426     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10427                                    /*TopLevelOfInitList=*/false,
10428                                    /*TreatUnavailableAsInvalid=*/false);
10429     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10430     if (Result.isInvalid()) {
10431       VDecl->setInvalidDecl();
10432       return;
10433     }
10434 
10435     Init = Result.getAs<Expr>();
10436   }
10437 
10438   // Check for self-references within variable initializers.
10439   // Variables declared within a function/method body (except for references)
10440   // are handled by a dataflow analysis.
10441   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10442       VDecl->getType()->isReferenceType()) {
10443     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10444   }
10445 
10446   // If the type changed, it means we had an incomplete type that was
10447   // completed by the initializer. For example:
10448   //   int ary[] = { 1, 3, 5 };
10449   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10450   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10451     VDecl->setType(DclT);
10452 
10453   if (!VDecl->isInvalidDecl()) {
10454     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10455 
10456     if (VDecl->hasAttr<BlocksAttr>())
10457       checkRetainCycles(VDecl, Init);
10458 
10459     // It is safe to assign a weak reference into a strong variable.
10460     // Although this code can still have problems:
10461     //   id x = self.weakProp;
10462     //   id y = self.weakProp;
10463     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10464     // paths through the function. This should be revisited if
10465     // -Wrepeated-use-of-weak is made flow-sensitive.
10466     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10467          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10468         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10469                          Init->getLocStart()))
10470       getCurFunction()->markSafeWeakUse(Init);
10471   }
10472 
10473   // The initialization is usually a full-expression.
10474   //
10475   // FIXME: If this is a braced initialization of an aggregate, it is not
10476   // an expression, and each individual field initializer is a separate
10477   // full-expression. For instance, in:
10478   //
10479   //   struct Temp { ~Temp(); };
10480   //   struct S { S(Temp); };
10481   //   struct T { S a, b; } t = { Temp(), Temp() }
10482   //
10483   // we should destroy the first Temp before constructing the second.
10484   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10485                                           false,
10486                                           VDecl->isConstexpr());
10487   if (Result.isInvalid()) {
10488     VDecl->setInvalidDecl();
10489     return;
10490   }
10491   Init = Result.get();
10492 
10493   // Attach the initializer to the decl.
10494   VDecl->setInit(Init);
10495 
10496   if (VDecl->isLocalVarDecl()) {
10497     // Don't check the initializer if the declaration is malformed.
10498     if (VDecl->isInvalidDecl()) {
10499       // do nothing
10500 
10501     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10502     // This is true even in OpenCL C++.
10503     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10504       CheckForConstantInitializer(Init, DclT);
10505 
10506     // Otherwise, C++ does not restrict the initializer.
10507     } else if (getLangOpts().CPlusPlus) {
10508       // do nothing
10509 
10510     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10511     // static storage duration shall be constant expressions or string literals.
10512     } else if (VDecl->getStorageClass() == SC_Static) {
10513       CheckForConstantInitializer(Init, DclT);
10514 
10515     // C89 is stricter than C99 for aggregate initializers.
10516     // C89 6.5.7p3: All the expressions [...] in an initializer list
10517     // for an object that has aggregate or union type shall be
10518     // constant expressions.
10519     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10520                isa<InitListExpr>(Init)) {
10521       const Expr *Culprit;
10522       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10523         Diag(Culprit->getExprLoc(),
10524              diag::ext_aggregate_init_not_constant)
10525           << Culprit->getSourceRange();
10526       }
10527     }
10528   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10529              VDecl->getLexicalDeclContext()->isRecord()) {
10530     // This is an in-class initialization for a static data member, e.g.,
10531     //
10532     // struct S {
10533     //   static const int value = 17;
10534     // };
10535 
10536     // C++ [class.mem]p4:
10537     //   A member-declarator can contain a constant-initializer only
10538     //   if it declares a static member (9.4) of const integral or
10539     //   const enumeration type, see 9.4.2.
10540     //
10541     // C++11 [class.static.data]p3:
10542     //   If a non-volatile non-inline const static data member is of integral
10543     //   or enumeration type, its declaration in the class definition can
10544     //   specify a brace-or-equal-initializer in which every initializer-clause
10545     //   that is an assignment-expression is a constant expression. A static
10546     //   data member of literal type can be declared in the class definition
10547     //   with the constexpr specifier; if so, its declaration shall specify a
10548     //   brace-or-equal-initializer in which every initializer-clause that is
10549     //   an assignment-expression is a constant expression.
10550 
10551     // Do nothing on dependent types.
10552     if (DclT->isDependentType()) {
10553 
10554     // Allow any 'static constexpr' members, whether or not they are of literal
10555     // type. We separately check that every constexpr variable is of literal
10556     // type.
10557     } else if (VDecl->isConstexpr()) {
10558 
10559     // Require constness.
10560     } else if (!DclT.isConstQualified()) {
10561       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10562         << Init->getSourceRange();
10563       VDecl->setInvalidDecl();
10564 
10565     // We allow integer constant expressions in all cases.
10566     } else if (DclT->isIntegralOrEnumerationType()) {
10567       // Check whether the expression is a constant expression.
10568       SourceLocation Loc;
10569       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10570         // In C++11, a non-constexpr const static data member with an
10571         // in-class initializer cannot be volatile.
10572         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10573       else if (Init->isValueDependent())
10574         ; // Nothing to check.
10575       else if (Init->isIntegerConstantExpr(Context, &Loc))
10576         ; // Ok, it's an ICE!
10577       else if (Init->isEvaluatable(Context)) {
10578         // If we can constant fold the initializer through heroics, accept it,
10579         // but report this as a use of an extension for -pedantic.
10580         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10581           << Init->getSourceRange();
10582       } else {
10583         // Otherwise, this is some crazy unknown case.  Report the issue at the
10584         // location provided by the isIntegerConstantExpr failed check.
10585         Diag(Loc, diag::err_in_class_initializer_non_constant)
10586           << Init->getSourceRange();
10587         VDecl->setInvalidDecl();
10588       }
10589 
10590     // We allow foldable floating-point constants as an extension.
10591     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10592       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10593       // it anyway and provide a fixit to add the 'constexpr'.
10594       if (getLangOpts().CPlusPlus11) {
10595         Diag(VDecl->getLocation(),
10596              diag::ext_in_class_initializer_float_type_cxx11)
10597             << DclT << Init->getSourceRange();
10598         Diag(VDecl->getLocStart(),
10599              diag::note_in_class_initializer_float_type_cxx11)
10600             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10601       } else {
10602         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10603           << DclT << Init->getSourceRange();
10604 
10605         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10606           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10607             << Init->getSourceRange();
10608           VDecl->setInvalidDecl();
10609         }
10610       }
10611 
10612     // Suggest adding 'constexpr' in C++11 for literal types.
10613     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10614       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10615         << DclT << Init->getSourceRange()
10616         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10617       VDecl->setConstexpr(true);
10618 
10619     } else {
10620       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10621         << DclT << Init->getSourceRange();
10622       VDecl->setInvalidDecl();
10623     }
10624   } else if (VDecl->isFileVarDecl()) {
10625     // In C, extern is typically used to avoid tentative definitions when
10626     // declaring variables in headers, but adding an intializer makes it a
10627     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10628     // In C++, extern is often used to give implictly static const variables
10629     // external linkage, so don't warn in that case. If selectany is present,
10630     // this might be header code intended for C and C++ inclusion, so apply the
10631     // C++ rules.
10632     if (VDecl->getStorageClass() == SC_Extern &&
10633         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10634          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10635         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10636         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10637       Diag(VDecl->getLocation(), diag::warn_extern_init);
10638 
10639     // C99 6.7.8p4. All file scoped initializers need to be constant.
10640     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10641       CheckForConstantInitializer(Init, DclT);
10642   }
10643 
10644   // We will represent direct-initialization similarly to copy-initialization:
10645   //    int x(1);  -as-> int x = 1;
10646   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10647   //
10648   // Clients that want to distinguish between the two forms, can check for
10649   // direct initializer using VarDecl::getInitStyle().
10650   // A major benefit is that clients that don't particularly care about which
10651   // exactly form was it (like the CodeGen) can handle both cases without
10652   // special case code.
10653 
10654   // C++ 8.5p11:
10655   // The form of initialization (using parentheses or '=') is generally
10656   // insignificant, but does matter when the entity being initialized has a
10657   // class type.
10658   if (CXXDirectInit) {
10659     assert(DirectInit && "Call-style initializer must be direct init.");
10660     VDecl->setInitStyle(VarDecl::CallInit);
10661   } else if (DirectInit) {
10662     // This must be list-initialization. No other way is direct-initialization.
10663     VDecl->setInitStyle(VarDecl::ListInit);
10664   }
10665 
10666   CheckCompleteVariableDeclaration(VDecl);
10667 }
10668 
10669 /// ActOnInitializerError - Given that there was an error parsing an
10670 /// initializer for the given declaration, try to return to some form
10671 /// of sanity.
10672 void Sema::ActOnInitializerError(Decl *D) {
10673   // Our main concern here is re-establishing invariants like "a
10674   // variable's type is either dependent or complete".
10675   if (!D || D->isInvalidDecl()) return;
10676 
10677   VarDecl *VD = dyn_cast<VarDecl>(D);
10678   if (!VD) return;
10679 
10680   // Bindings are not usable if we can't make sense of the initializer.
10681   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10682     for (auto *BD : DD->bindings())
10683       BD->setInvalidDecl();
10684 
10685   // Auto types are meaningless if we can't make sense of the initializer.
10686   if (ParsingInitForAutoVars.count(D)) {
10687     D->setInvalidDecl();
10688     return;
10689   }
10690 
10691   QualType Ty = VD->getType();
10692   if (Ty->isDependentType()) return;
10693 
10694   // Require a complete type.
10695   if (RequireCompleteType(VD->getLocation(),
10696                           Context.getBaseElementType(Ty),
10697                           diag::err_typecheck_decl_incomplete_type)) {
10698     VD->setInvalidDecl();
10699     return;
10700   }
10701 
10702   // Require a non-abstract type.
10703   if (RequireNonAbstractType(VD->getLocation(), Ty,
10704                              diag::err_abstract_type_in_decl,
10705                              AbstractVariableType)) {
10706     VD->setInvalidDecl();
10707     return;
10708   }
10709 
10710   // Don't bother complaining about constructors or destructors,
10711   // though.
10712 }
10713 
10714 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10715   // If there is no declaration, there was an error parsing it. Just ignore it.
10716   if (!RealDecl)
10717     return;
10718 
10719   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10720     QualType Type = Var->getType();
10721 
10722     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10723     if (isa<DecompositionDecl>(RealDecl)) {
10724       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10725       Var->setInvalidDecl();
10726       return;
10727     }
10728 
10729     if (Type->isUndeducedType() &&
10730         DeduceVariableDeclarationType(Var, false, nullptr))
10731       return;
10732 
10733     // C++11 [class.static.data]p3: A static data member can be declared with
10734     // the constexpr specifier; if so, its declaration shall specify
10735     // a brace-or-equal-initializer.
10736     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10737     // the definition of a variable [...] or the declaration of a static data
10738     // member.
10739     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10740         !Var->isThisDeclarationADemotedDefinition()) {
10741       if (Var->isStaticDataMember()) {
10742         // C++1z removes the relevant rule; the in-class declaration is always
10743         // a definition there.
10744         if (!getLangOpts().CPlusPlus1z) {
10745           Diag(Var->getLocation(),
10746                diag::err_constexpr_static_mem_var_requires_init)
10747             << Var->getDeclName();
10748           Var->setInvalidDecl();
10749           return;
10750         }
10751       } else {
10752         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10753         Var->setInvalidDecl();
10754         return;
10755       }
10756     }
10757 
10758     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10759     // definition having the concept specifier is called a variable concept. A
10760     // concept definition refers to [...] a variable concept and its initializer.
10761     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10762       if (VTD->isConcept()) {
10763         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10764         Var->setInvalidDecl();
10765         return;
10766       }
10767     }
10768 
10769     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10770     // be initialized.
10771     if (!Var->isInvalidDecl() &&
10772         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10773         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10774       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10775       Var->setInvalidDecl();
10776       return;
10777     }
10778 
10779     switch (Var->isThisDeclarationADefinition()) {
10780     case VarDecl::Definition:
10781       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10782         break;
10783 
10784       // We have an out-of-line definition of a static data member
10785       // that has an in-class initializer, so we type-check this like
10786       // a declaration.
10787       //
10788       // Fall through
10789 
10790     case VarDecl::DeclarationOnly:
10791       // It's only a declaration.
10792 
10793       // Block scope. C99 6.7p7: If an identifier for an object is
10794       // declared with no linkage (C99 6.2.2p6), the type for the
10795       // object shall be complete.
10796       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10797           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10798           RequireCompleteType(Var->getLocation(), Type,
10799                               diag::err_typecheck_decl_incomplete_type))
10800         Var->setInvalidDecl();
10801 
10802       // Make sure that the type is not abstract.
10803       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10804           RequireNonAbstractType(Var->getLocation(), Type,
10805                                  diag::err_abstract_type_in_decl,
10806                                  AbstractVariableType))
10807         Var->setInvalidDecl();
10808       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10809           Var->getStorageClass() == SC_PrivateExtern) {
10810         Diag(Var->getLocation(), diag::warn_private_extern);
10811         Diag(Var->getLocation(), diag::note_private_extern);
10812       }
10813 
10814       return;
10815 
10816     case VarDecl::TentativeDefinition:
10817       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10818       // object that has file scope without an initializer, and without a
10819       // storage-class specifier or with the storage-class specifier "static",
10820       // constitutes a tentative definition. Note: A tentative definition with
10821       // external linkage is valid (C99 6.2.2p5).
10822       if (!Var->isInvalidDecl()) {
10823         if (const IncompleteArrayType *ArrayT
10824                                     = Context.getAsIncompleteArrayType(Type)) {
10825           if (RequireCompleteType(Var->getLocation(),
10826                                   ArrayT->getElementType(),
10827                                   diag::err_illegal_decl_array_incomplete_type))
10828             Var->setInvalidDecl();
10829         } else if (Var->getStorageClass() == SC_Static) {
10830           // C99 6.9.2p3: If the declaration of an identifier for an object is
10831           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10832           // declared type shall not be an incomplete type.
10833           // NOTE: code such as the following
10834           //     static struct s;
10835           //     struct s { int a; };
10836           // is accepted by gcc. Hence here we issue a warning instead of
10837           // an error and we do not invalidate the static declaration.
10838           // NOTE: to avoid multiple warnings, only check the first declaration.
10839           if (Var->isFirstDecl())
10840             RequireCompleteType(Var->getLocation(), Type,
10841                                 diag::ext_typecheck_decl_incomplete_type);
10842         }
10843       }
10844 
10845       // Record the tentative definition; we're done.
10846       if (!Var->isInvalidDecl())
10847         TentativeDefinitions.push_back(Var);
10848       return;
10849     }
10850 
10851     // Provide a specific diagnostic for uninitialized variable
10852     // definitions with incomplete array type.
10853     if (Type->isIncompleteArrayType()) {
10854       Diag(Var->getLocation(),
10855            diag::err_typecheck_incomplete_array_needs_initializer);
10856       Var->setInvalidDecl();
10857       return;
10858     }
10859 
10860     // Provide a specific diagnostic for uninitialized variable
10861     // definitions with reference type.
10862     if (Type->isReferenceType()) {
10863       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10864         << Var->getDeclName()
10865         << SourceRange(Var->getLocation(), Var->getLocation());
10866       Var->setInvalidDecl();
10867       return;
10868     }
10869 
10870     // Do not attempt to type-check the default initializer for a
10871     // variable with dependent type.
10872     if (Type->isDependentType())
10873       return;
10874 
10875     if (Var->isInvalidDecl())
10876       return;
10877 
10878     if (!Var->hasAttr<AliasAttr>()) {
10879       if (RequireCompleteType(Var->getLocation(),
10880                               Context.getBaseElementType(Type),
10881                               diag::err_typecheck_decl_incomplete_type)) {
10882         Var->setInvalidDecl();
10883         return;
10884       }
10885     } else {
10886       return;
10887     }
10888 
10889     // The variable can not have an abstract class type.
10890     if (RequireNonAbstractType(Var->getLocation(), Type,
10891                                diag::err_abstract_type_in_decl,
10892                                AbstractVariableType)) {
10893       Var->setInvalidDecl();
10894       return;
10895     }
10896 
10897     // Check for jumps past the implicit initializer.  C++0x
10898     // clarifies that this applies to a "variable with automatic
10899     // storage duration", not a "local variable".
10900     // C++11 [stmt.dcl]p3
10901     //   A program that jumps from a point where a variable with automatic
10902     //   storage duration is not in scope to a point where it is in scope is
10903     //   ill-formed unless the variable has scalar type, class type with a
10904     //   trivial default constructor and a trivial destructor, a cv-qualified
10905     //   version of one of these types, or an array of one of the preceding
10906     //   types and is declared without an initializer.
10907     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10908       if (const RecordType *Record
10909             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10910         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10911         // Mark the function for further checking even if the looser rules of
10912         // C++11 do not require such checks, so that we can diagnose
10913         // incompatibilities with C++98.
10914         if (!CXXRecord->isPOD())
10915           getCurFunction()->setHasBranchProtectedScope();
10916       }
10917     }
10918 
10919     // C++03 [dcl.init]p9:
10920     //   If no initializer is specified for an object, and the
10921     //   object is of (possibly cv-qualified) non-POD class type (or
10922     //   array thereof), the object shall be default-initialized; if
10923     //   the object is of const-qualified type, the underlying class
10924     //   type shall have a user-declared default
10925     //   constructor. Otherwise, if no initializer is specified for
10926     //   a non- static object, the object and its subobjects, if
10927     //   any, have an indeterminate initial value); if the object
10928     //   or any of its subobjects are of const-qualified type, the
10929     //   program is ill-formed.
10930     // C++0x [dcl.init]p11:
10931     //   If no initializer is specified for an object, the object is
10932     //   default-initialized; [...].
10933     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10934     InitializationKind Kind
10935       = InitializationKind::CreateDefault(Var->getLocation());
10936 
10937     InitializationSequence InitSeq(*this, Entity, Kind, None);
10938     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10939     if (Init.isInvalid())
10940       Var->setInvalidDecl();
10941     else if (Init.get()) {
10942       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10943       // This is important for template substitution.
10944       Var->setInitStyle(VarDecl::CallInit);
10945     }
10946 
10947     CheckCompleteVariableDeclaration(Var);
10948   }
10949 }
10950 
10951 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10952   // If there is no declaration, there was an error parsing it. Ignore it.
10953   if (!D)
10954     return;
10955 
10956   VarDecl *VD = dyn_cast<VarDecl>(D);
10957   if (!VD) {
10958     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10959     D->setInvalidDecl();
10960     return;
10961   }
10962 
10963   VD->setCXXForRangeDecl(true);
10964 
10965   // for-range-declaration cannot be given a storage class specifier.
10966   int Error = -1;
10967   switch (VD->getStorageClass()) {
10968   case SC_None:
10969     break;
10970   case SC_Extern:
10971     Error = 0;
10972     break;
10973   case SC_Static:
10974     Error = 1;
10975     break;
10976   case SC_PrivateExtern:
10977     Error = 2;
10978     break;
10979   case SC_Auto:
10980     Error = 3;
10981     break;
10982   case SC_Register:
10983     Error = 4;
10984     break;
10985   }
10986   if (Error != -1) {
10987     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10988       << VD->getDeclName() << Error;
10989     D->setInvalidDecl();
10990   }
10991 }
10992 
10993 StmtResult
10994 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10995                                  IdentifierInfo *Ident,
10996                                  ParsedAttributes &Attrs,
10997                                  SourceLocation AttrEnd) {
10998   // C++1y [stmt.iter]p1:
10999   //   A range-based for statement of the form
11000   //      for ( for-range-identifier : for-range-initializer ) statement
11001   //   is equivalent to
11002   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11003   DeclSpec DS(Attrs.getPool().getFactory());
11004 
11005   const char *PrevSpec;
11006   unsigned DiagID;
11007   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11008                      getPrintingPolicy());
11009 
11010   Declarator D(DS, Declarator::ForContext);
11011   D.SetIdentifier(Ident, IdentLoc);
11012   D.takeAttributes(Attrs, AttrEnd);
11013 
11014   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11015   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11016                 EmptyAttrs, IdentLoc);
11017   Decl *Var = ActOnDeclarator(S, D);
11018   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11019   FinalizeDeclaration(Var);
11020   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11021                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11022 }
11023 
11024 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11025   if (var->isInvalidDecl()) return;
11026 
11027   if (getLangOpts().OpenCL) {
11028     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11029     // initialiser
11030     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11031         !var->hasInit()) {
11032       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11033           << 1 /*Init*/;
11034       var->setInvalidDecl();
11035       return;
11036     }
11037   }
11038 
11039   // In Objective-C, don't allow jumps past the implicit initialization of a
11040   // local retaining variable.
11041   if (getLangOpts().ObjC1 &&
11042       var->hasLocalStorage()) {
11043     switch (var->getType().getObjCLifetime()) {
11044     case Qualifiers::OCL_None:
11045     case Qualifiers::OCL_ExplicitNone:
11046     case Qualifiers::OCL_Autoreleasing:
11047       break;
11048 
11049     case Qualifiers::OCL_Weak:
11050     case Qualifiers::OCL_Strong:
11051       getCurFunction()->setHasBranchProtectedScope();
11052       break;
11053     }
11054   }
11055 
11056   // Warn about externally-visible variables being defined without a
11057   // prior declaration.  We only want to do this for global
11058   // declarations, but we also specifically need to avoid doing it for
11059   // class members because the linkage of an anonymous class can
11060   // change if it's later given a typedef name.
11061   if (var->isThisDeclarationADefinition() &&
11062       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11063       var->isExternallyVisible() && var->hasLinkage() &&
11064       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11065                                   var->getLocation())) {
11066     // Find a previous declaration that's not a definition.
11067     VarDecl *prev = var->getPreviousDecl();
11068     while (prev && prev->isThisDeclarationADefinition())
11069       prev = prev->getPreviousDecl();
11070 
11071     if (!prev)
11072       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11073   }
11074 
11075   // Cache the result of checking for constant initialization.
11076   Optional<bool> CacheHasConstInit;
11077   const Expr *CacheCulprit;
11078   auto checkConstInit = [&]() mutable {
11079     if (!CacheHasConstInit)
11080       CacheHasConstInit = var->getInit()->isConstantInitializer(
11081             Context, var->getType()->isReferenceType(), &CacheCulprit);
11082     return *CacheHasConstInit;
11083   };
11084 
11085   if (var->getTLSKind() == VarDecl::TLS_Static) {
11086     if (var->getType().isDestructedType()) {
11087       // GNU C++98 edits for __thread, [basic.start.term]p3:
11088       //   The type of an object with thread storage duration shall not
11089       //   have a non-trivial destructor.
11090       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11091       if (getLangOpts().CPlusPlus11)
11092         Diag(var->getLocation(), diag::note_use_thread_local);
11093     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11094       if (!checkConstInit()) {
11095         // GNU C++98 edits for __thread, [basic.start.init]p4:
11096         //   An object of thread storage duration shall not require dynamic
11097         //   initialization.
11098         // FIXME: Need strict checking here.
11099         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11100           << CacheCulprit->getSourceRange();
11101         if (getLangOpts().CPlusPlus11)
11102           Diag(var->getLocation(), diag::note_use_thread_local);
11103       }
11104     }
11105   }
11106 
11107   // Apply section attributes and pragmas to global variables.
11108   bool GlobalStorage = var->hasGlobalStorage();
11109   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11110       !inTemplateInstantiation()) {
11111     PragmaStack<StringLiteral *> *Stack = nullptr;
11112     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11113     if (var->getType().isConstQualified())
11114       Stack = &ConstSegStack;
11115     else if (!var->getInit()) {
11116       Stack = &BSSSegStack;
11117       SectionFlags |= ASTContext::PSF_Write;
11118     } else {
11119       Stack = &DataSegStack;
11120       SectionFlags |= ASTContext::PSF_Write;
11121     }
11122     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11123       var->addAttr(SectionAttr::CreateImplicit(
11124           Context, SectionAttr::Declspec_allocate,
11125           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11126     }
11127     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11128       if (UnifySection(SA->getName(), SectionFlags, var))
11129         var->dropAttr<SectionAttr>();
11130 
11131     // Apply the init_seg attribute if this has an initializer.  If the
11132     // initializer turns out to not be dynamic, we'll end up ignoring this
11133     // attribute.
11134     if (CurInitSeg && var->getInit())
11135       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11136                                                CurInitSegLoc));
11137   }
11138 
11139   // All the following checks are C++ only.
11140   if (!getLangOpts().CPlusPlus) {
11141       // If this variable must be emitted, add it as an initializer for the
11142       // current module.
11143      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11144        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11145      return;
11146   }
11147 
11148   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11149     CheckCompleteDecompositionDeclaration(DD);
11150 
11151   QualType type = var->getType();
11152   if (type->isDependentType()) return;
11153 
11154   // __block variables might require us to capture a copy-initializer.
11155   if (var->hasAttr<BlocksAttr>()) {
11156     // It's currently invalid to ever have a __block variable with an
11157     // array type; should we diagnose that here?
11158 
11159     // Regardless, we don't want to ignore array nesting when
11160     // constructing this copy.
11161     if (type->isStructureOrClassType()) {
11162       EnterExpressionEvaluationContext scope(
11163           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11164       SourceLocation poi = var->getLocation();
11165       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11166       ExprResult result
11167         = PerformMoveOrCopyInitialization(
11168             InitializedEntity::InitializeBlock(poi, type, false),
11169             var, var->getType(), varRef, /*AllowNRVO=*/true);
11170       if (!result.isInvalid()) {
11171         result = MaybeCreateExprWithCleanups(result);
11172         Expr *init = result.getAs<Expr>();
11173         Context.setBlockVarCopyInits(var, init);
11174       }
11175     }
11176   }
11177 
11178   Expr *Init = var->getInit();
11179   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11180   QualType baseType = Context.getBaseElementType(type);
11181 
11182   if (Init && !Init->isValueDependent()) {
11183     if (var->isConstexpr()) {
11184       SmallVector<PartialDiagnosticAt, 8> Notes;
11185       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11186         SourceLocation DiagLoc = var->getLocation();
11187         // If the note doesn't add any useful information other than a source
11188         // location, fold it into the primary diagnostic.
11189         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11190               diag::note_invalid_subexpr_in_const_expr) {
11191           DiagLoc = Notes[0].first;
11192           Notes.clear();
11193         }
11194         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11195           << var << Init->getSourceRange();
11196         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11197           Diag(Notes[I].first, Notes[I].second);
11198       }
11199     } else if (var->isUsableInConstantExpressions(Context)) {
11200       // Check whether the initializer of a const variable of integral or
11201       // enumeration type is an ICE now, since we can't tell whether it was
11202       // initialized by a constant expression if we check later.
11203       var->checkInitIsICE();
11204     }
11205 
11206     // Don't emit further diagnostics about constexpr globals since they
11207     // were just diagnosed.
11208     if (!var->isConstexpr() && GlobalStorage &&
11209             var->hasAttr<RequireConstantInitAttr>()) {
11210       // FIXME: Need strict checking in C++03 here.
11211       bool DiagErr = getLangOpts().CPlusPlus11
11212           ? !var->checkInitIsICE() : !checkConstInit();
11213       if (DiagErr) {
11214         auto attr = var->getAttr<RequireConstantInitAttr>();
11215         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11216           << Init->getSourceRange();
11217         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11218           << attr->getRange();
11219         if (getLangOpts().CPlusPlus11) {
11220           APValue Value;
11221           SmallVector<PartialDiagnosticAt, 8> Notes;
11222           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11223           for (auto &it : Notes)
11224             Diag(it.first, it.second);
11225         } else {
11226           Diag(CacheCulprit->getExprLoc(),
11227                diag::note_invalid_subexpr_in_const_expr)
11228               << CacheCulprit->getSourceRange();
11229         }
11230       }
11231     }
11232     else if (!var->isConstexpr() && IsGlobal &&
11233              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11234                                     var->getLocation())) {
11235       // Warn about globals which don't have a constant initializer.  Don't
11236       // warn about globals with a non-trivial destructor because we already
11237       // warned about them.
11238       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11239       if (!(RD && !RD->hasTrivialDestructor())) {
11240         if (!checkConstInit())
11241           Diag(var->getLocation(), diag::warn_global_constructor)
11242             << Init->getSourceRange();
11243       }
11244     }
11245   }
11246 
11247   // Require the destructor.
11248   if (const RecordType *recordType = baseType->getAs<RecordType>())
11249     FinalizeVarWithDestructor(var, recordType);
11250 
11251   // If this variable must be emitted, add it as an initializer for the current
11252   // module.
11253   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11254     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11255 }
11256 
11257 /// \brief Determines if a variable's alignment is dependent.
11258 static bool hasDependentAlignment(VarDecl *VD) {
11259   if (VD->getType()->isDependentType())
11260     return true;
11261   for (auto *I : VD->specific_attrs<AlignedAttr>())
11262     if (I->isAlignmentDependent())
11263       return true;
11264   return false;
11265 }
11266 
11267 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11268 /// any semantic actions necessary after any initializer has been attached.
11269 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11270   // Note that we are no longer parsing the initializer for this declaration.
11271   ParsingInitForAutoVars.erase(ThisDecl);
11272 
11273   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11274   if (!VD)
11275     return;
11276 
11277   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11278   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11279       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11280     if (PragmaClangBSSSection.Valid)
11281       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11282                                                             PragmaClangBSSSection.SectionName,
11283                                                             PragmaClangBSSSection.PragmaLocation));
11284     if (PragmaClangDataSection.Valid)
11285       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11286                                                              PragmaClangDataSection.SectionName,
11287                                                              PragmaClangDataSection.PragmaLocation));
11288     if (PragmaClangRodataSection.Valid)
11289       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11290                                                                PragmaClangRodataSection.SectionName,
11291                                                                PragmaClangRodataSection.PragmaLocation));
11292   }
11293 
11294   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11295     for (auto *BD : DD->bindings()) {
11296       FinalizeDeclaration(BD);
11297     }
11298   }
11299 
11300   checkAttributesAfterMerging(*this, *VD);
11301 
11302   // Perform TLS alignment check here after attributes attached to the variable
11303   // which may affect the alignment have been processed. Only perform the check
11304   // if the target has a maximum TLS alignment (zero means no constraints).
11305   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11306     // Protect the check so that it's not performed on dependent types and
11307     // dependent alignments (we can't determine the alignment in that case).
11308     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11309         !VD->isInvalidDecl()) {
11310       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11311       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11312         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11313           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11314           << (unsigned)MaxAlignChars.getQuantity();
11315       }
11316     }
11317   }
11318 
11319   if (VD->isStaticLocal()) {
11320     if (FunctionDecl *FD =
11321             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11322       // Static locals inherit dll attributes from their function.
11323       if (Attr *A = getDLLAttr(FD)) {
11324         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11325         NewAttr->setInherited(true);
11326         VD->addAttr(NewAttr);
11327       }
11328       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11329       // function, only __shared__ variables may be declared with
11330       // static storage class.
11331       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11332           CUDADiagIfDeviceCode(VD->getLocation(),
11333                                diag::err_device_static_local_var)
11334               << CurrentCUDATarget())
11335         VD->setInvalidDecl();
11336     }
11337   }
11338 
11339   // Perform check for initializers of device-side global variables.
11340   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11341   // 7.5). We must also apply the same checks to all __shared__
11342   // variables whether they are local or not. CUDA also allows
11343   // constant initializers for __constant__ and __device__ variables.
11344   if (getLangOpts().CUDA) {
11345     const Expr *Init = VD->getInit();
11346     if (Init && VD->hasGlobalStorage()) {
11347       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11348           VD->hasAttr<CUDASharedAttr>()) {
11349         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11350         bool AllowedInit = false;
11351         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11352           AllowedInit =
11353               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11354         // We'll allow constant initializers even if it's a non-empty
11355         // constructor according to CUDA rules. This deviates from NVCC,
11356         // but allows us to handle things like constexpr constructors.
11357         if (!AllowedInit &&
11358             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11359           AllowedInit = VD->getInit()->isConstantInitializer(
11360               Context, VD->getType()->isReferenceType());
11361 
11362         // Also make sure that destructor, if there is one, is empty.
11363         if (AllowedInit)
11364           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11365             AllowedInit =
11366                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11367 
11368         if (!AllowedInit) {
11369           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11370                                       ? diag::err_shared_var_init
11371                                       : diag::err_dynamic_var_init)
11372               << Init->getSourceRange();
11373           VD->setInvalidDecl();
11374         }
11375       } else {
11376         // This is a host-side global variable.  Check that the initializer is
11377         // callable from the host side.
11378         const FunctionDecl *InitFn = nullptr;
11379         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11380           InitFn = CE->getConstructor();
11381         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11382           InitFn = CE->getDirectCallee();
11383         }
11384         if (InitFn) {
11385           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11386           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11387             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11388                 << InitFnTarget << InitFn;
11389             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11390             VD->setInvalidDecl();
11391           }
11392         }
11393       }
11394     }
11395   }
11396 
11397   // Grab the dllimport or dllexport attribute off of the VarDecl.
11398   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11399 
11400   // Imported static data members cannot be defined out-of-line.
11401   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11402     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11403         VD->isThisDeclarationADefinition()) {
11404       // We allow definitions of dllimport class template static data members
11405       // with a warning.
11406       CXXRecordDecl *Context =
11407         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11408       bool IsClassTemplateMember =
11409           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11410           Context->getDescribedClassTemplate();
11411 
11412       Diag(VD->getLocation(),
11413            IsClassTemplateMember
11414                ? diag::warn_attribute_dllimport_static_field_definition
11415                : diag::err_attribute_dllimport_static_field_definition);
11416       Diag(IA->getLocation(), diag::note_attribute);
11417       if (!IsClassTemplateMember)
11418         VD->setInvalidDecl();
11419     }
11420   }
11421 
11422   // dllimport/dllexport variables cannot be thread local, their TLS index
11423   // isn't exported with the variable.
11424   if (DLLAttr && VD->getTLSKind()) {
11425     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11426     if (F && getDLLAttr(F)) {
11427       assert(VD->isStaticLocal());
11428       // But if this is a static local in a dlimport/dllexport function, the
11429       // function will never be inlined, which means the var would never be
11430       // imported, so having it marked import/export is safe.
11431     } else {
11432       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11433                                                                     << DLLAttr;
11434       VD->setInvalidDecl();
11435     }
11436   }
11437 
11438   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11439     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11440       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11441       VD->dropAttr<UsedAttr>();
11442     }
11443   }
11444 
11445   const DeclContext *DC = VD->getDeclContext();
11446   // If there's a #pragma GCC visibility in scope, and this isn't a class
11447   // member, set the visibility of this variable.
11448   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11449     AddPushedVisibilityAttribute(VD);
11450 
11451   // FIXME: Warn on unused var template partial specializations.
11452   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11453     MarkUnusedFileScopedDecl(VD);
11454 
11455   // Now we have parsed the initializer and can update the table of magic
11456   // tag values.
11457   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11458       !VD->getType()->isIntegralOrEnumerationType())
11459     return;
11460 
11461   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11462     const Expr *MagicValueExpr = VD->getInit();
11463     if (!MagicValueExpr) {
11464       continue;
11465     }
11466     llvm::APSInt MagicValueInt;
11467     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11468       Diag(I->getRange().getBegin(),
11469            diag::err_type_tag_for_datatype_not_ice)
11470         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11471       continue;
11472     }
11473     if (MagicValueInt.getActiveBits() > 64) {
11474       Diag(I->getRange().getBegin(),
11475            diag::err_type_tag_for_datatype_too_large)
11476         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11477       continue;
11478     }
11479     uint64_t MagicValue = MagicValueInt.getZExtValue();
11480     RegisterTypeTagForDatatype(I->getArgumentKind(),
11481                                MagicValue,
11482                                I->getMatchingCType(),
11483                                I->getLayoutCompatible(),
11484                                I->getMustBeNull());
11485   }
11486 }
11487 
11488 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11489   auto *VD = dyn_cast<VarDecl>(DD);
11490   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11491 }
11492 
11493 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11494                                                    ArrayRef<Decl *> Group) {
11495   SmallVector<Decl*, 8> Decls;
11496 
11497   if (DS.isTypeSpecOwned())
11498     Decls.push_back(DS.getRepAsDecl());
11499 
11500   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11501   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11502   bool DiagnosedMultipleDecomps = false;
11503   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11504   bool DiagnosedNonDeducedAuto = false;
11505 
11506   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11507     if (Decl *D = Group[i]) {
11508       // For declarators, there are some additional syntactic-ish checks we need
11509       // to perform.
11510       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11511         if (!FirstDeclaratorInGroup)
11512           FirstDeclaratorInGroup = DD;
11513         if (!FirstDecompDeclaratorInGroup)
11514           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11515         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11516             !hasDeducedAuto(DD))
11517           FirstNonDeducedAutoInGroup = DD;
11518 
11519         if (FirstDeclaratorInGroup != DD) {
11520           // A decomposition declaration cannot be combined with any other
11521           // declaration in the same group.
11522           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11523             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11524                  diag::err_decomp_decl_not_alone)
11525                 << FirstDeclaratorInGroup->getSourceRange()
11526                 << DD->getSourceRange();
11527             DiagnosedMultipleDecomps = true;
11528           }
11529 
11530           // A declarator that uses 'auto' in any way other than to declare a
11531           // variable with a deduced type cannot be combined with any other
11532           // declarator in the same group.
11533           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11534             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11535                  diag::err_auto_non_deduced_not_alone)
11536                 << FirstNonDeducedAutoInGroup->getType()
11537                        ->hasAutoForTrailingReturnType()
11538                 << FirstDeclaratorInGroup->getSourceRange()
11539                 << DD->getSourceRange();
11540             DiagnosedNonDeducedAuto = true;
11541           }
11542         }
11543       }
11544 
11545       Decls.push_back(D);
11546     }
11547   }
11548 
11549   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11550     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11551       handleTagNumbering(Tag, S);
11552       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11553           getLangOpts().CPlusPlus)
11554         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11555     }
11556   }
11557 
11558   return BuildDeclaratorGroup(Decls);
11559 }
11560 
11561 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11562 /// group, performing any necessary semantic checking.
11563 Sema::DeclGroupPtrTy
11564 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11565   // C++14 [dcl.spec.auto]p7: (DR1347)
11566   //   If the type that replaces the placeholder type is not the same in each
11567   //   deduction, the program is ill-formed.
11568   if (Group.size() > 1) {
11569     QualType Deduced;
11570     VarDecl *DeducedDecl = nullptr;
11571     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11572       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11573       if (!D || D->isInvalidDecl())
11574         break;
11575       DeducedType *DT = D->getType()->getContainedDeducedType();
11576       if (!DT || DT->getDeducedType().isNull())
11577         continue;
11578       if (Deduced.isNull()) {
11579         Deduced = DT->getDeducedType();
11580         DeducedDecl = D;
11581       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11582         auto *AT = dyn_cast<AutoType>(DT);
11583         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11584              diag::err_auto_different_deductions)
11585           << (AT ? (unsigned)AT->getKeyword() : 3)
11586           << Deduced << DeducedDecl->getDeclName()
11587           << DT->getDeducedType() << D->getDeclName()
11588           << DeducedDecl->getInit()->getSourceRange()
11589           << D->getInit()->getSourceRange();
11590         D->setInvalidDecl();
11591         break;
11592       }
11593     }
11594   }
11595 
11596   ActOnDocumentableDecls(Group);
11597 
11598   return DeclGroupPtrTy::make(
11599       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11600 }
11601 
11602 void Sema::ActOnDocumentableDecl(Decl *D) {
11603   ActOnDocumentableDecls(D);
11604 }
11605 
11606 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11607   // Don't parse the comment if Doxygen diagnostics are ignored.
11608   if (Group.empty() || !Group[0])
11609     return;
11610 
11611   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11612                       Group[0]->getLocation()) &&
11613       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11614                       Group[0]->getLocation()))
11615     return;
11616 
11617   if (Group.size() >= 2) {
11618     // This is a decl group.  Normally it will contain only declarations
11619     // produced from declarator list.  But in case we have any definitions or
11620     // additional declaration references:
11621     //   'typedef struct S {} S;'
11622     //   'typedef struct S *S;'
11623     //   'struct S *pS;'
11624     // FinalizeDeclaratorGroup adds these as separate declarations.
11625     Decl *MaybeTagDecl = Group[0];
11626     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11627       Group = Group.slice(1);
11628     }
11629   }
11630 
11631   // See if there are any new comments that are not attached to a decl.
11632   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11633   if (!Comments.empty() &&
11634       !Comments.back()->isAttached()) {
11635     // There is at least one comment that not attached to a decl.
11636     // Maybe it should be attached to one of these decls?
11637     //
11638     // Note that this way we pick up not only comments that precede the
11639     // declaration, but also comments that *follow* the declaration -- thanks to
11640     // the lookahead in the lexer: we've consumed the semicolon and looked
11641     // ahead through comments.
11642     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11643       Context.getCommentForDecl(Group[i], &PP);
11644   }
11645 }
11646 
11647 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11648 /// to introduce parameters into function prototype scope.
11649 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11650   const DeclSpec &DS = D.getDeclSpec();
11651 
11652   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11653 
11654   // C++03 [dcl.stc]p2 also permits 'auto'.
11655   StorageClass SC = SC_None;
11656   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11657     SC = SC_Register;
11658   } else if (getLangOpts().CPlusPlus &&
11659              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11660     SC = SC_Auto;
11661   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11662     Diag(DS.getStorageClassSpecLoc(),
11663          diag::err_invalid_storage_class_in_func_decl);
11664     D.getMutableDeclSpec().ClearStorageClassSpecs();
11665   }
11666 
11667   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11668     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11669       << DeclSpec::getSpecifierName(TSCS);
11670   if (DS.isInlineSpecified())
11671     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11672         << getLangOpts().CPlusPlus1z;
11673   if (DS.isConstexprSpecified())
11674     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11675       << 0;
11676   if (DS.isConceptSpecified())
11677     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11678 
11679   DiagnoseFunctionSpecifiers(DS);
11680 
11681   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11682   QualType parmDeclType = TInfo->getType();
11683 
11684   if (getLangOpts().CPlusPlus) {
11685     // Check that there are no default arguments inside the type of this
11686     // parameter.
11687     CheckExtraCXXDefaultArguments(D);
11688 
11689     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11690     if (D.getCXXScopeSpec().isSet()) {
11691       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11692         << D.getCXXScopeSpec().getRange();
11693       D.getCXXScopeSpec().clear();
11694     }
11695   }
11696 
11697   // Ensure we have a valid name
11698   IdentifierInfo *II = nullptr;
11699   if (D.hasName()) {
11700     II = D.getIdentifier();
11701     if (!II) {
11702       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11703         << GetNameForDeclarator(D).getName();
11704       D.setInvalidType(true);
11705     }
11706   }
11707 
11708   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11709   if (II) {
11710     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11711                    ForRedeclaration);
11712     LookupName(R, S);
11713     if (R.isSingleResult()) {
11714       NamedDecl *PrevDecl = R.getFoundDecl();
11715       if (PrevDecl->isTemplateParameter()) {
11716         // Maybe we will complain about the shadowed template parameter.
11717         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11718         // Just pretend that we didn't see the previous declaration.
11719         PrevDecl = nullptr;
11720       } else if (S->isDeclScope(PrevDecl)) {
11721         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11722         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11723 
11724         // Recover by removing the name
11725         II = nullptr;
11726         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11727         D.setInvalidType(true);
11728       }
11729     }
11730   }
11731 
11732   // Temporarily put parameter variables in the translation unit, not
11733   // the enclosing context.  This prevents them from accidentally
11734   // looking like class members in C++.
11735   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11736                                     D.getLocStart(),
11737                                     D.getIdentifierLoc(), II,
11738                                     parmDeclType, TInfo,
11739                                     SC);
11740 
11741   if (D.isInvalidType())
11742     New->setInvalidDecl();
11743 
11744   assert(S->isFunctionPrototypeScope());
11745   assert(S->getFunctionPrototypeDepth() >= 1);
11746   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11747                     S->getNextFunctionPrototypeIndex());
11748 
11749   // Add the parameter declaration into this scope.
11750   S->AddDecl(New);
11751   if (II)
11752     IdResolver.AddDecl(New);
11753 
11754   ProcessDeclAttributes(S, New, D);
11755 
11756   if (D.getDeclSpec().isModulePrivateSpecified())
11757     Diag(New->getLocation(), diag::err_module_private_local)
11758       << 1 << New->getDeclName()
11759       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11760       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11761 
11762   if (New->hasAttr<BlocksAttr>()) {
11763     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11764   }
11765   return New;
11766 }
11767 
11768 /// \brief Synthesizes a variable for a parameter arising from a
11769 /// typedef.
11770 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11771                                               SourceLocation Loc,
11772                                               QualType T) {
11773   /* FIXME: setting StartLoc == Loc.
11774      Would it be worth to modify callers so as to provide proper source
11775      location for the unnamed parameters, embedding the parameter's type? */
11776   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11777                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11778                                            SC_None, nullptr);
11779   Param->setImplicit();
11780   return Param;
11781 }
11782 
11783 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11784   // Don't diagnose unused-parameter errors in template instantiations; we
11785   // will already have done so in the template itself.
11786   if (inTemplateInstantiation())
11787     return;
11788 
11789   for (const ParmVarDecl *Parameter : Parameters) {
11790     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11791         !Parameter->hasAttr<UnusedAttr>()) {
11792       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11793         << Parameter->getDeclName();
11794     }
11795   }
11796 }
11797 
11798 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11799     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11800   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11801     return;
11802 
11803   // Warn if the return value is pass-by-value and larger than the specified
11804   // threshold.
11805   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11806     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11807     if (Size > LangOpts.NumLargeByValueCopy)
11808       Diag(D->getLocation(), diag::warn_return_value_size)
11809           << D->getDeclName() << Size;
11810   }
11811 
11812   // Warn if any parameter is pass-by-value and larger than the specified
11813   // threshold.
11814   for (const ParmVarDecl *Parameter : Parameters) {
11815     QualType T = Parameter->getType();
11816     if (T->isDependentType() || !T.isPODType(Context))
11817       continue;
11818     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11819     if (Size > LangOpts.NumLargeByValueCopy)
11820       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11821           << Parameter->getDeclName() << Size;
11822   }
11823 }
11824 
11825 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11826                                   SourceLocation NameLoc, IdentifierInfo *Name,
11827                                   QualType T, TypeSourceInfo *TSInfo,
11828                                   StorageClass SC) {
11829   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11830   if (getLangOpts().ObjCAutoRefCount &&
11831       T.getObjCLifetime() == Qualifiers::OCL_None &&
11832       T->isObjCLifetimeType()) {
11833 
11834     Qualifiers::ObjCLifetime lifetime;
11835 
11836     // Special cases for arrays:
11837     //   - if it's const, use __unsafe_unretained
11838     //   - otherwise, it's an error
11839     if (T->isArrayType()) {
11840       if (!T.isConstQualified()) {
11841         DelayedDiagnostics.add(
11842             sema::DelayedDiagnostic::makeForbiddenType(
11843             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11844       }
11845       lifetime = Qualifiers::OCL_ExplicitNone;
11846     } else {
11847       lifetime = T->getObjCARCImplicitLifetime();
11848     }
11849     T = Context.getLifetimeQualifiedType(T, lifetime);
11850   }
11851 
11852   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11853                                          Context.getAdjustedParameterType(T),
11854                                          TSInfo, SC, nullptr);
11855 
11856   // Parameters can not be abstract class types.
11857   // For record types, this is done by the AbstractClassUsageDiagnoser once
11858   // the class has been completely parsed.
11859   if (!CurContext->isRecord() &&
11860       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11861                              AbstractParamType))
11862     New->setInvalidDecl();
11863 
11864   // Parameter declarators cannot be interface types. All ObjC objects are
11865   // passed by reference.
11866   if (T->isObjCObjectType()) {
11867     SourceLocation TypeEndLoc =
11868         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11869     Diag(NameLoc,
11870          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11871       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11872     T = Context.getObjCObjectPointerType(T);
11873     New->setType(T);
11874   }
11875 
11876   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11877   // duration shall not be qualified by an address-space qualifier."
11878   // Since all parameters have automatic store duration, they can not have
11879   // an address space.
11880   if (T.getAddressSpace() != 0) {
11881     // OpenCL allows function arguments declared to be an array of a type
11882     // to be qualified with an address space.
11883     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11884       Diag(NameLoc, diag::err_arg_with_address_space);
11885       New->setInvalidDecl();
11886     }
11887   }
11888 
11889   return New;
11890 }
11891 
11892 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11893                                            SourceLocation LocAfterDecls) {
11894   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11895 
11896   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11897   // for a K&R function.
11898   if (!FTI.hasPrototype) {
11899     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11900       --i;
11901       if (FTI.Params[i].Param == nullptr) {
11902         SmallString<256> Code;
11903         llvm::raw_svector_ostream(Code)
11904             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11905         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11906             << FTI.Params[i].Ident
11907             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11908 
11909         // Implicitly declare the argument as type 'int' for lack of a better
11910         // type.
11911         AttributeFactory attrs;
11912         DeclSpec DS(attrs);
11913         const char* PrevSpec; // unused
11914         unsigned DiagID; // unused
11915         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11916                            DiagID, Context.getPrintingPolicy());
11917         // Use the identifier location for the type source range.
11918         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11919         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11920         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11921         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11922         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11923       }
11924     }
11925   }
11926 }
11927 
11928 Decl *
11929 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11930                               MultiTemplateParamsArg TemplateParameterLists,
11931                               SkipBodyInfo *SkipBody) {
11932   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11933   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11934   Scope *ParentScope = FnBodyScope->getParent();
11935 
11936   D.setFunctionDefinitionKind(FDK_Definition);
11937   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11938   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11939 }
11940 
11941 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11942   Consumer.HandleInlineFunctionDefinition(D);
11943 }
11944 
11945 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11946                              const FunctionDecl*& PossibleZeroParamPrototype) {
11947   // Don't warn about invalid declarations.
11948   if (FD->isInvalidDecl())
11949     return false;
11950 
11951   // Or declarations that aren't global.
11952   if (!FD->isGlobal())
11953     return false;
11954 
11955   // Don't warn about C++ member functions.
11956   if (isa<CXXMethodDecl>(FD))
11957     return false;
11958 
11959   // Don't warn about 'main'.
11960   if (FD->isMain())
11961     return false;
11962 
11963   // Don't warn about inline functions.
11964   if (FD->isInlined())
11965     return false;
11966 
11967   // Don't warn about function templates.
11968   if (FD->getDescribedFunctionTemplate())
11969     return false;
11970 
11971   // Don't warn about function template specializations.
11972   if (FD->isFunctionTemplateSpecialization())
11973     return false;
11974 
11975   // Don't warn for OpenCL kernels.
11976   if (FD->hasAttr<OpenCLKernelAttr>())
11977     return false;
11978 
11979   // Don't warn on explicitly deleted functions.
11980   if (FD->isDeleted())
11981     return false;
11982 
11983   bool MissingPrototype = true;
11984   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11985        Prev; Prev = Prev->getPreviousDecl()) {
11986     // Ignore any declarations that occur in function or method
11987     // scope, because they aren't visible from the header.
11988     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11989       continue;
11990 
11991     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11992     if (FD->getNumParams() == 0)
11993       PossibleZeroParamPrototype = Prev;
11994     break;
11995   }
11996 
11997   return MissingPrototype;
11998 }
11999 
12000 void
12001 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12002                                    const FunctionDecl *EffectiveDefinition,
12003                                    SkipBodyInfo *SkipBody) {
12004   const FunctionDecl *Definition = EffectiveDefinition;
12005   if (!Definition)
12006     if (!FD->isDefined(Definition))
12007       return;
12008 
12009   if (canRedefineFunction(Definition, getLangOpts()))
12010     return;
12011 
12012   // Don't emit an error when this is redefinition of a typo-corrected
12013   // definition.
12014   if (TypoCorrectedFunctionDefinitions.count(Definition))
12015     return;
12016 
12017   // If we don't have a visible definition of the function, and it's inline or
12018   // a template, skip the new definition.
12019   if (SkipBody && !hasVisibleDefinition(Definition) &&
12020       (Definition->getFormalLinkage() == InternalLinkage ||
12021        Definition->isInlined() ||
12022        Definition->getDescribedFunctionTemplate() ||
12023        Definition->getNumTemplateParameterLists())) {
12024     SkipBody->ShouldSkip = true;
12025     if (auto *TD = Definition->getDescribedFunctionTemplate())
12026       makeMergedDefinitionVisible(TD);
12027     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12028     return;
12029   }
12030 
12031   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12032       Definition->getStorageClass() == SC_Extern)
12033     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12034         << FD->getDeclName() << getLangOpts().CPlusPlus;
12035   else
12036     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12037 
12038   Diag(Definition->getLocation(), diag::note_previous_definition);
12039   FD->setInvalidDecl();
12040 }
12041 
12042 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12043                                    Sema &S) {
12044   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12045 
12046   LambdaScopeInfo *LSI = S.PushLambdaScope();
12047   LSI->CallOperator = CallOperator;
12048   LSI->Lambda = LambdaClass;
12049   LSI->ReturnType = CallOperator->getReturnType();
12050   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12051 
12052   if (LCD == LCD_None)
12053     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12054   else if (LCD == LCD_ByCopy)
12055     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12056   else if (LCD == LCD_ByRef)
12057     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12058   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12059 
12060   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12061   LSI->Mutable = !CallOperator->isConst();
12062 
12063   // Add the captures to the LSI so they can be noted as already
12064   // captured within tryCaptureVar.
12065   auto I = LambdaClass->field_begin();
12066   for (const auto &C : LambdaClass->captures()) {
12067     if (C.capturesVariable()) {
12068       VarDecl *VD = C.getCapturedVar();
12069       if (VD->isInitCapture())
12070         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12071       QualType CaptureType = VD->getType();
12072       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12073       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12074           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12075           /*EllipsisLoc*/C.isPackExpansion()
12076                          ? C.getEllipsisLoc() : SourceLocation(),
12077           CaptureType, /*Expr*/ nullptr);
12078 
12079     } else if (C.capturesThis()) {
12080       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12081                               /*Expr*/ nullptr,
12082                               C.getCaptureKind() == LCK_StarThis);
12083     } else {
12084       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12085     }
12086     ++I;
12087   }
12088 }
12089 
12090 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12091                                     SkipBodyInfo *SkipBody) {
12092   if (!D)
12093     return D;
12094   FunctionDecl *FD = nullptr;
12095 
12096   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12097     FD = FunTmpl->getTemplatedDecl();
12098   else
12099     FD = cast<FunctionDecl>(D);
12100 
12101   // Check for defining attributes before the check for redefinition.
12102   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12103     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12104     FD->dropAttr<AliasAttr>();
12105     FD->setInvalidDecl();
12106   }
12107   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12108     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12109     FD->dropAttr<IFuncAttr>();
12110     FD->setInvalidDecl();
12111   }
12112 
12113   // See if this is a redefinition. If 'will have body' is already set, then
12114   // these checks were already performed when it was set.
12115   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12116     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12117 
12118     // If we're skipping the body, we're done. Don't enter the scope.
12119     if (SkipBody && SkipBody->ShouldSkip)
12120       return D;
12121   }
12122 
12123   // Mark this function as "will have a body eventually".  This lets users to
12124   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12125   // this function.
12126   FD->setWillHaveBody();
12127 
12128   // If we are instantiating a generic lambda call operator, push
12129   // a LambdaScopeInfo onto the function stack.  But use the information
12130   // that's already been calculated (ActOnLambdaExpr) to prime the current
12131   // LambdaScopeInfo.
12132   // When the template operator is being specialized, the LambdaScopeInfo,
12133   // has to be properly restored so that tryCaptureVariable doesn't try
12134   // and capture any new variables. In addition when calculating potential
12135   // captures during transformation of nested lambdas, it is necessary to
12136   // have the LSI properly restored.
12137   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12138     assert(inTemplateInstantiation() &&
12139            "There should be an active template instantiation on the stack "
12140            "when instantiating a generic lambda!");
12141     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12142   } else {
12143     // Enter a new function scope
12144     PushFunctionScope();
12145   }
12146 
12147   // Builtin functions cannot be defined.
12148   if (unsigned BuiltinID = FD->getBuiltinID()) {
12149     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12150         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12151       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12152       FD->setInvalidDecl();
12153     }
12154   }
12155 
12156   // The return type of a function definition must be complete
12157   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12158   QualType ResultType = FD->getReturnType();
12159   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12160       !FD->isInvalidDecl() &&
12161       RequireCompleteType(FD->getLocation(), ResultType,
12162                           diag::err_func_def_incomplete_result))
12163     FD->setInvalidDecl();
12164 
12165   if (FnBodyScope)
12166     PushDeclContext(FnBodyScope, FD);
12167 
12168   // Check the validity of our function parameters
12169   CheckParmsForFunctionDef(FD->parameters(),
12170                            /*CheckParameterNames=*/true);
12171 
12172   // Add non-parameter declarations already in the function to the current
12173   // scope.
12174   if (FnBodyScope) {
12175     for (Decl *NPD : FD->decls()) {
12176       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12177       if (!NonParmDecl)
12178         continue;
12179       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12180              "parameters should not be in newly created FD yet");
12181 
12182       // If the decl has a name, make it accessible in the current scope.
12183       if (NonParmDecl->getDeclName())
12184         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12185 
12186       // Similarly, dive into enums and fish their constants out, making them
12187       // accessible in this scope.
12188       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12189         for (auto *EI : ED->enumerators())
12190           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12191       }
12192     }
12193   }
12194 
12195   // Introduce our parameters into the function scope
12196   for (auto Param : FD->parameters()) {
12197     Param->setOwningFunction(FD);
12198 
12199     // If this has an identifier, add it to the scope stack.
12200     if (Param->getIdentifier() && FnBodyScope) {
12201       CheckShadow(FnBodyScope, Param);
12202 
12203       PushOnScopeChains(Param, FnBodyScope);
12204     }
12205   }
12206 
12207   // Ensure that the function's exception specification is instantiated.
12208   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12209     ResolveExceptionSpec(D->getLocation(), FPT);
12210 
12211   // dllimport cannot be applied to non-inline function definitions.
12212   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12213       !FD->isTemplateInstantiation()) {
12214     assert(!FD->hasAttr<DLLExportAttr>());
12215     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12216     FD->setInvalidDecl();
12217     return D;
12218   }
12219   // We want to attach documentation to original Decl (which might be
12220   // a function template).
12221   ActOnDocumentableDecl(D);
12222   if (getCurLexicalContext()->isObjCContainer() &&
12223       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12224       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12225     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12226 
12227   return D;
12228 }
12229 
12230 /// \brief Given the set of return statements within a function body,
12231 /// compute the variables that are subject to the named return value
12232 /// optimization.
12233 ///
12234 /// Each of the variables that is subject to the named return value
12235 /// optimization will be marked as NRVO variables in the AST, and any
12236 /// return statement that has a marked NRVO variable as its NRVO candidate can
12237 /// use the named return value optimization.
12238 ///
12239 /// This function applies a very simplistic algorithm for NRVO: if every return
12240 /// statement in the scope of a variable has the same NRVO candidate, that
12241 /// candidate is an NRVO variable.
12242 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12243   ReturnStmt **Returns = Scope->Returns.data();
12244 
12245   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12246     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12247       if (!NRVOCandidate->isNRVOVariable())
12248         Returns[I]->setNRVOCandidate(nullptr);
12249     }
12250   }
12251 }
12252 
12253 bool Sema::canDelayFunctionBody(const Declarator &D) {
12254   // We can't delay parsing the body of a constexpr function template (yet).
12255   if (D.getDeclSpec().isConstexprSpecified())
12256     return false;
12257 
12258   // We can't delay parsing the body of a function template with a deduced
12259   // return type (yet).
12260   if (D.getDeclSpec().hasAutoTypeSpec()) {
12261     // If the placeholder introduces a non-deduced trailing return type,
12262     // we can still delay parsing it.
12263     if (D.getNumTypeObjects()) {
12264       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12265       if (Outer.Kind == DeclaratorChunk::Function &&
12266           Outer.Fun.hasTrailingReturnType()) {
12267         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12268         return Ty.isNull() || !Ty->isUndeducedType();
12269       }
12270     }
12271     return false;
12272   }
12273 
12274   return true;
12275 }
12276 
12277 bool Sema::canSkipFunctionBody(Decl *D) {
12278   // We cannot skip the body of a function (or function template) which is
12279   // constexpr, since we may need to evaluate its body in order to parse the
12280   // rest of the file.
12281   // We cannot skip the body of a function with an undeduced return type,
12282   // because any callers of that function need to know the type.
12283   if (const FunctionDecl *FD = D->getAsFunction())
12284     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12285       return false;
12286   return Consumer.shouldSkipFunctionBody(D);
12287 }
12288 
12289 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12290   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12291     FD->setHasSkippedBody();
12292   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12293     MD->setHasSkippedBody();
12294   return Decl;
12295 }
12296 
12297 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12298   return ActOnFinishFunctionBody(D, BodyArg, false);
12299 }
12300 
12301 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12302                                     bool IsInstantiation) {
12303   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12304 
12305   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12306   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12307 
12308   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12309     CheckCompletedCoroutineBody(FD, Body);
12310 
12311   if (FD) {
12312     FD->setBody(Body);
12313     FD->setWillHaveBody(false);
12314 
12315     if (getLangOpts().CPlusPlus14) {
12316       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12317           FD->getReturnType()->isUndeducedType()) {
12318         // If the function has a deduced result type but contains no 'return'
12319         // statements, the result type as written must be exactly 'auto', and
12320         // the deduced result type is 'void'.
12321         if (!FD->getReturnType()->getAs<AutoType>()) {
12322           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12323               << FD->getReturnType();
12324           FD->setInvalidDecl();
12325         } else {
12326           // Substitute 'void' for the 'auto' in the type.
12327           TypeLoc ResultType = getReturnTypeLoc(FD);
12328           Context.adjustDeducedFunctionResultType(
12329               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12330         }
12331       }
12332     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12333       // In C++11, we don't use 'auto' deduction rules for lambda call
12334       // operators because we don't support return type deduction.
12335       auto *LSI = getCurLambda();
12336       if (LSI->HasImplicitReturnType) {
12337         deduceClosureReturnType(*LSI);
12338 
12339         // C++11 [expr.prim.lambda]p4:
12340         //   [...] if there are no return statements in the compound-statement
12341         //   [the deduced type is] the type void
12342         QualType RetType =
12343             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12344 
12345         // Update the return type to the deduced type.
12346         const FunctionProtoType *Proto =
12347             FD->getType()->getAs<FunctionProtoType>();
12348         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12349                                             Proto->getExtProtoInfo()));
12350       }
12351     }
12352 
12353     // If the function implicitly returns zero (like 'main') or is naked,
12354     // don't complain about missing return statements.
12355     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12356       WP.disableCheckFallThrough();
12357 
12358     // MSVC permits the use of pure specifier (=0) on function definition,
12359     // defined at class scope, warn about this non-standard construct.
12360     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12361       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12362 
12363     if (!FD->isInvalidDecl()) {
12364       // Don't diagnose unused parameters of defaulted or deleted functions.
12365       if (!FD->isDeleted() && !FD->isDefaulted())
12366         DiagnoseUnusedParameters(FD->parameters());
12367       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12368                                              FD->getReturnType(), FD);
12369 
12370       // If this is a structor, we need a vtable.
12371       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12372         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12373       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12374         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12375 
12376       // Try to apply the named return value optimization. We have to check
12377       // if we can do this here because lambdas keep return statements around
12378       // to deduce an implicit return type.
12379       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12380           !FD->isDependentContext())
12381         computeNRVO(Body, getCurFunction());
12382     }
12383 
12384     // GNU warning -Wmissing-prototypes:
12385     //   Warn if a global function is defined without a previous
12386     //   prototype declaration. This warning is issued even if the
12387     //   definition itself provides a prototype. The aim is to detect
12388     //   global functions that fail to be declared in header files.
12389     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12390     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12391       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12392 
12393       if (PossibleZeroParamPrototype) {
12394         // We found a declaration that is not a prototype,
12395         // but that could be a zero-parameter prototype
12396         if (TypeSourceInfo *TI =
12397                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12398           TypeLoc TL = TI->getTypeLoc();
12399           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12400             Diag(PossibleZeroParamPrototype->getLocation(),
12401                  diag::note_declaration_not_a_prototype)
12402                 << PossibleZeroParamPrototype
12403                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12404         }
12405       }
12406 
12407       // GNU warning -Wstrict-prototypes
12408       //   Warn if K&R function is defined without a previous declaration.
12409       //   This warning is issued only if the definition itself does not provide
12410       //   a prototype. Only K&R definitions do not provide a prototype.
12411       //   An empty list in a function declarator that is part of a definition
12412       //   of that function specifies that the function has no parameters
12413       //   (C99 6.7.5.3p14)
12414       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12415           !LangOpts.CPlusPlus) {
12416         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12417         TypeLoc TL = TI->getTypeLoc();
12418         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12419         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12420       }
12421     }
12422 
12423     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12424       const CXXMethodDecl *KeyFunction;
12425       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12426           MD->isVirtual() &&
12427           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12428           MD == KeyFunction->getCanonicalDecl()) {
12429         // Update the key-function state if necessary for this ABI.
12430         if (FD->isInlined() &&
12431             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12432           Context.setNonKeyFunction(MD);
12433 
12434           // If the newly-chosen key function is already defined, then we
12435           // need to mark the vtable as used retroactively.
12436           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12437           const FunctionDecl *Definition;
12438           if (KeyFunction && KeyFunction->isDefined(Definition))
12439             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12440         } else {
12441           // We just defined they key function; mark the vtable as used.
12442           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12443         }
12444       }
12445     }
12446 
12447     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12448            "Function parsing confused");
12449   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12450     assert(MD == getCurMethodDecl() && "Method parsing confused");
12451     MD->setBody(Body);
12452     if (!MD->isInvalidDecl()) {
12453       DiagnoseUnusedParameters(MD->parameters());
12454       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12455                                              MD->getReturnType(), MD);
12456 
12457       if (Body)
12458         computeNRVO(Body, getCurFunction());
12459     }
12460     if (getCurFunction()->ObjCShouldCallSuper) {
12461       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12462         << MD->getSelector().getAsString();
12463       getCurFunction()->ObjCShouldCallSuper = false;
12464     }
12465     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12466       const ObjCMethodDecl *InitMethod = nullptr;
12467       bool isDesignated =
12468           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12469       assert(isDesignated && InitMethod);
12470       (void)isDesignated;
12471 
12472       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12473         auto IFace = MD->getClassInterface();
12474         if (!IFace)
12475           return false;
12476         auto SuperD = IFace->getSuperClass();
12477         if (!SuperD)
12478           return false;
12479         return SuperD->getIdentifier() ==
12480             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12481       };
12482       // Don't issue this warning for unavailable inits or direct subclasses
12483       // of NSObject.
12484       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12485         Diag(MD->getLocation(),
12486              diag::warn_objc_designated_init_missing_super_call);
12487         Diag(InitMethod->getLocation(),
12488              diag::note_objc_designated_init_marked_here);
12489       }
12490       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12491     }
12492     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12493       // Don't issue this warning for unavaialable inits.
12494       if (!MD->isUnavailable())
12495         Diag(MD->getLocation(),
12496              diag::warn_objc_secondary_init_missing_init_call);
12497       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12498     }
12499   } else {
12500     return nullptr;
12501   }
12502 
12503   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12504     DiagnoseUnguardedAvailabilityViolations(dcl);
12505 
12506   assert(!getCurFunction()->ObjCShouldCallSuper &&
12507          "This should only be set for ObjC methods, which should have been "
12508          "handled in the block above.");
12509 
12510   // Verify and clean out per-function state.
12511   if (Body && (!FD || !FD->isDefaulted())) {
12512     // C++ constructors that have function-try-blocks can't have return
12513     // statements in the handlers of that block. (C++ [except.handle]p14)
12514     // Verify this.
12515     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12516       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12517 
12518     // Verify that gotos and switch cases don't jump into scopes illegally.
12519     if (getCurFunction()->NeedsScopeChecking() &&
12520         !PP.isCodeCompletionEnabled())
12521       DiagnoseInvalidJumps(Body);
12522 
12523     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12524       if (!Destructor->getParent()->isDependentType())
12525         CheckDestructor(Destructor);
12526 
12527       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12528                                              Destructor->getParent());
12529     }
12530 
12531     // If any errors have occurred, clear out any temporaries that may have
12532     // been leftover. This ensures that these temporaries won't be picked up for
12533     // deletion in some later function.
12534     if (getDiagnostics().hasErrorOccurred() ||
12535         getDiagnostics().getSuppressAllDiagnostics()) {
12536       DiscardCleanupsInEvaluationContext();
12537     }
12538     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12539         !isa<FunctionTemplateDecl>(dcl)) {
12540       // Since the body is valid, issue any analysis-based warnings that are
12541       // enabled.
12542       ActivePolicy = &WP;
12543     }
12544 
12545     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12546         (!CheckConstexprFunctionDecl(FD) ||
12547          !CheckConstexprFunctionBody(FD, Body)))
12548       FD->setInvalidDecl();
12549 
12550     if (FD && FD->hasAttr<NakedAttr>()) {
12551       for (const Stmt *S : Body->children()) {
12552         // Allow local register variables without initializer as they don't
12553         // require prologue.
12554         bool RegisterVariables = false;
12555         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12556           for (const auto *Decl : DS->decls()) {
12557             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12558               RegisterVariables =
12559                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12560               if (!RegisterVariables)
12561                 break;
12562             }
12563           }
12564         }
12565         if (RegisterVariables)
12566           continue;
12567         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12568           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12569           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12570           FD->setInvalidDecl();
12571           break;
12572         }
12573       }
12574     }
12575 
12576     assert(ExprCleanupObjects.size() ==
12577                ExprEvalContexts.back().NumCleanupObjects &&
12578            "Leftover temporaries in function");
12579     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12580     assert(MaybeODRUseExprs.empty() &&
12581            "Leftover expressions for odr-use checking");
12582   }
12583 
12584   if (!IsInstantiation)
12585     PopDeclContext();
12586 
12587   PopFunctionScopeInfo(ActivePolicy, dcl);
12588   // If any errors have occurred, clear out any temporaries that may have
12589   // been leftover. This ensures that these temporaries won't be picked up for
12590   // deletion in some later function.
12591   if (getDiagnostics().hasErrorOccurred()) {
12592     DiscardCleanupsInEvaluationContext();
12593   }
12594 
12595   return dcl;
12596 }
12597 
12598 /// When we finish delayed parsing of an attribute, we must attach it to the
12599 /// relevant Decl.
12600 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12601                                        ParsedAttributes &Attrs) {
12602   // Always attach attributes to the underlying decl.
12603   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12604     D = TD->getTemplatedDecl();
12605   ProcessDeclAttributeList(S, D, Attrs.getList());
12606 
12607   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12608     if (Method->isStatic())
12609       checkThisInStaticMemberFunctionAttributes(Method);
12610 }
12611 
12612 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12613 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12614 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12615                                           IdentifierInfo &II, Scope *S) {
12616   Scope *BlockScope = S;
12617   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12618     BlockScope = BlockScope->getParent();
12619 
12620   // Before we produce a declaration for an implicitly defined
12621   // function, see whether there was a locally-scoped declaration of
12622   // this name as a function or variable. If so, use that
12623   // (non-visible) declaration, and complain about it.
12624   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12625   if (ExternCPrev) {
12626     // We still need to inject the function into the enclosing block scope so
12627     // that later (non-call) uses can see it.
12628     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12629 
12630     // C89 footnote 38:
12631     //   If in fact it is not defined as having type "function returning int",
12632     //   the behavior is undefined.
12633     if (!isa<FunctionDecl>(ExternCPrev) ||
12634         !Context.typesAreCompatible(
12635             cast<FunctionDecl>(ExternCPrev)->getType(),
12636             Context.getFunctionNoProtoType(Context.IntTy))) {
12637       Diag(Loc, diag::ext_use_out_of_scope_declaration)
12638           << ExternCPrev << !getLangOpts().C99;
12639       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12640       return ExternCPrev;
12641     }
12642   }
12643 
12644   // Extension in C99.  Legal in C90, but warn about it.
12645   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12646   unsigned diag_id;
12647   if (II.getName().startswith("__builtin_"))
12648     diag_id = diag::warn_builtin_unknown;
12649   else if (getLangOpts().C99 || getLangOpts().OpenCL)
12650     diag_id = diag::ext_implicit_function_decl;
12651   else
12652     diag_id = diag::warn_implicit_function_decl;
12653   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
12654 
12655   // If we found a prior declaration of this function, don't bother building
12656   // another one. We've already pushed that one into scope, so there's nothing
12657   // more to do.
12658   if (ExternCPrev)
12659     return ExternCPrev;
12660 
12661   // Because typo correction is expensive, only do it if the implicit
12662   // function declaration is going to be treated as an error.
12663   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12664     TypoCorrection Corrected;
12665     if (S &&
12666         (Corrected = CorrectTypo(
12667              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12668              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12669       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12670                    /*ErrorRecovery*/false);
12671   }
12672 
12673   // Set a Declarator for the implicit definition: int foo();
12674   const char *Dummy;
12675   AttributeFactory attrFactory;
12676   DeclSpec DS(attrFactory);
12677   unsigned DiagID;
12678   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12679                                   Context.getPrintingPolicy());
12680   (void)Error; // Silence warning.
12681   assert(!Error && "Error setting up implicit decl!");
12682   SourceLocation NoLoc;
12683   Declarator D(DS, Declarator::BlockContext);
12684   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12685                                              /*IsAmbiguous=*/false,
12686                                              /*LParenLoc=*/NoLoc,
12687                                              /*Params=*/nullptr,
12688                                              /*NumParams=*/0,
12689                                              /*EllipsisLoc=*/NoLoc,
12690                                              /*RParenLoc=*/NoLoc,
12691                                              /*TypeQuals=*/0,
12692                                              /*RefQualifierIsLvalueRef=*/true,
12693                                              /*RefQualifierLoc=*/NoLoc,
12694                                              /*ConstQualifierLoc=*/NoLoc,
12695                                              /*VolatileQualifierLoc=*/NoLoc,
12696                                              /*RestrictQualifierLoc=*/NoLoc,
12697                                              /*MutableLoc=*/NoLoc,
12698                                              EST_None,
12699                                              /*ESpecRange=*/SourceRange(),
12700                                              /*Exceptions=*/nullptr,
12701                                              /*ExceptionRanges=*/nullptr,
12702                                              /*NumExceptions=*/0,
12703                                              /*NoexceptExpr=*/nullptr,
12704                                              /*ExceptionSpecTokens=*/nullptr,
12705                                              /*DeclsInPrototype=*/None,
12706                                              Loc, Loc, D),
12707                 DS.getAttributes(),
12708                 SourceLocation());
12709   D.SetIdentifier(&II, Loc);
12710 
12711   // Insert this function into the enclosing block scope.
12712   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
12713   FD->setImplicit();
12714 
12715   AddKnownFunctionAttributes(FD);
12716 
12717   return FD;
12718 }
12719 
12720 /// \brief Adds any function attributes that we know a priori based on
12721 /// the declaration of this function.
12722 ///
12723 /// These attributes can apply both to implicitly-declared builtins
12724 /// (like __builtin___printf_chk) or to library-declared functions
12725 /// like NSLog or printf.
12726 ///
12727 /// We need to check for duplicate attributes both here and where user-written
12728 /// attributes are applied to declarations.
12729 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12730   if (FD->isInvalidDecl())
12731     return;
12732 
12733   // If this is a built-in function, map its builtin attributes to
12734   // actual attributes.
12735   if (unsigned BuiltinID = FD->getBuiltinID()) {
12736     // Handle printf-formatting attributes.
12737     unsigned FormatIdx;
12738     bool HasVAListArg;
12739     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12740       if (!FD->hasAttr<FormatAttr>()) {
12741         const char *fmt = "printf";
12742         unsigned int NumParams = FD->getNumParams();
12743         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12744             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12745           fmt = "NSString";
12746         FD->addAttr(FormatAttr::CreateImplicit(Context,
12747                                                &Context.Idents.get(fmt),
12748                                                FormatIdx+1,
12749                                                HasVAListArg ? 0 : FormatIdx+2,
12750                                                FD->getLocation()));
12751       }
12752     }
12753     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12754                                              HasVAListArg)) {
12755      if (!FD->hasAttr<FormatAttr>())
12756        FD->addAttr(FormatAttr::CreateImplicit(Context,
12757                                               &Context.Idents.get("scanf"),
12758                                               FormatIdx+1,
12759                                               HasVAListArg ? 0 : FormatIdx+2,
12760                                               FD->getLocation()));
12761     }
12762 
12763     // Mark const if we don't care about errno and that is the only
12764     // thing preventing the function from being const. This allows
12765     // IRgen to use LLVM intrinsics for such functions.
12766     if (!getLangOpts().MathErrno &&
12767         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12768       if (!FD->hasAttr<ConstAttr>())
12769         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12770     }
12771 
12772     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12773         !FD->hasAttr<ReturnsTwiceAttr>())
12774       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12775                                          FD->getLocation()));
12776     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12777       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12778     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12779       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12780     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12781       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12782     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12783         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12784       // Add the appropriate attribute, depending on the CUDA compilation mode
12785       // and which target the builtin belongs to. For example, during host
12786       // compilation, aux builtins are __device__, while the rest are __host__.
12787       if (getLangOpts().CUDAIsDevice !=
12788           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12789         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12790       else
12791         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12792     }
12793   }
12794 
12795   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12796   // throw, add an implicit nothrow attribute to any extern "C" function we come
12797   // across.
12798   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12799       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12800     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12801     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12802       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12803   }
12804 
12805   IdentifierInfo *Name = FD->getIdentifier();
12806   if (!Name)
12807     return;
12808   if ((!getLangOpts().CPlusPlus &&
12809        FD->getDeclContext()->isTranslationUnit()) ||
12810       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12811        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12812        LinkageSpecDecl::lang_c)) {
12813     // Okay: this could be a libc/libm/Objective-C function we know
12814     // about.
12815   } else
12816     return;
12817 
12818   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12819     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12820     // target-specific builtins, perhaps?
12821     if (!FD->hasAttr<FormatAttr>())
12822       FD->addAttr(FormatAttr::CreateImplicit(Context,
12823                                              &Context.Idents.get("printf"), 2,
12824                                              Name->isStr("vasprintf") ? 0 : 3,
12825                                              FD->getLocation()));
12826   }
12827 
12828   if (Name->isStr("__CFStringMakeConstantString")) {
12829     // We already have a __builtin___CFStringMakeConstantString,
12830     // but builds that use -fno-constant-cfstrings don't go through that.
12831     if (!FD->hasAttr<FormatArgAttr>())
12832       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12833                                                 FD->getLocation()));
12834   }
12835 }
12836 
12837 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12838                                     TypeSourceInfo *TInfo) {
12839   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12840   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12841 
12842   if (!TInfo) {
12843     assert(D.isInvalidType() && "no declarator info for valid type");
12844     TInfo = Context.getTrivialTypeSourceInfo(T);
12845   }
12846 
12847   // Scope manipulation handled by caller.
12848   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12849                                            D.getLocStart(),
12850                                            D.getIdentifierLoc(),
12851                                            D.getIdentifier(),
12852                                            TInfo);
12853 
12854   // Bail out immediately if we have an invalid declaration.
12855   if (D.isInvalidType()) {
12856     NewTD->setInvalidDecl();
12857     return NewTD;
12858   }
12859 
12860   if (D.getDeclSpec().isModulePrivateSpecified()) {
12861     if (CurContext->isFunctionOrMethod())
12862       Diag(NewTD->getLocation(), diag::err_module_private_local)
12863         << 2 << NewTD->getDeclName()
12864         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12865         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12866     else
12867       NewTD->setModulePrivate();
12868   }
12869 
12870   // C++ [dcl.typedef]p8:
12871   //   If the typedef declaration defines an unnamed class (or
12872   //   enum), the first typedef-name declared by the declaration
12873   //   to be that class type (or enum type) is used to denote the
12874   //   class type (or enum type) for linkage purposes only.
12875   // We need to check whether the type was declared in the declaration.
12876   switch (D.getDeclSpec().getTypeSpecType()) {
12877   case TST_enum:
12878   case TST_struct:
12879   case TST_interface:
12880   case TST_union:
12881   case TST_class: {
12882     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12883     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12884     break;
12885   }
12886 
12887   default:
12888     break;
12889   }
12890 
12891   return NewTD;
12892 }
12893 
12894 /// \brief Check that this is a valid underlying type for an enum declaration.
12895 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12896   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12897   QualType T = TI->getType();
12898 
12899   if (T->isDependentType())
12900     return false;
12901 
12902   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12903     if (BT->isInteger())
12904       return false;
12905 
12906   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12907   return true;
12908 }
12909 
12910 /// Check whether this is a valid redeclaration of a previous enumeration.
12911 /// \return true if the redeclaration was invalid.
12912 bool Sema::CheckEnumRedeclaration(
12913     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12914     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12915   bool IsFixed = !EnumUnderlyingTy.isNull();
12916 
12917   if (IsScoped != Prev->isScoped()) {
12918     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12919       << Prev->isScoped();
12920     Diag(Prev->getLocation(), diag::note_previous_declaration);
12921     return true;
12922   }
12923 
12924   if (IsFixed && Prev->isFixed()) {
12925     if (!EnumUnderlyingTy->isDependentType() &&
12926         !Prev->getIntegerType()->isDependentType() &&
12927         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12928                                         Prev->getIntegerType())) {
12929       // TODO: Highlight the underlying type of the redeclaration.
12930       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12931         << EnumUnderlyingTy << Prev->getIntegerType();
12932       Diag(Prev->getLocation(), diag::note_previous_declaration)
12933           << Prev->getIntegerTypeRange();
12934       return true;
12935     }
12936   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12937     ;
12938   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12939     ;
12940   } else if (IsFixed != Prev->isFixed()) {
12941     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12942       << Prev->isFixed();
12943     Diag(Prev->getLocation(), diag::note_previous_declaration);
12944     return true;
12945   }
12946 
12947   return false;
12948 }
12949 
12950 /// \brief Get diagnostic %select index for tag kind for
12951 /// redeclaration diagnostic message.
12952 /// WARNING: Indexes apply to particular diagnostics only!
12953 ///
12954 /// \returns diagnostic %select index.
12955 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12956   switch (Tag) {
12957   case TTK_Struct: return 0;
12958   case TTK_Interface: return 1;
12959   case TTK_Class:  return 2;
12960   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12961   }
12962 }
12963 
12964 /// \brief Determine if tag kind is a class-key compatible with
12965 /// class for redeclaration (class, struct, or __interface).
12966 ///
12967 /// \returns true iff the tag kind is compatible.
12968 static bool isClassCompatTagKind(TagTypeKind Tag)
12969 {
12970   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12971 }
12972 
12973 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12974                                              TagTypeKind TTK) {
12975   if (isa<TypedefDecl>(PrevDecl))
12976     return NTK_Typedef;
12977   else if (isa<TypeAliasDecl>(PrevDecl))
12978     return NTK_TypeAlias;
12979   else if (isa<ClassTemplateDecl>(PrevDecl))
12980     return NTK_Template;
12981   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12982     return NTK_TypeAliasTemplate;
12983   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12984     return NTK_TemplateTemplateArgument;
12985   switch (TTK) {
12986   case TTK_Struct:
12987   case TTK_Interface:
12988   case TTK_Class:
12989     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12990   case TTK_Union:
12991     return NTK_NonUnion;
12992   case TTK_Enum:
12993     return NTK_NonEnum;
12994   }
12995   llvm_unreachable("invalid TTK");
12996 }
12997 
12998 /// \brief Determine whether a tag with a given kind is acceptable
12999 /// as a redeclaration of the given tag declaration.
13000 ///
13001 /// \returns true if the new tag kind is acceptable, false otherwise.
13002 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13003                                         TagTypeKind NewTag, bool isDefinition,
13004                                         SourceLocation NewTagLoc,
13005                                         const IdentifierInfo *Name) {
13006   // C++ [dcl.type.elab]p3:
13007   //   The class-key or enum keyword present in the
13008   //   elaborated-type-specifier shall agree in kind with the
13009   //   declaration to which the name in the elaborated-type-specifier
13010   //   refers. This rule also applies to the form of
13011   //   elaborated-type-specifier that declares a class-name or
13012   //   friend class since it can be construed as referring to the
13013   //   definition of the class. Thus, in any
13014   //   elaborated-type-specifier, the enum keyword shall be used to
13015   //   refer to an enumeration (7.2), the union class-key shall be
13016   //   used to refer to a union (clause 9), and either the class or
13017   //   struct class-key shall be used to refer to a class (clause 9)
13018   //   declared using the class or struct class-key.
13019   TagTypeKind OldTag = Previous->getTagKind();
13020   if (!isDefinition || !isClassCompatTagKind(NewTag))
13021     if (OldTag == NewTag)
13022       return true;
13023 
13024   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13025     // Warn about the struct/class tag mismatch.
13026     bool isTemplate = false;
13027     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13028       isTemplate = Record->getDescribedClassTemplate();
13029 
13030     if (inTemplateInstantiation()) {
13031       // In a template instantiation, do not offer fix-its for tag mismatches
13032       // since they usually mess up the template instead of fixing the problem.
13033       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13034         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13035         << getRedeclDiagFromTagKind(OldTag);
13036       return true;
13037     }
13038 
13039     if (isDefinition) {
13040       // On definitions, check previous tags and issue a fix-it for each
13041       // one that doesn't match the current tag.
13042       if (Previous->getDefinition()) {
13043         // Don't suggest fix-its for redefinitions.
13044         return true;
13045       }
13046 
13047       bool previousMismatch = false;
13048       for (auto I : Previous->redecls()) {
13049         if (I->getTagKind() != NewTag) {
13050           if (!previousMismatch) {
13051             previousMismatch = true;
13052             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13053               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13054               << getRedeclDiagFromTagKind(I->getTagKind());
13055           }
13056           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13057             << getRedeclDiagFromTagKind(NewTag)
13058             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13059                  TypeWithKeyword::getTagTypeKindName(NewTag));
13060         }
13061       }
13062       return true;
13063     }
13064 
13065     // Check for a previous definition.  If current tag and definition
13066     // are same type, do nothing.  If no definition, but disagree with
13067     // with previous tag type, give a warning, but no fix-it.
13068     const TagDecl *Redecl = Previous->getDefinition() ?
13069                             Previous->getDefinition() : Previous;
13070     if (Redecl->getTagKind() == NewTag) {
13071       return true;
13072     }
13073 
13074     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13075       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13076       << getRedeclDiagFromTagKind(OldTag);
13077     Diag(Redecl->getLocation(), diag::note_previous_use);
13078 
13079     // If there is a previous definition, suggest a fix-it.
13080     if (Previous->getDefinition()) {
13081         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13082           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13083           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13084                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13085     }
13086 
13087     return true;
13088   }
13089   return false;
13090 }
13091 
13092 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13093 /// from an outer enclosing namespace or file scope inside a friend declaration.
13094 /// This should provide the commented out code in the following snippet:
13095 ///   namespace N {
13096 ///     struct X;
13097 ///     namespace M {
13098 ///       struct Y { friend struct /*N::*/ X; };
13099 ///     }
13100 ///   }
13101 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13102                                          SourceLocation NameLoc) {
13103   // While the decl is in a namespace, do repeated lookup of that name and see
13104   // if we get the same namespace back.  If we do not, continue until
13105   // translation unit scope, at which point we have a fully qualified NNS.
13106   SmallVector<IdentifierInfo *, 4> Namespaces;
13107   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13108   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13109     // This tag should be declared in a namespace, which can only be enclosed by
13110     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13111     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13112     if (!Namespace || Namespace->isAnonymousNamespace())
13113       return FixItHint();
13114     IdentifierInfo *II = Namespace->getIdentifier();
13115     Namespaces.push_back(II);
13116     NamedDecl *Lookup = SemaRef.LookupSingleName(
13117         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13118     if (Lookup == Namespace)
13119       break;
13120   }
13121 
13122   // Once we have all the namespaces, reverse them to go outermost first, and
13123   // build an NNS.
13124   SmallString<64> Insertion;
13125   llvm::raw_svector_ostream OS(Insertion);
13126   if (DC->isTranslationUnit())
13127     OS << "::";
13128   std::reverse(Namespaces.begin(), Namespaces.end());
13129   for (auto *II : Namespaces)
13130     OS << II->getName() << "::";
13131   return FixItHint::CreateInsertion(NameLoc, Insertion);
13132 }
13133 
13134 /// \brief Determine whether a tag originally declared in context \p OldDC can
13135 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13136 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13137 /// using-declaration).
13138 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13139                                          DeclContext *NewDC) {
13140   OldDC = OldDC->getRedeclContext();
13141   NewDC = NewDC->getRedeclContext();
13142 
13143   if (OldDC->Equals(NewDC))
13144     return true;
13145 
13146   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13147   // encloses the other).
13148   if (S.getLangOpts().MSVCCompat &&
13149       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13150     return true;
13151 
13152   return false;
13153 }
13154 
13155 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13156 /// former case, Name will be non-null.  In the later case, Name will be null.
13157 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13158 /// reference/declaration/definition of a tag.
13159 ///
13160 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13161 /// trailing-type-specifier) other than one in an alias-declaration.
13162 ///
13163 /// \param SkipBody If non-null, will be set to indicate if the caller should
13164 /// skip the definition of this tag and treat it as if it were a declaration.
13165 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13166                      SourceLocation KWLoc, CXXScopeSpec &SS,
13167                      IdentifierInfo *Name, SourceLocation NameLoc,
13168                      AttributeList *Attr, AccessSpecifier AS,
13169                      SourceLocation ModulePrivateLoc,
13170                      MultiTemplateParamsArg TemplateParameterLists,
13171                      bool &OwnedDecl, bool &IsDependent,
13172                      SourceLocation ScopedEnumKWLoc,
13173                      bool ScopedEnumUsesClassTag,
13174                      TypeResult UnderlyingType,
13175                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13176                      SkipBodyInfo *SkipBody) {
13177   // If this is not a definition, it must have a name.
13178   IdentifierInfo *OrigName = Name;
13179   assert((Name != nullptr || TUK == TUK_Definition) &&
13180          "Nameless record must be a definition!");
13181   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13182 
13183   OwnedDecl = false;
13184   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13185   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13186 
13187   // FIXME: Check member specializations more carefully.
13188   bool isMemberSpecialization = false;
13189   bool Invalid = false;
13190 
13191   // We only need to do this matching if we have template parameters
13192   // or a scope specifier, which also conveniently avoids this work
13193   // for non-C++ cases.
13194   if (TemplateParameterLists.size() > 0 ||
13195       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13196     if (TemplateParameterList *TemplateParams =
13197             MatchTemplateParametersToScopeSpecifier(
13198                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13199                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13200       if (Kind == TTK_Enum) {
13201         Diag(KWLoc, diag::err_enum_template);
13202         return nullptr;
13203       }
13204 
13205       if (TemplateParams->size() > 0) {
13206         // This is a declaration or definition of a class template (which may
13207         // be a member of another template).
13208 
13209         if (Invalid)
13210           return nullptr;
13211 
13212         OwnedDecl = false;
13213         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13214                                                SS, Name, NameLoc, Attr,
13215                                                TemplateParams, AS,
13216                                                ModulePrivateLoc,
13217                                                /*FriendLoc*/SourceLocation(),
13218                                                TemplateParameterLists.size()-1,
13219                                                TemplateParameterLists.data(),
13220                                                SkipBody);
13221         return Result.get();
13222       } else {
13223         // The "template<>" header is extraneous.
13224         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13225           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13226         isMemberSpecialization = true;
13227       }
13228     }
13229   }
13230 
13231   // Figure out the underlying type if this a enum declaration. We need to do
13232   // this early, because it's needed to detect if this is an incompatible
13233   // redeclaration.
13234   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13235   bool EnumUnderlyingIsImplicit = false;
13236 
13237   if (Kind == TTK_Enum) {
13238     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13239       // No underlying type explicitly specified, or we failed to parse the
13240       // type, default to int.
13241       EnumUnderlying = Context.IntTy.getTypePtr();
13242     else if (UnderlyingType.get()) {
13243       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13244       // integral type; any cv-qualification is ignored.
13245       TypeSourceInfo *TI = nullptr;
13246       GetTypeFromParser(UnderlyingType.get(), &TI);
13247       EnumUnderlying = TI;
13248 
13249       if (CheckEnumUnderlyingType(TI))
13250         // Recover by falling back to int.
13251         EnumUnderlying = Context.IntTy.getTypePtr();
13252 
13253       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13254                                           UPPC_FixedUnderlyingType))
13255         EnumUnderlying = Context.IntTy.getTypePtr();
13256 
13257     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13258       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13259         // Microsoft enums are always of int type.
13260         EnumUnderlying = Context.IntTy.getTypePtr();
13261         EnumUnderlyingIsImplicit = true;
13262       }
13263     }
13264   }
13265 
13266   DeclContext *SearchDC = CurContext;
13267   DeclContext *DC = CurContext;
13268   bool isStdBadAlloc = false;
13269   bool isStdAlignValT = false;
13270 
13271   RedeclarationKind Redecl = ForRedeclaration;
13272   if (TUK == TUK_Friend || TUK == TUK_Reference)
13273     Redecl = NotForRedeclaration;
13274 
13275   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13276   /// implemented asks for structural equivalence checking, the returned decl
13277   /// here is passed back to the parser, allowing the tag body to be parsed.
13278   auto createTagFromNewDecl = [&]() -> TagDecl * {
13279     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13280     // If there is an identifier, use the location of the identifier as the
13281     // location of the decl, otherwise use the location of the struct/union
13282     // keyword.
13283     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13284     TagDecl *New = nullptr;
13285 
13286     if (Kind == TTK_Enum) {
13287       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13288                              ScopedEnum, ScopedEnumUsesClassTag,
13289                              !EnumUnderlying.isNull());
13290       // If this is an undefined enum, bail.
13291       if (TUK != TUK_Definition && !Invalid)
13292         return nullptr;
13293       if (EnumUnderlying) {
13294         EnumDecl *ED = cast<EnumDecl>(New);
13295         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13296           ED->setIntegerTypeSourceInfo(TI);
13297         else
13298           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13299         ED->setPromotionType(ED->getIntegerType());
13300       }
13301     } else { // struct/union
13302       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13303                                nullptr);
13304     }
13305 
13306     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13307       // Add alignment attributes if necessary; these attributes are checked
13308       // when the ASTContext lays out the structure.
13309       //
13310       // It is important for implementing the correct semantics that this
13311       // happen here (in ActOnTag). The #pragma pack stack is
13312       // maintained as a result of parser callbacks which can occur at
13313       // many points during the parsing of a struct declaration (because
13314       // the #pragma tokens are effectively skipped over during the
13315       // parsing of the struct).
13316       if (TUK == TUK_Definition) {
13317         AddAlignmentAttributesForRecord(RD);
13318         AddMsStructLayoutForRecord(RD);
13319       }
13320     }
13321     New->setLexicalDeclContext(CurContext);
13322     return New;
13323   };
13324 
13325   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13326   if (Name && SS.isNotEmpty()) {
13327     // We have a nested-name tag ('struct foo::bar').
13328 
13329     // Check for invalid 'foo::'.
13330     if (SS.isInvalid()) {
13331       Name = nullptr;
13332       goto CreateNewDecl;
13333     }
13334 
13335     // If this is a friend or a reference to a class in a dependent
13336     // context, don't try to make a decl for it.
13337     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13338       DC = computeDeclContext(SS, false);
13339       if (!DC) {
13340         IsDependent = true;
13341         return nullptr;
13342       }
13343     } else {
13344       DC = computeDeclContext(SS, true);
13345       if (!DC) {
13346         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13347           << SS.getRange();
13348         return nullptr;
13349       }
13350     }
13351 
13352     if (RequireCompleteDeclContext(SS, DC))
13353       return nullptr;
13354 
13355     SearchDC = DC;
13356     // Look-up name inside 'foo::'.
13357     LookupQualifiedName(Previous, DC);
13358 
13359     if (Previous.isAmbiguous())
13360       return nullptr;
13361 
13362     if (Previous.empty()) {
13363       // Name lookup did not find anything. However, if the
13364       // nested-name-specifier refers to the current instantiation,
13365       // and that current instantiation has any dependent base
13366       // classes, we might find something at instantiation time: treat
13367       // this as a dependent elaborated-type-specifier.
13368       // But this only makes any sense for reference-like lookups.
13369       if (Previous.wasNotFoundInCurrentInstantiation() &&
13370           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13371         IsDependent = true;
13372         return nullptr;
13373       }
13374 
13375       // A tag 'foo::bar' must already exist.
13376       Diag(NameLoc, diag::err_not_tag_in_scope)
13377         << Kind << Name << DC << SS.getRange();
13378       Name = nullptr;
13379       Invalid = true;
13380       goto CreateNewDecl;
13381     }
13382   } else if (Name) {
13383     // C++14 [class.mem]p14:
13384     //   If T is the name of a class, then each of the following shall have a
13385     //   name different from T:
13386     //    -- every member of class T that is itself a type
13387     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13388         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13389       return nullptr;
13390 
13391     // If this is a named struct, check to see if there was a previous forward
13392     // declaration or definition.
13393     // FIXME: We're looking into outer scopes here, even when we
13394     // shouldn't be. Doing so can result in ambiguities that we
13395     // shouldn't be diagnosing.
13396     LookupName(Previous, S);
13397 
13398     // When declaring or defining a tag, ignore ambiguities introduced
13399     // by types using'ed into this scope.
13400     if (Previous.isAmbiguous() &&
13401         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13402       LookupResult::Filter F = Previous.makeFilter();
13403       while (F.hasNext()) {
13404         NamedDecl *ND = F.next();
13405         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13406                 SearchDC->getRedeclContext()))
13407           F.erase();
13408       }
13409       F.done();
13410     }
13411 
13412     // C++11 [namespace.memdef]p3:
13413     //   If the name in a friend declaration is neither qualified nor
13414     //   a template-id and the declaration is a function or an
13415     //   elaborated-type-specifier, the lookup to determine whether
13416     //   the entity has been previously declared shall not consider
13417     //   any scopes outside the innermost enclosing namespace.
13418     //
13419     // MSVC doesn't implement the above rule for types, so a friend tag
13420     // declaration may be a redeclaration of a type declared in an enclosing
13421     // scope.  They do implement this rule for friend functions.
13422     //
13423     // Does it matter that this should be by scope instead of by
13424     // semantic context?
13425     if (!Previous.empty() && TUK == TUK_Friend) {
13426       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13427       LookupResult::Filter F = Previous.makeFilter();
13428       bool FriendSawTagOutsideEnclosingNamespace = false;
13429       while (F.hasNext()) {
13430         NamedDecl *ND = F.next();
13431         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13432         if (DC->isFileContext() &&
13433             !EnclosingNS->Encloses(ND->getDeclContext())) {
13434           if (getLangOpts().MSVCCompat)
13435             FriendSawTagOutsideEnclosingNamespace = true;
13436           else
13437             F.erase();
13438         }
13439       }
13440       F.done();
13441 
13442       // Diagnose this MSVC extension in the easy case where lookup would have
13443       // unambiguously found something outside the enclosing namespace.
13444       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13445         NamedDecl *ND = Previous.getFoundDecl();
13446         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13447             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13448       }
13449     }
13450 
13451     // Note:  there used to be some attempt at recovery here.
13452     if (Previous.isAmbiguous())
13453       return nullptr;
13454 
13455     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13456       // FIXME: This makes sure that we ignore the contexts associated
13457       // with C structs, unions, and enums when looking for a matching
13458       // tag declaration or definition. See the similar lookup tweak
13459       // in Sema::LookupName; is there a better way to deal with this?
13460       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13461         SearchDC = SearchDC->getParent();
13462     }
13463   }
13464 
13465   if (Previous.isSingleResult() &&
13466       Previous.getFoundDecl()->isTemplateParameter()) {
13467     // Maybe we will complain about the shadowed template parameter.
13468     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13469     // Just pretend that we didn't see the previous declaration.
13470     Previous.clear();
13471   }
13472 
13473   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13474       DC->Equals(getStdNamespace())) {
13475     if (Name->isStr("bad_alloc")) {
13476       // This is a declaration of or a reference to "std::bad_alloc".
13477       isStdBadAlloc = true;
13478 
13479       // If std::bad_alloc has been implicitly declared (but made invisible to
13480       // name lookup), fill in this implicit declaration as the previous
13481       // declaration, so that the declarations get chained appropriately.
13482       if (Previous.empty() && StdBadAlloc)
13483         Previous.addDecl(getStdBadAlloc());
13484     } else if (Name->isStr("align_val_t")) {
13485       isStdAlignValT = true;
13486       if (Previous.empty() && StdAlignValT)
13487         Previous.addDecl(getStdAlignValT());
13488     }
13489   }
13490 
13491   // If we didn't find a previous declaration, and this is a reference
13492   // (or friend reference), move to the correct scope.  In C++, we
13493   // also need to do a redeclaration lookup there, just in case
13494   // there's a shadow friend decl.
13495   if (Name && Previous.empty() &&
13496       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13497     if (Invalid) goto CreateNewDecl;
13498     assert(SS.isEmpty());
13499 
13500     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13501       // C++ [basic.scope.pdecl]p5:
13502       //   -- for an elaborated-type-specifier of the form
13503       //
13504       //          class-key identifier
13505       //
13506       //      if the elaborated-type-specifier is used in the
13507       //      decl-specifier-seq or parameter-declaration-clause of a
13508       //      function defined in namespace scope, the identifier is
13509       //      declared as a class-name in the namespace that contains
13510       //      the declaration; otherwise, except as a friend
13511       //      declaration, the identifier is declared in the smallest
13512       //      non-class, non-function-prototype scope that contains the
13513       //      declaration.
13514       //
13515       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13516       // C structs and unions.
13517       //
13518       // It is an error in C++ to declare (rather than define) an enum
13519       // type, including via an elaborated type specifier.  We'll
13520       // diagnose that later; for now, declare the enum in the same
13521       // scope as we would have picked for any other tag type.
13522       //
13523       // GNU C also supports this behavior as part of its incomplete
13524       // enum types extension, while GNU C++ does not.
13525       //
13526       // Find the context where we'll be declaring the tag.
13527       // FIXME: We would like to maintain the current DeclContext as the
13528       // lexical context,
13529       SearchDC = getTagInjectionContext(SearchDC);
13530 
13531       // Find the scope where we'll be declaring the tag.
13532       S = getTagInjectionScope(S, getLangOpts());
13533     } else {
13534       assert(TUK == TUK_Friend);
13535       // C++ [namespace.memdef]p3:
13536       //   If a friend declaration in a non-local class first declares a
13537       //   class or function, the friend class or function is a member of
13538       //   the innermost enclosing namespace.
13539       SearchDC = SearchDC->getEnclosingNamespaceContext();
13540     }
13541 
13542     // In C++, we need to do a redeclaration lookup to properly
13543     // diagnose some problems.
13544     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13545     // hidden declaration so that we don't get ambiguity errors when using a
13546     // type declared by an elaborated-type-specifier.  In C that is not correct
13547     // and we should instead merge compatible types found by lookup.
13548     if (getLangOpts().CPlusPlus) {
13549       Previous.setRedeclarationKind(ForRedeclaration);
13550       LookupQualifiedName(Previous, SearchDC);
13551     } else {
13552       Previous.setRedeclarationKind(ForRedeclaration);
13553       LookupName(Previous, S);
13554     }
13555   }
13556 
13557   // If we have a known previous declaration to use, then use it.
13558   if (Previous.empty() && SkipBody && SkipBody->Previous)
13559     Previous.addDecl(SkipBody->Previous);
13560 
13561   if (!Previous.empty()) {
13562     NamedDecl *PrevDecl = Previous.getFoundDecl();
13563     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13564 
13565     // It's okay to have a tag decl in the same scope as a typedef
13566     // which hides a tag decl in the same scope.  Finding this
13567     // insanity with a redeclaration lookup can only actually happen
13568     // in C++.
13569     //
13570     // This is also okay for elaborated-type-specifiers, which is
13571     // technically forbidden by the current standard but which is
13572     // okay according to the likely resolution of an open issue;
13573     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13574     if (getLangOpts().CPlusPlus) {
13575       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13576         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13577           TagDecl *Tag = TT->getDecl();
13578           if (Tag->getDeclName() == Name &&
13579               Tag->getDeclContext()->getRedeclContext()
13580                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13581             PrevDecl = Tag;
13582             Previous.clear();
13583             Previous.addDecl(Tag);
13584             Previous.resolveKind();
13585           }
13586         }
13587       }
13588     }
13589 
13590     // If this is a redeclaration of a using shadow declaration, it must
13591     // declare a tag in the same context. In MSVC mode, we allow a
13592     // redefinition if either context is within the other.
13593     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13594       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13595       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13596           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13597           !(OldTag && isAcceptableTagRedeclContext(
13598                           *this, OldTag->getDeclContext(), SearchDC))) {
13599         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13600         Diag(Shadow->getTargetDecl()->getLocation(),
13601              diag::note_using_decl_target);
13602         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13603             << 0;
13604         // Recover by ignoring the old declaration.
13605         Previous.clear();
13606         goto CreateNewDecl;
13607       }
13608     }
13609 
13610     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13611       // If this is a use of a previous tag, or if the tag is already declared
13612       // in the same scope (so that the definition/declaration completes or
13613       // rementions the tag), reuse the decl.
13614       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13615           isDeclInScope(DirectPrevDecl, SearchDC, S,
13616                         SS.isNotEmpty() || isMemberSpecialization)) {
13617         // Make sure that this wasn't declared as an enum and now used as a
13618         // struct or something similar.
13619         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13620                                           TUK == TUK_Definition, KWLoc,
13621                                           Name)) {
13622           bool SafeToContinue
13623             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13624                Kind != TTK_Enum);
13625           if (SafeToContinue)
13626             Diag(KWLoc, diag::err_use_with_wrong_tag)
13627               << Name
13628               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13629                                               PrevTagDecl->getKindName());
13630           else
13631             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13632           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13633 
13634           if (SafeToContinue)
13635             Kind = PrevTagDecl->getTagKind();
13636           else {
13637             // Recover by making this an anonymous redefinition.
13638             Name = nullptr;
13639             Previous.clear();
13640             Invalid = true;
13641           }
13642         }
13643 
13644         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13645           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13646 
13647           // If this is an elaborated-type-specifier for a scoped enumeration,
13648           // the 'class' keyword is not necessary and not permitted.
13649           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13650             if (ScopedEnum)
13651               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13652                 << PrevEnum->isScoped()
13653                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13654             return PrevTagDecl;
13655           }
13656 
13657           QualType EnumUnderlyingTy;
13658           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13659             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13660           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13661             EnumUnderlyingTy = QualType(T, 0);
13662 
13663           // All conflicts with previous declarations are recovered by
13664           // returning the previous declaration, unless this is a definition,
13665           // in which case we want the caller to bail out.
13666           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13667                                      ScopedEnum, EnumUnderlyingTy,
13668                                      EnumUnderlyingIsImplicit, PrevEnum))
13669             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13670         }
13671 
13672         // C++11 [class.mem]p1:
13673         //   A member shall not be declared twice in the member-specification,
13674         //   except that a nested class or member class template can be declared
13675         //   and then later defined.
13676         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13677             S->isDeclScope(PrevDecl)) {
13678           Diag(NameLoc, diag::ext_member_redeclared);
13679           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13680         }
13681 
13682         if (!Invalid) {
13683           // If this is a use, just return the declaration we found, unless
13684           // we have attributes.
13685           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13686             if (Attr) {
13687               // FIXME: Diagnose these attributes. For now, we create a new
13688               // declaration to hold them.
13689             } else if (TUK == TUK_Reference &&
13690                        (PrevTagDecl->getFriendObjectKind() ==
13691                             Decl::FOK_Undeclared ||
13692                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13693                        SS.isEmpty()) {
13694               // This declaration is a reference to an existing entity, but
13695               // has different visibility from that entity: it either makes
13696               // a friend visible or it makes a type visible in a new module.
13697               // In either case, create a new declaration. We only do this if
13698               // the declaration would have meant the same thing if no prior
13699               // declaration were found, that is, if it was found in the same
13700               // scope where we would have injected a declaration.
13701               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13702                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13703                 return PrevTagDecl;
13704               // This is in the injected scope, create a new declaration in
13705               // that scope.
13706               S = getTagInjectionScope(S, getLangOpts());
13707             } else {
13708               return PrevTagDecl;
13709             }
13710           }
13711 
13712           // Diagnose attempts to redefine a tag.
13713           if (TUK == TUK_Definition) {
13714             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13715               // If we're defining a specialization and the previous definition
13716               // is from an implicit instantiation, don't emit an error
13717               // here; we'll catch this in the general case below.
13718               bool IsExplicitSpecializationAfterInstantiation = false;
13719               if (isMemberSpecialization) {
13720                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13721                   IsExplicitSpecializationAfterInstantiation =
13722                     RD->getTemplateSpecializationKind() !=
13723                     TSK_ExplicitSpecialization;
13724                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13725                   IsExplicitSpecializationAfterInstantiation =
13726                     ED->getTemplateSpecializationKind() !=
13727                     TSK_ExplicitSpecialization;
13728               }
13729 
13730               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13731               // not keep more that one definition around (merge them). However,
13732               // ensure the decl passes the structural compatibility check in
13733               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13734               NamedDecl *Hidden = nullptr;
13735               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13736                 // There is a definition of this tag, but it is not visible. We
13737                 // explicitly make use of C++'s one definition rule here, and
13738                 // assume that this definition is identical to the hidden one
13739                 // we already have. Make the existing definition visible and
13740                 // use it in place of this one.
13741                 if (!getLangOpts().CPlusPlus) {
13742                   // Postpone making the old definition visible until after we
13743                   // complete parsing the new one and do the structural
13744                   // comparison.
13745                   SkipBody->CheckSameAsPrevious = true;
13746                   SkipBody->New = createTagFromNewDecl();
13747                   SkipBody->Previous = Hidden;
13748                 } else {
13749                   SkipBody->ShouldSkip = true;
13750                   makeMergedDefinitionVisible(Hidden);
13751                 }
13752                 return Def;
13753               } else if (!IsExplicitSpecializationAfterInstantiation) {
13754                 // A redeclaration in function prototype scope in C isn't
13755                 // visible elsewhere, so merely issue a warning.
13756                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13757                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13758                 else
13759                   Diag(NameLoc, diag::err_redefinition) << Name;
13760                 notePreviousDefinition(Def,
13761                                        NameLoc.isValid() ? NameLoc : KWLoc);
13762                 // If this is a redefinition, recover by making this
13763                 // struct be anonymous, which will make any later
13764                 // references get the previous definition.
13765                 Name = nullptr;
13766                 Previous.clear();
13767                 Invalid = true;
13768               }
13769             } else {
13770               // If the type is currently being defined, complain
13771               // about a nested redefinition.
13772               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13773               if (TD->isBeingDefined()) {
13774                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13775                 Diag(PrevTagDecl->getLocation(),
13776                      diag::note_previous_definition);
13777                 Name = nullptr;
13778                 Previous.clear();
13779                 Invalid = true;
13780               }
13781             }
13782 
13783             // Okay, this is definition of a previously declared or referenced
13784             // tag. We're going to create a new Decl for it.
13785           }
13786 
13787           // Okay, we're going to make a redeclaration.  If this is some kind
13788           // of reference, make sure we build the redeclaration in the same DC
13789           // as the original, and ignore the current access specifier.
13790           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13791             SearchDC = PrevTagDecl->getDeclContext();
13792             AS = AS_none;
13793           }
13794         }
13795         // If we get here we have (another) forward declaration or we
13796         // have a definition.  Just create a new decl.
13797 
13798       } else {
13799         // If we get here, this is a definition of a new tag type in a nested
13800         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13801         // new decl/type.  We set PrevDecl to NULL so that the entities
13802         // have distinct types.
13803         Previous.clear();
13804       }
13805       // If we get here, we're going to create a new Decl. If PrevDecl
13806       // is non-NULL, it's a definition of the tag declared by
13807       // PrevDecl. If it's NULL, we have a new definition.
13808 
13809     // Otherwise, PrevDecl is not a tag, but was found with tag
13810     // lookup.  This is only actually possible in C++, where a few
13811     // things like templates still live in the tag namespace.
13812     } else {
13813       // Use a better diagnostic if an elaborated-type-specifier
13814       // found the wrong kind of type on the first
13815       // (non-redeclaration) lookup.
13816       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13817           !Previous.isForRedeclaration()) {
13818         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13819         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13820                                                        << Kind;
13821         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13822         Invalid = true;
13823 
13824       // Otherwise, only diagnose if the declaration is in scope.
13825       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13826                                 SS.isNotEmpty() || isMemberSpecialization)) {
13827         // do nothing
13828 
13829       // Diagnose implicit declarations introduced by elaborated types.
13830       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13831         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13832         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13833         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13834         Invalid = true;
13835 
13836       // Otherwise it's a declaration.  Call out a particularly common
13837       // case here.
13838       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13839         unsigned Kind = 0;
13840         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13841         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13842           << Name << Kind << TND->getUnderlyingType();
13843         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13844         Invalid = true;
13845 
13846       // Otherwise, diagnose.
13847       } else {
13848         // The tag name clashes with something else in the target scope,
13849         // issue an error and recover by making this tag be anonymous.
13850         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13851         notePreviousDefinition(PrevDecl, NameLoc);
13852         Name = nullptr;
13853         Invalid = true;
13854       }
13855 
13856       // The existing declaration isn't relevant to us; we're in a
13857       // new scope, so clear out the previous declaration.
13858       Previous.clear();
13859     }
13860   }
13861 
13862 CreateNewDecl:
13863 
13864   TagDecl *PrevDecl = nullptr;
13865   if (Previous.isSingleResult())
13866     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13867 
13868   // If there is an identifier, use the location of the identifier as the
13869   // location of the decl, otherwise use the location of the struct/union
13870   // keyword.
13871   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13872 
13873   // Otherwise, create a new declaration. If there is a previous
13874   // declaration of the same entity, the two will be linked via
13875   // PrevDecl.
13876   TagDecl *New;
13877 
13878   bool IsForwardReference = false;
13879   if (Kind == TTK_Enum) {
13880     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13881     // enum X { A, B, C } D;    D should chain to X.
13882     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13883                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13884                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13885 
13886     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13887       StdAlignValT = cast<EnumDecl>(New);
13888 
13889     // If this is an undefined enum, warn.
13890     if (TUK != TUK_Definition && !Invalid) {
13891       TagDecl *Def;
13892       if (!EnumUnderlyingIsImplicit &&
13893           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13894           cast<EnumDecl>(New)->isFixed()) {
13895         // C++0x: 7.2p2: opaque-enum-declaration.
13896         // Conflicts are diagnosed above. Do nothing.
13897       }
13898       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13899         Diag(Loc, diag::ext_forward_ref_enum_def)
13900           << New;
13901         Diag(Def->getLocation(), diag::note_previous_definition);
13902       } else {
13903         unsigned DiagID = diag::ext_forward_ref_enum;
13904         if (getLangOpts().MSVCCompat)
13905           DiagID = diag::ext_ms_forward_ref_enum;
13906         else if (getLangOpts().CPlusPlus)
13907           DiagID = diag::err_forward_ref_enum;
13908         Diag(Loc, DiagID);
13909 
13910         // If this is a forward-declared reference to an enumeration, make a
13911         // note of it; we won't actually be introducing the declaration into
13912         // the declaration context.
13913         if (TUK == TUK_Reference)
13914           IsForwardReference = true;
13915       }
13916     }
13917 
13918     if (EnumUnderlying) {
13919       EnumDecl *ED = cast<EnumDecl>(New);
13920       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13921         ED->setIntegerTypeSourceInfo(TI);
13922       else
13923         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13924       ED->setPromotionType(ED->getIntegerType());
13925     }
13926   } else {
13927     // struct/union/class
13928 
13929     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13930     // struct X { int A; } D;    D should chain to X.
13931     if (getLangOpts().CPlusPlus) {
13932       // FIXME: Look for a way to use RecordDecl for simple structs.
13933       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13934                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13935 
13936       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13937         StdBadAlloc = cast<CXXRecordDecl>(New);
13938     } else
13939       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13940                                cast_or_null<RecordDecl>(PrevDecl));
13941   }
13942 
13943   // C++11 [dcl.type]p3:
13944   //   A type-specifier-seq shall not define a class or enumeration [...].
13945   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13946       TUK == TUK_Definition) {
13947     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13948       << Context.getTagDeclType(New);
13949     Invalid = true;
13950   }
13951 
13952   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
13953       DC->getDeclKind() == Decl::Enum) {
13954     Diag(New->getLocation(), diag::err_type_defined_in_enum)
13955       << Context.getTagDeclType(New);
13956     Invalid = true;
13957   }
13958 
13959   // Maybe add qualifier info.
13960   if (SS.isNotEmpty()) {
13961     if (SS.isSet()) {
13962       // If this is either a declaration or a definition, check the
13963       // nested-name-specifier against the current context. We don't do this
13964       // for explicit specializations, because they have similar checking
13965       // (with more specific diagnostics) in the call to
13966       // CheckMemberSpecialization, below.
13967       if (!isMemberSpecialization &&
13968           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13969           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13970         Invalid = true;
13971 
13972       New->setQualifierInfo(SS.getWithLocInContext(Context));
13973       if (TemplateParameterLists.size() > 0) {
13974         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13975       }
13976     }
13977     else
13978       Invalid = true;
13979   }
13980 
13981   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13982     // Add alignment attributes if necessary; these attributes are checked when
13983     // the ASTContext lays out the structure.
13984     //
13985     // It is important for implementing the correct semantics that this
13986     // happen here (in ActOnTag). The #pragma pack stack is
13987     // maintained as a result of parser callbacks which can occur at
13988     // many points during the parsing of a struct declaration (because
13989     // the #pragma tokens are effectively skipped over during the
13990     // parsing of the struct).
13991     if (TUK == TUK_Definition) {
13992       AddAlignmentAttributesForRecord(RD);
13993       AddMsStructLayoutForRecord(RD);
13994     }
13995   }
13996 
13997   if (ModulePrivateLoc.isValid()) {
13998     if (isMemberSpecialization)
13999       Diag(New->getLocation(), diag::err_module_private_specialization)
14000         << 2
14001         << FixItHint::CreateRemoval(ModulePrivateLoc);
14002     // __module_private__ does not apply to local classes. However, we only
14003     // diagnose this as an error when the declaration specifiers are
14004     // freestanding. Here, we just ignore the __module_private__.
14005     else if (!SearchDC->isFunctionOrMethod())
14006       New->setModulePrivate();
14007   }
14008 
14009   // If this is a specialization of a member class (of a class template),
14010   // check the specialization.
14011   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14012     Invalid = true;
14013 
14014   // If we're declaring or defining a tag in function prototype scope in C,
14015   // note that this type can only be used within the function and add it to
14016   // the list of decls to inject into the function definition scope.
14017   if ((Name || Kind == TTK_Enum) &&
14018       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14019     if (getLangOpts().CPlusPlus) {
14020       // C++ [dcl.fct]p6:
14021       //   Types shall not be defined in return or parameter types.
14022       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14023         Diag(Loc, diag::err_type_defined_in_param_type)
14024             << Name;
14025         Invalid = true;
14026       }
14027     } else if (!PrevDecl) {
14028       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14029     }
14030   }
14031 
14032   if (Invalid)
14033     New->setInvalidDecl();
14034 
14035   // Set the lexical context. If the tag has a C++ scope specifier, the
14036   // lexical context will be different from the semantic context.
14037   New->setLexicalDeclContext(CurContext);
14038 
14039   // Mark this as a friend decl if applicable.
14040   // In Microsoft mode, a friend declaration also acts as a forward
14041   // declaration so we always pass true to setObjectOfFriendDecl to make
14042   // the tag name visible.
14043   if (TUK == TUK_Friend)
14044     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14045 
14046   // Set the access specifier.
14047   if (!Invalid && SearchDC->isRecord())
14048     SetMemberAccessSpecifier(New, PrevDecl, AS);
14049 
14050   if (TUK == TUK_Definition)
14051     New->startDefinition();
14052 
14053   if (Attr)
14054     ProcessDeclAttributeList(S, New, Attr);
14055   AddPragmaAttributes(S, New);
14056 
14057   // If this has an identifier, add it to the scope stack.
14058   if (TUK == TUK_Friend) {
14059     // We might be replacing an existing declaration in the lookup tables;
14060     // if so, borrow its access specifier.
14061     if (PrevDecl)
14062       New->setAccess(PrevDecl->getAccess());
14063 
14064     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14065     DC->makeDeclVisibleInContext(New);
14066     if (Name) // can be null along some error paths
14067       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14068         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14069   } else if (Name) {
14070     S = getNonFieldDeclScope(S);
14071     PushOnScopeChains(New, S, !IsForwardReference);
14072     if (IsForwardReference)
14073       SearchDC->makeDeclVisibleInContext(New);
14074   } else {
14075     CurContext->addDecl(New);
14076   }
14077 
14078   // If this is the C FILE type, notify the AST context.
14079   if (IdentifierInfo *II = New->getIdentifier())
14080     if (!New->isInvalidDecl() &&
14081         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14082         II->isStr("FILE"))
14083       Context.setFILEDecl(New);
14084 
14085   if (PrevDecl)
14086     mergeDeclAttributes(New, PrevDecl);
14087 
14088   // If there's a #pragma GCC visibility in scope, set the visibility of this
14089   // record.
14090   AddPushedVisibilityAttribute(New);
14091 
14092   if (isMemberSpecialization && !New->isInvalidDecl())
14093     CompleteMemberSpecialization(New, Previous);
14094 
14095   OwnedDecl = true;
14096   // In C++, don't return an invalid declaration. We can't recover well from
14097   // the cases where we make the type anonymous.
14098   if (Invalid && getLangOpts().CPlusPlus) {
14099     if (New->isBeingDefined())
14100       if (auto RD = dyn_cast<RecordDecl>(New))
14101         RD->completeDefinition();
14102     return nullptr;
14103   } else {
14104     return New;
14105   }
14106 }
14107 
14108 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14109   AdjustDeclIfTemplate(TagD);
14110   TagDecl *Tag = cast<TagDecl>(TagD);
14111 
14112   // Enter the tag context.
14113   PushDeclContext(S, Tag);
14114 
14115   ActOnDocumentableDecl(TagD);
14116 
14117   // If there's a #pragma GCC visibility in scope, set the visibility of this
14118   // record.
14119   AddPushedVisibilityAttribute(Tag);
14120 }
14121 
14122 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14123                                     SkipBodyInfo &SkipBody) {
14124   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14125     return false;
14126 
14127   // Make the previous decl visible.
14128   makeMergedDefinitionVisible(SkipBody.Previous);
14129   return true;
14130 }
14131 
14132 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14133   assert(isa<ObjCContainerDecl>(IDecl) &&
14134          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14135   DeclContext *OCD = cast<DeclContext>(IDecl);
14136   assert(getContainingDC(OCD) == CurContext &&
14137       "The next DeclContext should be lexically contained in the current one.");
14138   CurContext = OCD;
14139   return IDecl;
14140 }
14141 
14142 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14143                                            SourceLocation FinalLoc,
14144                                            bool IsFinalSpelledSealed,
14145                                            SourceLocation LBraceLoc) {
14146   AdjustDeclIfTemplate(TagD);
14147   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14148 
14149   FieldCollector->StartClass();
14150 
14151   if (!Record->getIdentifier())
14152     return;
14153 
14154   if (FinalLoc.isValid())
14155     Record->addAttr(new (Context)
14156                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14157 
14158   // C++ [class]p2:
14159   //   [...] The class-name is also inserted into the scope of the
14160   //   class itself; this is known as the injected-class-name. For
14161   //   purposes of access checking, the injected-class-name is treated
14162   //   as if it were a public member name.
14163   CXXRecordDecl *InjectedClassName
14164     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14165                             Record->getLocStart(), Record->getLocation(),
14166                             Record->getIdentifier(),
14167                             /*PrevDecl=*/nullptr,
14168                             /*DelayTypeCreation=*/true);
14169   Context.getTypeDeclType(InjectedClassName, Record);
14170   InjectedClassName->setImplicit();
14171   InjectedClassName->setAccess(AS_public);
14172   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14173       InjectedClassName->setDescribedClassTemplate(Template);
14174   PushOnScopeChains(InjectedClassName, S);
14175   assert(InjectedClassName->isInjectedClassName() &&
14176          "Broken injected-class-name");
14177 }
14178 
14179 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14180                                     SourceRange BraceRange) {
14181   AdjustDeclIfTemplate(TagD);
14182   TagDecl *Tag = cast<TagDecl>(TagD);
14183   Tag->setBraceRange(BraceRange);
14184 
14185   // Make sure we "complete" the definition even it is invalid.
14186   if (Tag->isBeingDefined()) {
14187     assert(Tag->isInvalidDecl() && "We should already have completed it");
14188     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14189       RD->completeDefinition();
14190   }
14191 
14192   if (isa<CXXRecordDecl>(Tag)) {
14193     FieldCollector->FinishClass();
14194   }
14195 
14196   // Exit this scope of this tag's definition.
14197   PopDeclContext();
14198 
14199   if (getCurLexicalContext()->isObjCContainer() &&
14200       Tag->getDeclContext()->isFileContext())
14201     Tag->setTopLevelDeclInObjCContainer();
14202 
14203   // Notify the consumer that we've defined a tag.
14204   if (!Tag->isInvalidDecl())
14205     Consumer.HandleTagDeclDefinition(Tag);
14206 }
14207 
14208 void Sema::ActOnObjCContainerFinishDefinition() {
14209   // Exit this scope of this interface definition.
14210   PopDeclContext();
14211 }
14212 
14213 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14214   assert(DC == CurContext && "Mismatch of container contexts");
14215   OriginalLexicalContext = DC;
14216   ActOnObjCContainerFinishDefinition();
14217 }
14218 
14219 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14220   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14221   OriginalLexicalContext = nullptr;
14222 }
14223 
14224 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14225   AdjustDeclIfTemplate(TagD);
14226   TagDecl *Tag = cast<TagDecl>(TagD);
14227   Tag->setInvalidDecl();
14228 
14229   // Make sure we "complete" the definition even it is invalid.
14230   if (Tag->isBeingDefined()) {
14231     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14232       RD->completeDefinition();
14233   }
14234 
14235   // We're undoing ActOnTagStartDefinition here, not
14236   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14237   // the FieldCollector.
14238 
14239   PopDeclContext();
14240 }
14241 
14242 // Note that FieldName may be null for anonymous bitfields.
14243 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14244                                 IdentifierInfo *FieldName,
14245                                 QualType FieldTy, bool IsMsStruct,
14246                                 Expr *BitWidth, bool *ZeroWidth) {
14247   // Default to true; that shouldn't confuse checks for emptiness
14248   if (ZeroWidth)
14249     *ZeroWidth = true;
14250 
14251   // C99 6.7.2.1p4 - verify the field type.
14252   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14253   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14254     // Handle incomplete types with specific error.
14255     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14256       return ExprError();
14257     if (FieldName)
14258       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14259         << FieldName << FieldTy << BitWidth->getSourceRange();
14260     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14261       << FieldTy << BitWidth->getSourceRange();
14262   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14263                                              UPPC_BitFieldWidth))
14264     return ExprError();
14265 
14266   // If the bit-width is type- or value-dependent, don't try to check
14267   // it now.
14268   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14269     return BitWidth;
14270 
14271   llvm::APSInt Value;
14272   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14273   if (ICE.isInvalid())
14274     return ICE;
14275   BitWidth = ICE.get();
14276 
14277   if (Value != 0 && ZeroWidth)
14278     *ZeroWidth = false;
14279 
14280   // Zero-width bitfield is ok for anonymous field.
14281   if (Value == 0 && FieldName)
14282     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14283 
14284   if (Value.isSigned() && Value.isNegative()) {
14285     if (FieldName)
14286       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14287                << FieldName << Value.toString(10);
14288     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14289       << Value.toString(10);
14290   }
14291 
14292   if (!FieldTy->isDependentType()) {
14293     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14294     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14295     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14296 
14297     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14298     // ABI.
14299     bool CStdConstraintViolation =
14300         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14301     bool MSBitfieldViolation =
14302         Value.ugt(TypeStorageSize) &&
14303         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14304     if (CStdConstraintViolation || MSBitfieldViolation) {
14305       unsigned DiagWidth =
14306           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14307       if (FieldName)
14308         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14309                << FieldName << (unsigned)Value.getZExtValue()
14310                << !CStdConstraintViolation << DiagWidth;
14311 
14312       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14313              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14314              << DiagWidth;
14315     }
14316 
14317     // Warn on types where the user might conceivably expect to get all
14318     // specified bits as value bits: that's all integral types other than
14319     // 'bool'.
14320     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14321       if (FieldName)
14322         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14323             << FieldName << (unsigned)Value.getZExtValue()
14324             << (unsigned)TypeWidth;
14325       else
14326         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14327             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14328     }
14329   }
14330 
14331   return BitWidth;
14332 }
14333 
14334 /// ActOnField - Each field of a C struct/union is passed into this in order
14335 /// to create a FieldDecl object for it.
14336 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14337                        Declarator &D, Expr *BitfieldWidth) {
14338   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14339                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14340                                /*InitStyle=*/ICIS_NoInit, AS_public);
14341   return Res;
14342 }
14343 
14344 /// HandleField - Analyze a field of a C struct or a C++ data member.
14345 ///
14346 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14347                              SourceLocation DeclStart,
14348                              Declarator &D, Expr *BitWidth,
14349                              InClassInitStyle InitStyle,
14350                              AccessSpecifier AS) {
14351   if (D.isDecompositionDeclarator()) {
14352     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14353     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14354       << Decomp.getSourceRange();
14355     return nullptr;
14356   }
14357 
14358   IdentifierInfo *II = D.getIdentifier();
14359   SourceLocation Loc = DeclStart;
14360   if (II) Loc = D.getIdentifierLoc();
14361 
14362   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14363   QualType T = TInfo->getType();
14364   if (getLangOpts().CPlusPlus) {
14365     CheckExtraCXXDefaultArguments(D);
14366 
14367     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14368                                         UPPC_DataMemberType)) {
14369       D.setInvalidType();
14370       T = Context.IntTy;
14371       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14372     }
14373   }
14374 
14375   // TR 18037 does not allow fields to be declared with address spaces.
14376   if (T.getQualifiers().hasAddressSpace() ||
14377       T->isDependentAddressSpaceType() ||
14378       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14379     Diag(Loc, diag::err_field_with_address_space);
14380     D.setInvalidType();
14381   }
14382 
14383   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14384   // used as structure or union field: image, sampler, event or block types.
14385   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14386                           T->isSamplerT() || T->isBlockPointerType())) {
14387     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14388     D.setInvalidType();
14389   }
14390 
14391   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14392 
14393   if (D.getDeclSpec().isInlineSpecified())
14394     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14395         << getLangOpts().CPlusPlus1z;
14396   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14397     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14398          diag::err_invalid_thread)
14399       << DeclSpec::getSpecifierName(TSCS);
14400 
14401   // Check to see if this name was declared as a member previously
14402   NamedDecl *PrevDecl = nullptr;
14403   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14404   LookupName(Previous, S);
14405   switch (Previous.getResultKind()) {
14406     case LookupResult::Found:
14407     case LookupResult::FoundUnresolvedValue:
14408       PrevDecl = Previous.getAsSingle<NamedDecl>();
14409       break;
14410 
14411     case LookupResult::FoundOverloaded:
14412       PrevDecl = Previous.getRepresentativeDecl();
14413       break;
14414 
14415     case LookupResult::NotFound:
14416     case LookupResult::NotFoundInCurrentInstantiation:
14417     case LookupResult::Ambiguous:
14418       break;
14419   }
14420   Previous.suppressDiagnostics();
14421 
14422   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14423     // Maybe we will complain about the shadowed template parameter.
14424     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14425     // Just pretend that we didn't see the previous declaration.
14426     PrevDecl = nullptr;
14427   }
14428 
14429   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14430     PrevDecl = nullptr;
14431 
14432   bool Mutable
14433     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14434   SourceLocation TSSL = D.getLocStart();
14435   FieldDecl *NewFD
14436     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14437                      TSSL, AS, PrevDecl, &D);
14438 
14439   if (NewFD->isInvalidDecl())
14440     Record->setInvalidDecl();
14441 
14442   if (D.getDeclSpec().isModulePrivateSpecified())
14443     NewFD->setModulePrivate();
14444 
14445   if (NewFD->isInvalidDecl() && PrevDecl) {
14446     // Don't introduce NewFD into scope; there's already something
14447     // with the same name in the same scope.
14448   } else if (II) {
14449     PushOnScopeChains(NewFD, S);
14450   } else
14451     Record->addDecl(NewFD);
14452 
14453   return NewFD;
14454 }
14455 
14456 /// \brief Build a new FieldDecl and check its well-formedness.
14457 ///
14458 /// This routine builds a new FieldDecl given the fields name, type,
14459 /// record, etc. \p PrevDecl should refer to any previous declaration
14460 /// with the same name and in the same scope as the field to be
14461 /// created.
14462 ///
14463 /// \returns a new FieldDecl.
14464 ///
14465 /// \todo The Declarator argument is a hack. It will be removed once
14466 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14467                                 TypeSourceInfo *TInfo,
14468                                 RecordDecl *Record, SourceLocation Loc,
14469                                 bool Mutable, Expr *BitWidth,
14470                                 InClassInitStyle InitStyle,
14471                                 SourceLocation TSSL,
14472                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14473                                 Declarator *D) {
14474   IdentifierInfo *II = Name.getAsIdentifierInfo();
14475   bool InvalidDecl = false;
14476   if (D) InvalidDecl = D->isInvalidType();
14477 
14478   // If we receive a broken type, recover by assuming 'int' and
14479   // marking this declaration as invalid.
14480   if (T.isNull()) {
14481     InvalidDecl = true;
14482     T = Context.IntTy;
14483   }
14484 
14485   QualType EltTy = Context.getBaseElementType(T);
14486   if (!EltTy->isDependentType()) {
14487     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14488       // Fields of incomplete type force their record to be invalid.
14489       Record->setInvalidDecl();
14490       InvalidDecl = true;
14491     } else {
14492       NamedDecl *Def;
14493       EltTy->isIncompleteType(&Def);
14494       if (Def && Def->isInvalidDecl()) {
14495         Record->setInvalidDecl();
14496         InvalidDecl = true;
14497       }
14498     }
14499   }
14500 
14501   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14502   if (BitWidth && getLangOpts().OpenCL) {
14503     Diag(Loc, diag::err_opencl_bitfields);
14504     InvalidDecl = true;
14505   }
14506 
14507   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14508   // than a variably modified type.
14509   if (!InvalidDecl && T->isVariablyModifiedType()) {
14510     bool SizeIsNegative;
14511     llvm::APSInt Oversized;
14512 
14513     TypeSourceInfo *FixedTInfo =
14514       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14515                                                     SizeIsNegative,
14516                                                     Oversized);
14517     if (FixedTInfo) {
14518       Diag(Loc, diag::warn_illegal_constant_array_size);
14519       TInfo = FixedTInfo;
14520       T = FixedTInfo->getType();
14521     } else {
14522       if (SizeIsNegative)
14523         Diag(Loc, diag::err_typecheck_negative_array_size);
14524       else if (Oversized.getBoolValue())
14525         Diag(Loc, diag::err_array_too_large)
14526           << Oversized.toString(10);
14527       else
14528         Diag(Loc, diag::err_typecheck_field_variable_size);
14529       InvalidDecl = true;
14530     }
14531   }
14532 
14533   // Fields can not have abstract class types
14534   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14535                                              diag::err_abstract_type_in_decl,
14536                                              AbstractFieldType))
14537     InvalidDecl = true;
14538 
14539   bool ZeroWidth = false;
14540   if (InvalidDecl)
14541     BitWidth = nullptr;
14542   // If this is declared as a bit-field, check the bit-field.
14543   if (BitWidth) {
14544     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14545                               &ZeroWidth).get();
14546     if (!BitWidth) {
14547       InvalidDecl = true;
14548       BitWidth = nullptr;
14549       ZeroWidth = false;
14550     }
14551   }
14552 
14553   // Check that 'mutable' is consistent with the type of the declaration.
14554   if (!InvalidDecl && Mutable) {
14555     unsigned DiagID = 0;
14556     if (T->isReferenceType())
14557       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14558                                         : diag::err_mutable_reference;
14559     else if (T.isConstQualified())
14560       DiagID = diag::err_mutable_const;
14561 
14562     if (DiagID) {
14563       SourceLocation ErrLoc = Loc;
14564       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14565         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14566       Diag(ErrLoc, DiagID);
14567       if (DiagID != diag::ext_mutable_reference) {
14568         Mutable = false;
14569         InvalidDecl = true;
14570       }
14571     }
14572   }
14573 
14574   // C++11 [class.union]p8 (DR1460):
14575   //   At most one variant member of a union may have a
14576   //   brace-or-equal-initializer.
14577   if (InitStyle != ICIS_NoInit)
14578     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14579 
14580   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14581                                        BitWidth, Mutable, InitStyle);
14582   if (InvalidDecl)
14583     NewFD->setInvalidDecl();
14584 
14585   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14586     Diag(Loc, diag::err_duplicate_member) << II;
14587     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14588     NewFD->setInvalidDecl();
14589   }
14590 
14591   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14592     if (Record->isUnion()) {
14593       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14594         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14595         if (RDecl->getDefinition()) {
14596           // C++ [class.union]p1: An object of a class with a non-trivial
14597           // constructor, a non-trivial copy constructor, a non-trivial
14598           // destructor, or a non-trivial copy assignment operator
14599           // cannot be a member of a union, nor can an array of such
14600           // objects.
14601           if (CheckNontrivialField(NewFD))
14602             NewFD->setInvalidDecl();
14603         }
14604       }
14605 
14606       // C++ [class.union]p1: If a union contains a member of reference type,
14607       // the program is ill-formed, except when compiling with MSVC extensions
14608       // enabled.
14609       if (EltTy->isReferenceType()) {
14610         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14611                                     diag::ext_union_member_of_reference_type :
14612                                     diag::err_union_member_of_reference_type)
14613           << NewFD->getDeclName() << EltTy;
14614         if (!getLangOpts().MicrosoftExt)
14615           NewFD->setInvalidDecl();
14616       }
14617     }
14618   }
14619 
14620   // FIXME: We need to pass in the attributes given an AST
14621   // representation, not a parser representation.
14622   if (D) {
14623     // FIXME: The current scope is almost... but not entirely... correct here.
14624     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14625 
14626     if (NewFD->hasAttrs())
14627       CheckAlignasUnderalignment(NewFD);
14628   }
14629 
14630   // In auto-retain/release, infer strong retension for fields of
14631   // retainable type.
14632   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14633     NewFD->setInvalidDecl();
14634 
14635   if (T.isObjCGCWeak())
14636     Diag(Loc, diag::warn_attribute_weak_on_field);
14637 
14638   NewFD->setAccess(AS);
14639   return NewFD;
14640 }
14641 
14642 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14643   assert(FD);
14644   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14645 
14646   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14647     return false;
14648 
14649   QualType EltTy = Context.getBaseElementType(FD->getType());
14650   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14651     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14652     if (RDecl->getDefinition()) {
14653       // We check for copy constructors before constructors
14654       // because otherwise we'll never get complaints about
14655       // copy constructors.
14656 
14657       CXXSpecialMember member = CXXInvalid;
14658       // We're required to check for any non-trivial constructors. Since the
14659       // implicit default constructor is suppressed if there are any
14660       // user-declared constructors, we just need to check that there is a
14661       // trivial default constructor and a trivial copy constructor. (We don't
14662       // worry about move constructors here, since this is a C++98 check.)
14663       if (RDecl->hasNonTrivialCopyConstructor())
14664         member = CXXCopyConstructor;
14665       else if (!RDecl->hasTrivialDefaultConstructor())
14666         member = CXXDefaultConstructor;
14667       else if (RDecl->hasNonTrivialCopyAssignment())
14668         member = CXXCopyAssignment;
14669       else if (RDecl->hasNonTrivialDestructor())
14670         member = CXXDestructor;
14671 
14672       if (member != CXXInvalid) {
14673         if (!getLangOpts().CPlusPlus11 &&
14674             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14675           // Objective-C++ ARC: it is an error to have a non-trivial field of
14676           // a union. However, system headers in Objective-C programs
14677           // occasionally have Objective-C lifetime objects within unions,
14678           // and rather than cause the program to fail, we make those
14679           // members unavailable.
14680           SourceLocation Loc = FD->getLocation();
14681           if (getSourceManager().isInSystemHeader(Loc)) {
14682             if (!FD->hasAttr<UnavailableAttr>())
14683               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14684                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14685             return false;
14686           }
14687         }
14688 
14689         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14690                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14691                diag::err_illegal_union_or_anon_struct_member)
14692           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14693         DiagnoseNontrivial(RDecl, member);
14694         return !getLangOpts().CPlusPlus11;
14695       }
14696     }
14697   }
14698 
14699   return false;
14700 }
14701 
14702 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14703 ///  AST enum value.
14704 static ObjCIvarDecl::AccessControl
14705 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14706   switch (ivarVisibility) {
14707   default: llvm_unreachable("Unknown visitibility kind");
14708   case tok::objc_private: return ObjCIvarDecl::Private;
14709   case tok::objc_public: return ObjCIvarDecl::Public;
14710   case tok::objc_protected: return ObjCIvarDecl::Protected;
14711   case tok::objc_package: return ObjCIvarDecl::Package;
14712   }
14713 }
14714 
14715 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14716 /// in order to create an IvarDecl object for it.
14717 Decl *Sema::ActOnIvar(Scope *S,
14718                                 SourceLocation DeclStart,
14719                                 Declarator &D, Expr *BitfieldWidth,
14720                                 tok::ObjCKeywordKind Visibility) {
14721 
14722   IdentifierInfo *II = D.getIdentifier();
14723   Expr *BitWidth = (Expr*)BitfieldWidth;
14724   SourceLocation Loc = DeclStart;
14725   if (II) Loc = D.getIdentifierLoc();
14726 
14727   // FIXME: Unnamed fields can be handled in various different ways, for
14728   // example, unnamed unions inject all members into the struct namespace!
14729 
14730   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14731   QualType T = TInfo->getType();
14732 
14733   if (BitWidth) {
14734     // 6.7.2.1p3, 6.7.2.1p4
14735     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14736     if (!BitWidth)
14737       D.setInvalidType();
14738   } else {
14739     // Not a bitfield.
14740 
14741     // validate II.
14742 
14743   }
14744   if (T->isReferenceType()) {
14745     Diag(Loc, diag::err_ivar_reference_type);
14746     D.setInvalidType();
14747   }
14748   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14749   // than a variably modified type.
14750   else if (T->isVariablyModifiedType()) {
14751     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14752     D.setInvalidType();
14753   }
14754 
14755   // Get the visibility (access control) for this ivar.
14756   ObjCIvarDecl::AccessControl ac =
14757     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14758                                         : ObjCIvarDecl::None;
14759   // Must set ivar's DeclContext to its enclosing interface.
14760   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14761   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14762     return nullptr;
14763   ObjCContainerDecl *EnclosingContext;
14764   if (ObjCImplementationDecl *IMPDecl =
14765       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14766     if (LangOpts.ObjCRuntime.isFragile()) {
14767     // Case of ivar declared in an implementation. Context is that of its class.
14768       EnclosingContext = IMPDecl->getClassInterface();
14769       assert(EnclosingContext && "Implementation has no class interface!");
14770     }
14771     else
14772       EnclosingContext = EnclosingDecl;
14773   } else {
14774     if (ObjCCategoryDecl *CDecl =
14775         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14776       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14777         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14778         return nullptr;
14779       }
14780     }
14781     EnclosingContext = EnclosingDecl;
14782   }
14783 
14784   // Construct the decl.
14785   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14786                                              DeclStart, Loc, II, T,
14787                                              TInfo, ac, (Expr *)BitfieldWidth);
14788 
14789   if (II) {
14790     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14791                                            ForRedeclaration);
14792     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14793         && !isa<TagDecl>(PrevDecl)) {
14794       Diag(Loc, diag::err_duplicate_member) << II;
14795       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14796       NewID->setInvalidDecl();
14797     }
14798   }
14799 
14800   // Process attributes attached to the ivar.
14801   ProcessDeclAttributes(S, NewID, D);
14802 
14803   if (D.isInvalidType())
14804     NewID->setInvalidDecl();
14805 
14806   // In ARC, infer 'retaining' for ivars of retainable type.
14807   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14808     NewID->setInvalidDecl();
14809 
14810   if (D.getDeclSpec().isModulePrivateSpecified())
14811     NewID->setModulePrivate();
14812 
14813   if (II) {
14814     // FIXME: When interfaces are DeclContexts, we'll need to add
14815     // these to the interface.
14816     S->AddDecl(NewID);
14817     IdResolver.AddDecl(NewID);
14818   }
14819 
14820   if (LangOpts.ObjCRuntime.isNonFragile() &&
14821       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14822     Diag(Loc, diag::warn_ivars_in_interface);
14823 
14824   return NewID;
14825 }
14826 
14827 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14828 /// class and class extensions. For every class \@interface and class
14829 /// extension \@interface, if the last ivar is a bitfield of any type,
14830 /// then add an implicit `char :0` ivar to the end of that interface.
14831 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14832                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14833   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14834     return;
14835 
14836   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14837   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14838 
14839   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14840     return;
14841   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14842   if (!ID) {
14843     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14844       if (!CD->IsClassExtension())
14845         return;
14846     }
14847     // No need to add this to end of @implementation.
14848     else
14849       return;
14850   }
14851   // All conditions are met. Add a new bitfield to the tail end of ivars.
14852   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14853   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14854 
14855   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14856                               DeclLoc, DeclLoc, nullptr,
14857                               Context.CharTy,
14858                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14859                                                                DeclLoc),
14860                               ObjCIvarDecl::Private, BW,
14861                               true);
14862   AllIvarDecls.push_back(Ivar);
14863 }
14864 
14865 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14866                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14867                        SourceLocation RBrac, AttributeList *Attr) {
14868   assert(EnclosingDecl && "missing record or interface decl");
14869 
14870   // If this is an Objective-C @implementation or category and we have
14871   // new fields here we should reset the layout of the interface since
14872   // it will now change.
14873   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14874     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14875     switch (DC->getKind()) {
14876     default: break;
14877     case Decl::ObjCCategory:
14878       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14879       break;
14880     case Decl::ObjCImplementation:
14881       Context.
14882         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14883       break;
14884     }
14885   }
14886 
14887   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14888 
14889   // Start counting up the number of named members; make sure to include
14890   // members of anonymous structs and unions in the total.
14891   unsigned NumNamedMembers = 0;
14892   if (Record) {
14893     for (const auto *I : Record->decls()) {
14894       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14895         if (IFD->getDeclName())
14896           ++NumNamedMembers;
14897     }
14898   }
14899 
14900   // Verify that all the fields are okay.
14901   SmallVector<FieldDecl*, 32> RecFields;
14902 
14903   bool ObjCFieldLifetimeErrReported = false;
14904   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14905        i != end; ++i) {
14906     FieldDecl *FD = cast<FieldDecl>(*i);
14907 
14908     // Get the type for the field.
14909     const Type *FDTy = FD->getType().getTypePtr();
14910 
14911     if (!FD->isAnonymousStructOrUnion()) {
14912       // Remember all fields written by the user.
14913       RecFields.push_back(FD);
14914     }
14915 
14916     // If the field is already invalid for some reason, don't emit more
14917     // diagnostics about it.
14918     if (FD->isInvalidDecl()) {
14919       EnclosingDecl->setInvalidDecl();
14920       continue;
14921     }
14922 
14923     // C99 6.7.2.1p2:
14924     //   A structure or union shall not contain a member with
14925     //   incomplete or function type (hence, a structure shall not
14926     //   contain an instance of itself, but may contain a pointer to
14927     //   an instance of itself), except that the last member of a
14928     //   structure with more than one named member may have incomplete
14929     //   array type; such a structure (and any union containing,
14930     //   possibly recursively, a member that is such a structure)
14931     //   shall not be a member of a structure or an element of an
14932     //   array.
14933     if (FDTy->isFunctionType()) {
14934       // Field declared as a function.
14935       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14936         << FD->getDeclName();
14937       FD->setInvalidDecl();
14938       EnclosingDecl->setInvalidDecl();
14939       continue;
14940     } else if (FDTy->isIncompleteArrayType() && Record &&
14941                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14942                 ((getLangOpts().MicrosoftExt ||
14943                   getLangOpts().CPlusPlus) &&
14944                  (i + 1 == Fields.end() || Record->isUnion())))) {
14945       // Flexible array member.
14946       // Microsoft and g++ is more permissive regarding flexible array.
14947       // It will accept flexible array in union and also
14948       // as the sole element of a struct/class.
14949       unsigned DiagID = 0;
14950       if (Record->isUnion())
14951         DiagID = getLangOpts().MicrosoftExt
14952                      ? diag::ext_flexible_array_union_ms
14953                      : getLangOpts().CPlusPlus
14954                            ? diag::ext_flexible_array_union_gnu
14955                            : diag::err_flexible_array_union;
14956       else if (NumNamedMembers < 1)
14957         DiagID = getLangOpts().MicrosoftExt
14958                      ? diag::ext_flexible_array_empty_aggregate_ms
14959                      : getLangOpts().CPlusPlus
14960                            ? diag::ext_flexible_array_empty_aggregate_gnu
14961                            : diag::err_flexible_array_empty_aggregate;
14962 
14963       if (DiagID)
14964         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14965                                         << Record->getTagKind();
14966       // While the layout of types that contain virtual bases is not specified
14967       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14968       // virtual bases after the derived members.  This would make a flexible
14969       // array member declared at the end of an object not adjacent to the end
14970       // of the type.
14971       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14972         if (RD->getNumVBases() != 0)
14973           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14974             << FD->getDeclName() << Record->getTagKind();
14975       if (!getLangOpts().C99)
14976         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14977           << FD->getDeclName() << Record->getTagKind();
14978 
14979       // If the element type has a non-trivial destructor, we would not
14980       // implicitly destroy the elements, so disallow it for now.
14981       //
14982       // FIXME: GCC allows this. We should probably either implicitly delete
14983       // the destructor of the containing class, or just allow this.
14984       QualType BaseElem = Context.getBaseElementType(FD->getType());
14985       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14986         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14987           << FD->getDeclName() << FD->getType();
14988         FD->setInvalidDecl();
14989         EnclosingDecl->setInvalidDecl();
14990         continue;
14991       }
14992       // Okay, we have a legal flexible array member at the end of the struct.
14993       Record->setHasFlexibleArrayMember(true);
14994     } else if (!FDTy->isDependentType() &&
14995                RequireCompleteType(FD->getLocation(), FD->getType(),
14996                                    diag::err_field_incomplete)) {
14997       // Incomplete type
14998       FD->setInvalidDecl();
14999       EnclosingDecl->setInvalidDecl();
15000       continue;
15001     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15002       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15003         // A type which contains a flexible array member is considered to be a
15004         // flexible array member.
15005         Record->setHasFlexibleArrayMember(true);
15006         if (!Record->isUnion()) {
15007           // If this is a struct/class and this is not the last element, reject
15008           // it.  Note that GCC supports variable sized arrays in the middle of
15009           // structures.
15010           if (i + 1 != Fields.end())
15011             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15012               << FD->getDeclName() << FD->getType();
15013           else {
15014             // We support flexible arrays at the end of structs in
15015             // other structs as an extension.
15016             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15017               << FD->getDeclName();
15018           }
15019         }
15020       }
15021       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15022           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15023                                  diag::err_abstract_type_in_decl,
15024                                  AbstractIvarType)) {
15025         // Ivars can not have abstract class types
15026         FD->setInvalidDecl();
15027       }
15028       if (Record && FDTTy->getDecl()->hasObjectMember())
15029         Record->setHasObjectMember(true);
15030       if (Record && FDTTy->getDecl()->hasVolatileMember())
15031         Record->setHasVolatileMember(true);
15032     } else if (FDTy->isObjCObjectType()) {
15033       /// A field cannot be an Objective-c object
15034       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15035         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15036       QualType T = Context.getObjCObjectPointerType(FD->getType());
15037       FD->setType(T);
15038     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15039                Record && !ObjCFieldLifetimeErrReported &&
15040                (!getLangOpts().CPlusPlus || Record->isUnion())) {
15041       // It's an error in ARC or Weak if a field has lifetime.
15042       // We don't want to report this in a system header, though,
15043       // so we just make the field unavailable.
15044       // FIXME: that's really not sufficient; we need to make the type
15045       // itself invalid to, say, initialize or copy.
15046       QualType T = FD->getType();
15047       if (T.hasNonTrivialObjCLifetime()) {
15048         SourceLocation loc = FD->getLocation();
15049         if (getSourceManager().isInSystemHeader(loc)) {
15050           if (!FD->hasAttr<UnavailableAttr>()) {
15051             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15052                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15053           }
15054         } else {
15055           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15056             << T->isBlockPointerType() << Record->getTagKind();
15057         }
15058         ObjCFieldLifetimeErrReported = true;
15059       }
15060     } else if (getLangOpts().ObjC1 &&
15061                getLangOpts().getGC() != LangOptions::NonGC &&
15062                Record && !Record->hasObjectMember()) {
15063       if (FD->getType()->isObjCObjectPointerType() ||
15064           FD->getType().isObjCGCStrong())
15065         Record->setHasObjectMember(true);
15066       else if (Context.getAsArrayType(FD->getType())) {
15067         QualType BaseType = Context.getBaseElementType(FD->getType());
15068         if (BaseType->isRecordType() &&
15069             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15070           Record->setHasObjectMember(true);
15071         else if (BaseType->isObjCObjectPointerType() ||
15072                  BaseType.isObjCGCStrong())
15073                Record->setHasObjectMember(true);
15074       }
15075     }
15076     if (Record && FD->getType().isVolatileQualified())
15077       Record->setHasVolatileMember(true);
15078     // Keep track of the number of named members.
15079     if (FD->getIdentifier())
15080       ++NumNamedMembers;
15081   }
15082 
15083   // Okay, we successfully defined 'Record'.
15084   if (Record) {
15085     bool Completed = false;
15086     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15087       if (!CXXRecord->isInvalidDecl()) {
15088         // Set access bits correctly on the directly-declared conversions.
15089         for (CXXRecordDecl::conversion_iterator
15090                I = CXXRecord->conversion_begin(),
15091                E = CXXRecord->conversion_end(); I != E; ++I)
15092           I.setAccess((*I)->getAccess());
15093       }
15094 
15095       if (!CXXRecord->isDependentType()) {
15096         if (CXXRecord->hasUserDeclaredDestructor()) {
15097           // Adjust user-defined destructor exception spec.
15098           if (getLangOpts().CPlusPlus11)
15099             AdjustDestructorExceptionSpec(CXXRecord,
15100                                           CXXRecord->getDestructor());
15101         }
15102 
15103         if (!CXXRecord->isInvalidDecl()) {
15104           // Add any implicitly-declared members to this class.
15105           AddImplicitlyDeclaredMembersToClass(CXXRecord);
15106 
15107           // If we have virtual base classes, we may end up finding multiple
15108           // final overriders for a given virtual function. Check for this
15109           // problem now.
15110           if (CXXRecord->getNumVBases()) {
15111             CXXFinalOverriderMap FinalOverriders;
15112             CXXRecord->getFinalOverriders(FinalOverriders);
15113 
15114             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15115                                              MEnd = FinalOverriders.end();
15116                  M != MEnd; ++M) {
15117               for (OverridingMethods::iterator SO = M->second.begin(),
15118                                             SOEnd = M->second.end();
15119                    SO != SOEnd; ++SO) {
15120                 assert(SO->second.size() > 0 &&
15121                        "Virtual function without overridding functions?");
15122                 if (SO->second.size() == 1)
15123                   continue;
15124 
15125                 // C++ [class.virtual]p2:
15126                 //   In a derived class, if a virtual member function of a base
15127                 //   class subobject has more than one final overrider the
15128                 //   program is ill-formed.
15129                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15130                   << (const NamedDecl *)M->first << Record;
15131                 Diag(M->first->getLocation(),
15132                      diag::note_overridden_virtual_function);
15133                 for (OverridingMethods::overriding_iterator
15134                           OM = SO->second.begin(),
15135                        OMEnd = SO->second.end();
15136                      OM != OMEnd; ++OM)
15137                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15138                     << (const NamedDecl *)M->first << OM->Method->getParent();
15139 
15140                 Record->setInvalidDecl();
15141               }
15142             }
15143             CXXRecord->completeDefinition(&FinalOverriders);
15144             Completed = true;
15145           }
15146         }
15147       }
15148     }
15149 
15150     if (!Completed)
15151       Record->completeDefinition();
15152 
15153     // We may have deferred checking for a deleted destructor. Check now.
15154     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15155       auto *Dtor = CXXRecord->getDestructor();
15156       if (Dtor && Dtor->isImplicit() &&
15157           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15158         CXXRecord->setImplicitDestructorIsDeleted();
15159         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15160       }
15161     }
15162 
15163     if (Record->hasAttrs()) {
15164       CheckAlignasUnderalignment(Record);
15165 
15166       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15167         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15168                                            IA->getRange(), IA->getBestCase(),
15169                                            IA->getSemanticSpelling());
15170     }
15171 
15172     // Check if the structure/union declaration is a type that can have zero
15173     // size in C. For C this is a language extension, for C++ it may cause
15174     // compatibility problems.
15175     bool CheckForZeroSize;
15176     if (!getLangOpts().CPlusPlus) {
15177       CheckForZeroSize = true;
15178     } else {
15179       // For C++ filter out types that cannot be referenced in C code.
15180       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15181       CheckForZeroSize =
15182           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15183           !CXXRecord->isDependentType() &&
15184           CXXRecord->isCLike();
15185     }
15186     if (CheckForZeroSize) {
15187       bool ZeroSize = true;
15188       bool IsEmpty = true;
15189       unsigned NonBitFields = 0;
15190       for (RecordDecl::field_iterator I = Record->field_begin(),
15191                                       E = Record->field_end();
15192            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15193         IsEmpty = false;
15194         if (I->isUnnamedBitfield()) {
15195           if (I->getBitWidthValue(Context) > 0)
15196             ZeroSize = false;
15197         } else {
15198           ++NonBitFields;
15199           QualType FieldType = I->getType();
15200           if (FieldType->isIncompleteType() ||
15201               !Context.getTypeSizeInChars(FieldType).isZero())
15202             ZeroSize = false;
15203         }
15204       }
15205 
15206       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15207       // allowed in C++, but warn if its declaration is inside
15208       // extern "C" block.
15209       if (ZeroSize) {
15210         Diag(RecLoc, getLangOpts().CPlusPlus ?
15211                          diag::warn_zero_size_struct_union_in_extern_c :
15212                          diag::warn_zero_size_struct_union_compat)
15213           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15214       }
15215 
15216       // Structs without named members are extension in C (C99 6.7.2.1p7),
15217       // but are accepted by GCC.
15218       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15219         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15220                                diag::ext_no_named_members_in_struct_union)
15221           << Record->isUnion();
15222       }
15223     }
15224   } else {
15225     ObjCIvarDecl **ClsFields =
15226       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15227     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15228       ID->setEndOfDefinitionLoc(RBrac);
15229       // Add ivar's to class's DeclContext.
15230       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15231         ClsFields[i]->setLexicalDeclContext(ID);
15232         ID->addDecl(ClsFields[i]);
15233       }
15234       // Must enforce the rule that ivars in the base classes may not be
15235       // duplicates.
15236       if (ID->getSuperClass())
15237         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15238     } else if (ObjCImplementationDecl *IMPDecl =
15239                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15240       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15241       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15242         // Ivar declared in @implementation never belongs to the implementation.
15243         // Only it is in implementation's lexical context.
15244         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15245       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15246       IMPDecl->setIvarLBraceLoc(LBrac);
15247       IMPDecl->setIvarRBraceLoc(RBrac);
15248     } else if (ObjCCategoryDecl *CDecl =
15249                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15250       // case of ivars in class extension; all other cases have been
15251       // reported as errors elsewhere.
15252       // FIXME. Class extension does not have a LocEnd field.
15253       // CDecl->setLocEnd(RBrac);
15254       // Add ivar's to class extension's DeclContext.
15255       // Diagnose redeclaration of private ivars.
15256       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15257       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15258         if (IDecl) {
15259           if (const ObjCIvarDecl *ClsIvar =
15260               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15261             Diag(ClsFields[i]->getLocation(),
15262                  diag::err_duplicate_ivar_declaration);
15263             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15264             continue;
15265           }
15266           for (const auto *Ext : IDecl->known_extensions()) {
15267             if (const ObjCIvarDecl *ClsExtIvar
15268                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15269               Diag(ClsFields[i]->getLocation(),
15270                    diag::err_duplicate_ivar_declaration);
15271               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15272               continue;
15273             }
15274           }
15275         }
15276         ClsFields[i]->setLexicalDeclContext(CDecl);
15277         CDecl->addDecl(ClsFields[i]);
15278       }
15279       CDecl->setIvarLBraceLoc(LBrac);
15280       CDecl->setIvarRBraceLoc(RBrac);
15281     }
15282   }
15283 
15284   if (Attr)
15285     ProcessDeclAttributeList(S, Record, Attr);
15286 }
15287 
15288 /// \brief Determine whether the given integral value is representable within
15289 /// the given type T.
15290 static bool isRepresentableIntegerValue(ASTContext &Context,
15291                                         llvm::APSInt &Value,
15292                                         QualType T) {
15293   assert(T->isIntegralType(Context) && "Integral type required!");
15294   unsigned BitWidth = Context.getIntWidth(T);
15295 
15296   if (Value.isUnsigned() || Value.isNonNegative()) {
15297     if (T->isSignedIntegerOrEnumerationType())
15298       --BitWidth;
15299     return Value.getActiveBits() <= BitWidth;
15300   }
15301   return Value.getMinSignedBits() <= BitWidth;
15302 }
15303 
15304 // \brief Given an integral type, return the next larger integral type
15305 // (or a NULL type of no such type exists).
15306 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15307   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15308   // enum checking below.
15309   assert(T->isIntegralType(Context) && "Integral type required!");
15310   const unsigned NumTypes = 4;
15311   QualType SignedIntegralTypes[NumTypes] = {
15312     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15313   };
15314   QualType UnsignedIntegralTypes[NumTypes] = {
15315     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15316     Context.UnsignedLongLongTy
15317   };
15318 
15319   unsigned BitWidth = Context.getTypeSize(T);
15320   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15321                                                         : UnsignedIntegralTypes;
15322   for (unsigned I = 0; I != NumTypes; ++I)
15323     if (Context.getTypeSize(Types[I]) > BitWidth)
15324       return Types[I];
15325 
15326   return QualType();
15327 }
15328 
15329 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15330                                           EnumConstantDecl *LastEnumConst,
15331                                           SourceLocation IdLoc,
15332                                           IdentifierInfo *Id,
15333                                           Expr *Val) {
15334   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15335   llvm::APSInt EnumVal(IntWidth);
15336   QualType EltTy;
15337 
15338   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15339     Val = nullptr;
15340 
15341   if (Val)
15342     Val = DefaultLvalueConversion(Val).get();
15343 
15344   if (Val) {
15345     if (Enum->isDependentType() || Val->isTypeDependent())
15346       EltTy = Context.DependentTy;
15347     else {
15348       SourceLocation ExpLoc;
15349       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15350           !getLangOpts().MSVCCompat) {
15351         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15352         // constant-expression in the enumerator-definition shall be a converted
15353         // constant expression of the underlying type.
15354         EltTy = Enum->getIntegerType();
15355         ExprResult Converted =
15356           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15357                                            CCEK_Enumerator);
15358         if (Converted.isInvalid())
15359           Val = nullptr;
15360         else
15361           Val = Converted.get();
15362       } else if (!Val->isValueDependent() &&
15363                  !(Val = VerifyIntegerConstantExpression(Val,
15364                                                          &EnumVal).get())) {
15365         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15366       } else {
15367         if (Enum->isFixed()) {
15368           EltTy = Enum->getIntegerType();
15369 
15370           // In Obj-C and Microsoft mode, require the enumeration value to be
15371           // representable in the underlying type of the enumeration. In C++11,
15372           // we perform a non-narrowing conversion as part of converted constant
15373           // expression checking.
15374           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15375             if (getLangOpts().MSVCCompat) {
15376               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15377               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15378             } else
15379               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15380           } else
15381             Val = ImpCastExprToType(Val, EltTy,
15382                                     EltTy->isBooleanType() ?
15383                                     CK_IntegralToBoolean : CK_IntegralCast)
15384                     .get();
15385         } else if (getLangOpts().CPlusPlus) {
15386           // C++11 [dcl.enum]p5:
15387           //   If the underlying type is not fixed, the type of each enumerator
15388           //   is the type of its initializing value:
15389           //     - If an initializer is specified for an enumerator, the
15390           //       initializing value has the same type as the expression.
15391           EltTy = Val->getType();
15392         } else {
15393           // C99 6.7.2.2p2:
15394           //   The expression that defines the value of an enumeration constant
15395           //   shall be an integer constant expression that has a value
15396           //   representable as an int.
15397 
15398           // Complain if the value is not representable in an int.
15399           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15400             Diag(IdLoc, diag::ext_enum_value_not_int)
15401               << EnumVal.toString(10) << Val->getSourceRange()
15402               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15403           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15404             // Force the type of the expression to 'int'.
15405             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15406           }
15407           EltTy = Val->getType();
15408         }
15409       }
15410     }
15411   }
15412 
15413   if (!Val) {
15414     if (Enum->isDependentType())
15415       EltTy = Context.DependentTy;
15416     else if (!LastEnumConst) {
15417       // C++0x [dcl.enum]p5:
15418       //   If the underlying type is not fixed, the type of each enumerator
15419       //   is the type of its initializing value:
15420       //     - If no initializer is specified for the first enumerator, the
15421       //       initializing value has an unspecified integral type.
15422       //
15423       // GCC uses 'int' for its unspecified integral type, as does
15424       // C99 6.7.2.2p3.
15425       if (Enum->isFixed()) {
15426         EltTy = Enum->getIntegerType();
15427       }
15428       else {
15429         EltTy = Context.IntTy;
15430       }
15431     } else {
15432       // Assign the last value + 1.
15433       EnumVal = LastEnumConst->getInitVal();
15434       ++EnumVal;
15435       EltTy = LastEnumConst->getType();
15436 
15437       // Check for overflow on increment.
15438       if (EnumVal < LastEnumConst->getInitVal()) {
15439         // C++0x [dcl.enum]p5:
15440         //   If the underlying type is not fixed, the type of each enumerator
15441         //   is the type of its initializing value:
15442         //
15443         //     - Otherwise the type of the initializing value is the same as
15444         //       the type of the initializing value of the preceding enumerator
15445         //       unless the incremented value is not representable in that type,
15446         //       in which case the type is an unspecified integral type
15447         //       sufficient to contain the incremented value. If no such type
15448         //       exists, the program is ill-formed.
15449         QualType T = getNextLargerIntegralType(Context, EltTy);
15450         if (T.isNull() || Enum->isFixed()) {
15451           // There is no integral type larger enough to represent this
15452           // value. Complain, then allow the value to wrap around.
15453           EnumVal = LastEnumConst->getInitVal();
15454           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15455           ++EnumVal;
15456           if (Enum->isFixed())
15457             // When the underlying type is fixed, this is ill-formed.
15458             Diag(IdLoc, diag::err_enumerator_wrapped)
15459               << EnumVal.toString(10)
15460               << EltTy;
15461           else
15462             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15463               << EnumVal.toString(10);
15464         } else {
15465           EltTy = T;
15466         }
15467 
15468         // Retrieve the last enumerator's value, extent that type to the
15469         // type that is supposed to be large enough to represent the incremented
15470         // value, then increment.
15471         EnumVal = LastEnumConst->getInitVal();
15472         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15473         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15474         ++EnumVal;
15475 
15476         // If we're not in C++, diagnose the overflow of enumerator values,
15477         // which in C99 means that the enumerator value is not representable in
15478         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15479         // permits enumerator values that are representable in some larger
15480         // integral type.
15481         if (!getLangOpts().CPlusPlus && !T.isNull())
15482           Diag(IdLoc, diag::warn_enum_value_overflow);
15483       } else if (!getLangOpts().CPlusPlus &&
15484                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15485         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15486         Diag(IdLoc, diag::ext_enum_value_not_int)
15487           << EnumVal.toString(10) << 1;
15488       }
15489     }
15490   }
15491 
15492   if (!EltTy->isDependentType()) {
15493     // Make the enumerator value match the signedness and size of the
15494     // enumerator's type.
15495     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15496     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15497   }
15498 
15499   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15500                                   Val, EnumVal);
15501 }
15502 
15503 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15504                                                 SourceLocation IILoc) {
15505   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15506       !getLangOpts().CPlusPlus)
15507     return SkipBodyInfo();
15508 
15509   // We have an anonymous enum definition. Look up the first enumerator to
15510   // determine if we should merge the definition with an existing one and
15511   // skip the body.
15512   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15513                                          ForRedeclaration);
15514   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15515   if (!PrevECD)
15516     return SkipBodyInfo();
15517 
15518   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15519   NamedDecl *Hidden;
15520   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15521     SkipBodyInfo Skip;
15522     Skip.Previous = Hidden;
15523     return Skip;
15524   }
15525 
15526   return SkipBodyInfo();
15527 }
15528 
15529 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15530                               SourceLocation IdLoc, IdentifierInfo *Id,
15531                               AttributeList *Attr,
15532                               SourceLocation EqualLoc, Expr *Val) {
15533   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15534   EnumConstantDecl *LastEnumConst =
15535     cast_or_null<EnumConstantDecl>(lastEnumConst);
15536 
15537   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15538   // we find one that is.
15539   S = getNonFieldDeclScope(S);
15540 
15541   // Verify that there isn't already something declared with this name in this
15542   // scope.
15543   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15544                                          ForRedeclaration);
15545   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15546     // Maybe we will complain about the shadowed template parameter.
15547     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15548     // Just pretend that we didn't see the previous declaration.
15549     PrevDecl = nullptr;
15550   }
15551 
15552   // C++ [class.mem]p15:
15553   // If T is the name of a class, then each of the following shall have a name
15554   // different from T:
15555   // - every enumerator of every member of class T that is an unscoped
15556   // enumerated type
15557   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15558     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15559                             DeclarationNameInfo(Id, IdLoc));
15560 
15561   EnumConstantDecl *New =
15562     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15563   if (!New)
15564     return nullptr;
15565 
15566   if (PrevDecl) {
15567     // When in C++, we may get a TagDecl with the same name; in this case the
15568     // enum constant will 'hide' the tag.
15569     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15570            "Received TagDecl when not in C++!");
15571     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15572         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15573       if (isa<EnumConstantDecl>(PrevDecl))
15574         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15575       else
15576         Diag(IdLoc, diag::err_redefinition) << Id;
15577       notePreviousDefinition(PrevDecl, IdLoc);
15578       return nullptr;
15579     }
15580   }
15581 
15582   // Process attributes.
15583   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15584   AddPragmaAttributes(S, New);
15585 
15586   // Register this decl in the current scope stack.
15587   New->setAccess(TheEnumDecl->getAccess());
15588   PushOnScopeChains(New, S);
15589 
15590   ActOnDocumentableDecl(New);
15591 
15592   return New;
15593 }
15594 
15595 // Returns true when the enum initial expression does not trigger the
15596 // duplicate enum warning.  A few common cases are exempted as follows:
15597 // Element2 = Element1
15598 // Element2 = Element1 + 1
15599 // Element2 = Element1 - 1
15600 // Where Element2 and Element1 are from the same enum.
15601 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15602   Expr *InitExpr = ECD->getInitExpr();
15603   if (!InitExpr)
15604     return true;
15605   InitExpr = InitExpr->IgnoreImpCasts();
15606 
15607   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15608     if (!BO->isAdditiveOp())
15609       return true;
15610     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15611     if (!IL)
15612       return true;
15613     if (IL->getValue() != 1)
15614       return true;
15615 
15616     InitExpr = BO->getLHS();
15617   }
15618 
15619   // This checks if the elements are from the same enum.
15620   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15621   if (!DRE)
15622     return true;
15623 
15624   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15625   if (!EnumConstant)
15626     return true;
15627 
15628   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15629       Enum)
15630     return true;
15631 
15632   return false;
15633 }
15634 
15635 namespace {
15636 struct DupKey {
15637   int64_t val;
15638   bool isTombstoneOrEmptyKey;
15639   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15640     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15641 };
15642 
15643 static DupKey GetDupKey(const llvm::APSInt& Val) {
15644   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15645                 false);
15646 }
15647 
15648 struct DenseMapInfoDupKey {
15649   static DupKey getEmptyKey() { return DupKey(0, true); }
15650   static DupKey getTombstoneKey() { return DupKey(1, true); }
15651   static unsigned getHashValue(const DupKey Key) {
15652     return (unsigned)(Key.val * 37);
15653   }
15654   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15655     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15656            LHS.val == RHS.val;
15657   }
15658 };
15659 } // end anonymous namespace
15660 
15661 // Emits a warning when an element is implicitly set a value that
15662 // a previous element has already been set to.
15663 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15664                                         EnumDecl *Enum,
15665                                         QualType EnumType) {
15666   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15667     return;
15668   // Avoid anonymous enums
15669   if (!Enum->getIdentifier())
15670     return;
15671 
15672   // Only check for small enums.
15673   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15674     return;
15675 
15676   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15677   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15678 
15679   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15680   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15681           ValueToVectorMap;
15682 
15683   DuplicatesVector DupVector;
15684   ValueToVectorMap EnumMap;
15685 
15686   // Populate the EnumMap with all values represented by enum constants without
15687   // an initialier.
15688   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15689     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15690 
15691     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15692     // this constant.  Skip this enum since it may be ill-formed.
15693     if (!ECD) {
15694       return;
15695     }
15696 
15697     if (ECD->getInitExpr())
15698       continue;
15699 
15700     DupKey Key = GetDupKey(ECD->getInitVal());
15701     DeclOrVector &Entry = EnumMap[Key];
15702 
15703     // First time encountering this value.
15704     if (Entry.isNull())
15705       Entry = ECD;
15706   }
15707 
15708   // Create vectors for any values that has duplicates.
15709   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15710     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15711     if (!ValidDuplicateEnum(ECD, Enum))
15712       continue;
15713 
15714     DupKey Key = GetDupKey(ECD->getInitVal());
15715 
15716     DeclOrVector& Entry = EnumMap[Key];
15717     if (Entry.isNull())
15718       continue;
15719 
15720     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15721       // Ensure constants are different.
15722       if (D == ECD)
15723         continue;
15724 
15725       // Create new vector and push values onto it.
15726       ECDVector *Vec = new ECDVector();
15727       Vec->push_back(D);
15728       Vec->push_back(ECD);
15729 
15730       // Update entry to point to the duplicates vector.
15731       Entry = Vec;
15732 
15733       // Store the vector somewhere we can consult later for quick emission of
15734       // diagnostics.
15735       DupVector.push_back(Vec);
15736       continue;
15737     }
15738 
15739     ECDVector *Vec = Entry.get<ECDVector*>();
15740     // Make sure constants are not added more than once.
15741     if (*Vec->begin() == ECD)
15742       continue;
15743 
15744     Vec->push_back(ECD);
15745   }
15746 
15747   // Emit diagnostics.
15748   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15749                                   DupVectorEnd = DupVector.end();
15750        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15751     ECDVector *Vec = *DupVectorIter;
15752     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15753 
15754     // Emit warning for one enum constant.
15755     ECDVector::iterator I = Vec->begin();
15756     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15757       << (*I)->getName() << (*I)->getInitVal().toString(10)
15758       << (*I)->getSourceRange();
15759     ++I;
15760 
15761     // Emit one note for each of the remaining enum constants with
15762     // the same value.
15763     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15764       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15765         << (*I)->getName() << (*I)->getInitVal().toString(10)
15766         << (*I)->getSourceRange();
15767     delete Vec;
15768   }
15769 }
15770 
15771 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15772                              bool AllowMask) const {
15773   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15774   assert(ED->isCompleteDefinition() && "expected enum definition");
15775 
15776   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15777   llvm::APInt &FlagBits = R.first->second;
15778 
15779   if (R.second) {
15780     for (auto *E : ED->enumerators()) {
15781       const auto &EVal = E->getInitVal();
15782       // Only single-bit enumerators introduce new flag values.
15783       if (EVal.isPowerOf2())
15784         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15785     }
15786   }
15787 
15788   // A value is in a flag enum if either its bits are a subset of the enum's
15789   // flag bits (the first condition) or we are allowing masks and the same is
15790   // true of its complement (the second condition). When masks are allowed, we
15791   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15792   //
15793   // While it's true that any value could be used as a mask, the assumption is
15794   // that a mask will have all of the insignificant bits set. Anything else is
15795   // likely a logic error.
15796   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15797   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15798 }
15799 
15800 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15801                          Decl *EnumDeclX,
15802                          ArrayRef<Decl *> Elements,
15803                          Scope *S, AttributeList *Attr) {
15804   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15805   QualType EnumType = Context.getTypeDeclType(Enum);
15806 
15807   if (Attr)
15808     ProcessDeclAttributeList(S, Enum, Attr);
15809 
15810   if (Enum->isDependentType()) {
15811     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15812       EnumConstantDecl *ECD =
15813         cast_or_null<EnumConstantDecl>(Elements[i]);
15814       if (!ECD) continue;
15815 
15816       ECD->setType(EnumType);
15817     }
15818 
15819     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15820     return;
15821   }
15822 
15823   // TODO: If the result value doesn't fit in an int, it must be a long or long
15824   // long value.  ISO C does not support this, but GCC does as an extension,
15825   // emit a warning.
15826   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15827   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15828   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15829 
15830   // Verify that all the values are okay, compute the size of the values, and
15831   // reverse the list.
15832   unsigned NumNegativeBits = 0;
15833   unsigned NumPositiveBits = 0;
15834 
15835   // Keep track of whether all elements have type int.
15836   bool AllElementsInt = true;
15837 
15838   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15839     EnumConstantDecl *ECD =
15840       cast_or_null<EnumConstantDecl>(Elements[i]);
15841     if (!ECD) continue;  // Already issued a diagnostic.
15842 
15843     const llvm::APSInt &InitVal = ECD->getInitVal();
15844 
15845     // Keep track of the size of positive and negative values.
15846     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15847       NumPositiveBits = std::max(NumPositiveBits,
15848                                  (unsigned)InitVal.getActiveBits());
15849     else
15850       NumNegativeBits = std::max(NumNegativeBits,
15851                                  (unsigned)InitVal.getMinSignedBits());
15852 
15853     // Keep track of whether every enum element has type int (very commmon).
15854     if (AllElementsInt)
15855       AllElementsInt = ECD->getType() == Context.IntTy;
15856   }
15857 
15858   // Figure out the type that should be used for this enum.
15859   QualType BestType;
15860   unsigned BestWidth;
15861 
15862   // C++0x N3000 [conv.prom]p3:
15863   //   An rvalue of an unscoped enumeration type whose underlying
15864   //   type is not fixed can be converted to an rvalue of the first
15865   //   of the following types that can represent all the values of
15866   //   the enumeration: int, unsigned int, long int, unsigned long
15867   //   int, long long int, or unsigned long long int.
15868   // C99 6.4.4.3p2:
15869   //   An identifier declared as an enumeration constant has type int.
15870   // The C99 rule is modified by a gcc extension
15871   QualType BestPromotionType;
15872 
15873   bool Packed = Enum->hasAttr<PackedAttr>();
15874   // -fshort-enums is the equivalent to specifying the packed attribute on all
15875   // enum definitions.
15876   if (LangOpts.ShortEnums)
15877     Packed = true;
15878 
15879   if (Enum->isFixed()) {
15880     BestType = Enum->getIntegerType();
15881     if (BestType->isPromotableIntegerType())
15882       BestPromotionType = Context.getPromotedIntegerType(BestType);
15883     else
15884       BestPromotionType = BestType;
15885 
15886     BestWidth = Context.getIntWidth(BestType);
15887   }
15888   else if (NumNegativeBits) {
15889     // If there is a negative value, figure out the smallest integer type (of
15890     // int/long/longlong) that fits.
15891     // If it's packed, check also if it fits a char or a short.
15892     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15893       BestType = Context.SignedCharTy;
15894       BestWidth = CharWidth;
15895     } else if (Packed && NumNegativeBits <= ShortWidth &&
15896                NumPositiveBits < ShortWidth) {
15897       BestType = Context.ShortTy;
15898       BestWidth = ShortWidth;
15899     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15900       BestType = Context.IntTy;
15901       BestWidth = IntWidth;
15902     } else {
15903       BestWidth = Context.getTargetInfo().getLongWidth();
15904 
15905       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15906         BestType = Context.LongTy;
15907       } else {
15908         BestWidth = Context.getTargetInfo().getLongLongWidth();
15909 
15910         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15911           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15912         BestType = Context.LongLongTy;
15913       }
15914     }
15915     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15916   } else {
15917     // If there is no negative value, figure out the smallest type that fits
15918     // all of the enumerator values.
15919     // If it's packed, check also if it fits a char or a short.
15920     if (Packed && NumPositiveBits <= CharWidth) {
15921       BestType = Context.UnsignedCharTy;
15922       BestPromotionType = Context.IntTy;
15923       BestWidth = CharWidth;
15924     } else if (Packed && NumPositiveBits <= ShortWidth) {
15925       BestType = Context.UnsignedShortTy;
15926       BestPromotionType = Context.IntTy;
15927       BestWidth = ShortWidth;
15928     } else if (NumPositiveBits <= IntWidth) {
15929       BestType = Context.UnsignedIntTy;
15930       BestWidth = IntWidth;
15931       BestPromotionType
15932         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15933                            ? Context.UnsignedIntTy : Context.IntTy;
15934     } else if (NumPositiveBits <=
15935                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15936       BestType = Context.UnsignedLongTy;
15937       BestPromotionType
15938         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15939                            ? Context.UnsignedLongTy : Context.LongTy;
15940     } else {
15941       BestWidth = Context.getTargetInfo().getLongLongWidth();
15942       assert(NumPositiveBits <= BestWidth &&
15943              "How could an initializer get larger than ULL?");
15944       BestType = Context.UnsignedLongLongTy;
15945       BestPromotionType
15946         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15947                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15948     }
15949   }
15950 
15951   // Loop over all of the enumerator constants, changing their types to match
15952   // the type of the enum if needed.
15953   for (auto *D : Elements) {
15954     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15955     if (!ECD) continue;  // Already issued a diagnostic.
15956 
15957     // Standard C says the enumerators have int type, but we allow, as an
15958     // extension, the enumerators to be larger than int size.  If each
15959     // enumerator value fits in an int, type it as an int, otherwise type it the
15960     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15961     // that X has type 'int', not 'unsigned'.
15962 
15963     // Determine whether the value fits into an int.
15964     llvm::APSInt InitVal = ECD->getInitVal();
15965 
15966     // If it fits into an integer type, force it.  Otherwise force it to match
15967     // the enum decl type.
15968     QualType NewTy;
15969     unsigned NewWidth;
15970     bool NewSign;
15971     if (!getLangOpts().CPlusPlus &&
15972         !Enum->isFixed() &&
15973         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15974       NewTy = Context.IntTy;
15975       NewWidth = IntWidth;
15976       NewSign = true;
15977     } else if (ECD->getType() == BestType) {
15978       // Already the right type!
15979       if (getLangOpts().CPlusPlus)
15980         // C++ [dcl.enum]p4: Following the closing brace of an
15981         // enum-specifier, each enumerator has the type of its
15982         // enumeration.
15983         ECD->setType(EnumType);
15984       continue;
15985     } else {
15986       NewTy = BestType;
15987       NewWidth = BestWidth;
15988       NewSign = BestType->isSignedIntegerOrEnumerationType();
15989     }
15990 
15991     // Adjust the APSInt value.
15992     InitVal = InitVal.extOrTrunc(NewWidth);
15993     InitVal.setIsSigned(NewSign);
15994     ECD->setInitVal(InitVal);
15995 
15996     // Adjust the Expr initializer and type.
15997     if (ECD->getInitExpr() &&
15998         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15999       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16000                                                 CK_IntegralCast,
16001                                                 ECD->getInitExpr(),
16002                                                 /*base paths*/ nullptr,
16003                                                 VK_RValue));
16004     if (getLangOpts().CPlusPlus)
16005       // C++ [dcl.enum]p4: Following the closing brace of an
16006       // enum-specifier, each enumerator has the type of its
16007       // enumeration.
16008       ECD->setType(EnumType);
16009     else
16010       ECD->setType(NewTy);
16011   }
16012 
16013   Enum->completeDefinition(BestType, BestPromotionType,
16014                            NumPositiveBits, NumNegativeBits);
16015 
16016   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16017 
16018   if (Enum->isClosedFlag()) {
16019     for (Decl *D : Elements) {
16020       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16021       if (!ECD) continue;  // Already issued a diagnostic.
16022 
16023       llvm::APSInt InitVal = ECD->getInitVal();
16024       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16025           !IsValueInFlagEnum(Enum, InitVal, true))
16026         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16027           << ECD << Enum;
16028     }
16029   }
16030 
16031   // Now that the enum type is defined, ensure it's not been underaligned.
16032   if (Enum->hasAttrs())
16033     CheckAlignasUnderalignment(Enum);
16034 }
16035 
16036 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16037                                   SourceLocation StartLoc,
16038                                   SourceLocation EndLoc) {
16039   StringLiteral *AsmString = cast<StringLiteral>(expr);
16040 
16041   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16042                                                    AsmString, StartLoc,
16043                                                    EndLoc);
16044   CurContext->addDecl(New);
16045   return New;
16046 }
16047 
16048 static void checkModuleImportContext(Sema &S, Module *M,
16049                                      SourceLocation ImportLoc, DeclContext *DC,
16050                                      bool FromInclude = false) {
16051   SourceLocation ExternCLoc;
16052 
16053   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16054     switch (LSD->getLanguage()) {
16055     case LinkageSpecDecl::lang_c:
16056       if (ExternCLoc.isInvalid())
16057         ExternCLoc = LSD->getLocStart();
16058       break;
16059     case LinkageSpecDecl::lang_cxx:
16060       break;
16061     }
16062     DC = LSD->getParent();
16063   }
16064 
16065   while (isa<LinkageSpecDecl>(DC))
16066     DC = DC->getParent();
16067 
16068   if (!isa<TranslationUnitDecl>(DC)) {
16069     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16070                           ? diag::ext_module_import_not_at_top_level_noop
16071                           : diag::err_module_import_not_at_top_level_fatal)
16072         << M->getFullModuleName() << DC;
16073     S.Diag(cast<Decl>(DC)->getLocStart(),
16074            diag::note_module_import_not_at_top_level) << DC;
16075   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16076     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16077       << M->getFullModuleName();
16078     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16079   }
16080 }
16081 
16082 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16083                                            SourceLocation ModuleLoc,
16084                                            ModuleDeclKind MDK,
16085                                            ModuleIdPath Path) {
16086   assert(getLangOpts().ModulesTS &&
16087          "should only have module decl in modules TS");
16088 
16089   // A module implementation unit requires that we are not compiling a module
16090   // of any kind. A module interface unit requires that we are not compiling a
16091   // module map.
16092   switch (getLangOpts().getCompilingModule()) {
16093   case LangOptions::CMK_None:
16094     // It's OK to compile a module interface as a normal translation unit.
16095     break;
16096 
16097   case LangOptions::CMK_ModuleInterface:
16098     if (MDK != ModuleDeclKind::Implementation)
16099       break;
16100 
16101     // We were asked to compile a module interface unit but this is a module
16102     // implementation unit. That indicates the 'export' is missing.
16103     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16104       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16105     break;
16106 
16107   case LangOptions::CMK_ModuleMap:
16108     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16109     return nullptr;
16110   }
16111 
16112   // FIXME: Most of this work should be done by the preprocessor rather than
16113   // here, in order to support macro import.
16114 
16115   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16116   // modules, the dots here are just another character that can appear in a
16117   // module name.
16118   std::string ModuleName;
16119   for (auto &Piece : Path) {
16120     if (!ModuleName.empty())
16121       ModuleName += ".";
16122     ModuleName += Piece.first->getName();
16123   }
16124 
16125   // FIXME: If we've already seen a module-declaration, report an error.
16126 
16127   // If a module name was explicitly specified on the command line, it must be
16128   // correct.
16129   if (!getLangOpts().CurrentModule.empty() &&
16130       getLangOpts().CurrentModule != ModuleName) {
16131     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16132         << SourceRange(Path.front().second, Path.back().second)
16133         << getLangOpts().CurrentModule;
16134     return nullptr;
16135   }
16136   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16137 
16138   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16139   Module *Mod;
16140 
16141   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16142 
16143   switch (MDK) {
16144   case ModuleDeclKind::Module: {
16145     // We can't have parsed or imported a definition of this module or parsed a
16146     // module map defining it already.
16147     if (auto *M = Map.findModule(ModuleName)) {
16148       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16149       if (M->DefinitionLoc.isValid())
16150         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16151       else if (const auto *FE = M->getASTFile())
16152         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16153             << FE->getName();
16154       return nullptr;
16155     }
16156 
16157     // Create a Module for the module that we're defining.
16158     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16159                                            ModuleScopes.front().Module);
16160     assert(Mod && "module creation should not fail");
16161     break;
16162   }
16163 
16164   case ModuleDeclKind::Partition:
16165     // FIXME: Check we are in a submodule of the named module.
16166     return nullptr;
16167 
16168   case ModuleDeclKind::Implementation:
16169     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16170         PP.getIdentifierInfo(ModuleName), Path[0].second);
16171     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16172                                        /*IsIncludeDirective=*/false);
16173     if (!Mod)
16174       return nullptr;
16175     break;
16176   }
16177 
16178   // Switch from the global module to the named module.
16179   ModuleScopes.back().Module = Mod;
16180   VisibleModules.setVisible(Mod, ModuleLoc);
16181 
16182   // From now on, we have an owning module for all declarations we see.
16183   // However, those declarations are module-private unless explicitly
16184   // exported.
16185   auto *TU = Context.getTranslationUnitDecl();
16186   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16187   TU->setLocalOwningModule(Mod);
16188 
16189   // FIXME: Create a ModuleDecl.
16190   return nullptr;
16191 }
16192 
16193 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16194                                    SourceLocation ImportLoc,
16195                                    ModuleIdPath Path) {
16196   Module *Mod =
16197       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16198                                    /*IsIncludeDirective=*/false);
16199   if (!Mod)
16200     return true;
16201 
16202   VisibleModules.setVisible(Mod, ImportLoc);
16203 
16204   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16205 
16206   // FIXME: we should support importing a submodule within a different submodule
16207   // of the same top-level module. Until we do, make it an error rather than
16208   // silently ignoring the import.
16209   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16210   // warn on a redundant import of the current module?
16211   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16212       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16213     Diag(ImportLoc, getLangOpts().isCompilingModule()
16214                         ? diag::err_module_self_import
16215                         : diag::err_module_import_in_implementation)
16216         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16217 
16218   SmallVector<SourceLocation, 2> IdentifierLocs;
16219   Module *ModCheck = Mod;
16220   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16221     // If we've run out of module parents, just drop the remaining identifiers.
16222     // We need the length to be consistent.
16223     if (!ModCheck)
16224       break;
16225     ModCheck = ModCheck->Parent;
16226 
16227     IdentifierLocs.push_back(Path[I].second);
16228   }
16229 
16230   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16231   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16232                                           Mod, IdentifierLocs);
16233   if (!ModuleScopes.empty())
16234     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16235   TU->addDecl(Import);
16236   return Import;
16237 }
16238 
16239 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16240   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16241   BuildModuleInclude(DirectiveLoc, Mod);
16242 }
16243 
16244 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16245   // Determine whether we're in the #include buffer for a module. The #includes
16246   // in that buffer do not qualify as module imports; they're just an
16247   // implementation detail of us building the module.
16248   //
16249   // FIXME: Should we even get ActOnModuleInclude calls for those?
16250   bool IsInModuleIncludes =
16251       TUKind == TU_Module &&
16252       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16253 
16254   bool ShouldAddImport = !IsInModuleIncludes;
16255 
16256   // If this module import was due to an inclusion directive, create an
16257   // implicit import declaration to capture it in the AST.
16258   if (ShouldAddImport) {
16259     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16260     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16261                                                      DirectiveLoc, Mod,
16262                                                      DirectiveLoc);
16263     if (!ModuleScopes.empty())
16264       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16265     TU->addDecl(ImportD);
16266     Consumer.HandleImplicitImportDecl(ImportD);
16267   }
16268 
16269   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16270   VisibleModules.setVisible(Mod, DirectiveLoc);
16271 }
16272 
16273 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16274   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16275 
16276   ModuleScopes.push_back({});
16277   ModuleScopes.back().Module = Mod;
16278   if (getLangOpts().ModulesLocalVisibility)
16279     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16280 
16281   VisibleModules.setVisible(Mod, DirectiveLoc);
16282 
16283   // The enclosing context is now part of this module.
16284   // FIXME: Consider creating a child DeclContext to hold the entities
16285   // lexically within the module.
16286   if (getLangOpts().trackLocalOwningModule()) {
16287     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16288       cast<Decl>(DC)->setModuleOwnershipKind(
16289           getLangOpts().ModulesLocalVisibility
16290               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16291               : Decl::ModuleOwnershipKind::Visible);
16292       cast<Decl>(DC)->setLocalOwningModule(Mod);
16293     }
16294   }
16295 }
16296 
16297 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16298   if (getLangOpts().ModulesLocalVisibility) {
16299     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16300     // Leaving a module hides namespace names, so our visible namespace cache
16301     // is now out of date.
16302     VisibleNamespaceCache.clear();
16303   }
16304 
16305   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16306          "left the wrong module scope");
16307   ModuleScopes.pop_back();
16308 
16309   // We got to the end of processing a local module. Create an
16310   // ImportDecl as we would for an imported module.
16311   FileID File = getSourceManager().getFileID(EomLoc);
16312   SourceLocation DirectiveLoc;
16313   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16314     // We reached the end of a #included module header. Use the #include loc.
16315     assert(File != getSourceManager().getMainFileID() &&
16316            "end of submodule in main source file");
16317     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16318   } else {
16319     // We reached an EOM pragma. Use the pragma location.
16320     DirectiveLoc = EomLoc;
16321   }
16322   BuildModuleInclude(DirectiveLoc, Mod);
16323 
16324   // Any further declarations are in whatever module we returned to.
16325   if (getLangOpts().trackLocalOwningModule()) {
16326     // The parser guarantees that this is the same context that we entered
16327     // the module within.
16328     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16329       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16330       if (!getCurrentModule())
16331         cast<Decl>(DC)->setModuleOwnershipKind(
16332             Decl::ModuleOwnershipKind::Unowned);
16333     }
16334   }
16335 }
16336 
16337 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16338                                                       Module *Mod) {
16339   // Bail if we're not allowed to implicitly import a module here.
16340   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16341       VisibleModules.isVisible(Mod))
16342     return;
16343 
16344   // Create the implicit import declaration.
16345   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16346   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16347                                                    Loc, Mod, Loc);
16348   TU->addDecl(ImportD);
16349   Consumer.HandleImplicitImportDecl(ImportD);
16350 
16351   // Make the module visible.
16352   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16353   VisibleModules.setVisible(Mod, Loc);
16354 }
16355 
16356 /// We have parsed the start of an export declaration, including the '{'
16357 /// (if present).
16358 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16359                                  SourceLocation LBraceLoc) {
16360   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16361 
16362   // C++ Modules TS draft:
16363   //   An export-declaration shall appear in the purview of a module other than
16364   //   the global module.
16365   if (ModuleScopes.empty() ||
16366       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16367     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16368 
16369   //   An export-declaration [...] shall not contain more than one
16370   //   export keyword.
16371   //
16372   // The intent here is that an export-declaration cannot appear within another
16373   // export-declaration.
16374   if (D->isExported())
16375     Diag(ExportLoc, diag::err_export_within_export);
16376 
16377   CurContext->addDecl(D);
16378   PushDeclContext(S, D);
16379   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16380   return D;
16381 }
16382 
16383 /// Complete the definition of an export declaration.
16384 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16385   auto *ED = cast<ExportDecl>(D);
16386   if (RBraceLoc.isValid())
16387     ED->setRBraceLoc(RBraceLoc);
16388 
16389   // FIXME: Diagnose export of internal-linkage declaration (including
16390   // anonymous namespace).
16391 
16392   PopDeclContext();
16393   return D;
16394 }
16395 
16396 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16397                                       IdentifierInfo* AliasName,
16398                                       SourceLocation PragmaLoc,
16399                                       SourceLocation NameLoc,
16400                                       SourceLocation AliasNameLoc) {
16401   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16402                                          LookupOrdinaryName);
16403   AsmLabelAttr *Attr =
16404       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16405 
16406   // If a declaration that:
16407   // 1) declares a function or a variable
16408   // 2) has external linkage
16409   // already exists, add a label attribute to it.
16410   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16411     if (isDeclExternC(PrevDecl))
16412       PrevDecl->addAttr(Attr);
16413     else
16414       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16415           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16416   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16417   } else
16418     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16419 }
16420 
16421 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16422                              SourceLocation PragmaLoc,
16423                              SourceLocation NameLoc) {
16424   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16425 
16426   if (PrevDecl) {
16427     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16428   } else {
16429     (void)WeakUndeclaredIdentifiers.insert(
16430       std::pair<IdentifierInfo*,WeakInfo>
16431         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16432   }
16433 }
16434 
16435 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16436                                 IdentifierInfo* AliasName,
16437                                 SourceLocation PragmaLoc,
16438                                 SourceLocation NameLoc,
16439                                 SourceLocation AliasNameLoc) {
16440   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16441                                     LookupOrdinaryName);
16442   WeakInfo W = WeakInfo(Name, NameLoc);
16443 
16444   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16445     if (!PrevDecl->hasAttr<AliasAttr>())
16446       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16447         DeclApplyPragmaWeak(TUScope, ND, W);
16448   } else {
16449     (void)WeakUndeclaredIdentifiers.insert(
16450       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16451   }
16452 }
16453 
16454 Decl *Sema::getObjCDeclContext() const {
16455   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16456 }
16457