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().CPlusPlus17 && !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 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1452 /// have compatible owning modules.
1453 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1454   // FIXME: The Modules TS is not clear about how friend declarations are
1455   // to be treated. It's not meaningful to have different owning modules for
1456   // linkage in redeclarations of the same entity, so for now allow the
1457   // redeclaration and change the owning modules to match.
1458   if (New->getFriendObjectKind() &&
1459       Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1460     New->setLocalOwningModule(Old->getOwningModule());
1461     makeMergedDefinitionVisible(New);
1462     return false;
1463   }
1464 
1465   Module *NewM = New->getOwningModule();
1466   Module *OldM = Old->getOwningModule();
1467   if (NewM == OldM)
1468     return false;
1469 
1470   // FIXME: Check proclaimed-ownership-declarations here too.
1471   bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472   bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473   if (NewIsModuleInterface || OldIsModuleInterface) {
1474     // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475     //   if a declaration of D [...] appears in the purview of a module, all
1476     //   other such declarations shall appear in the purview of the same module
1477     Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478       << New
1479       << NewIsModuleInterface
1480       << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481       << OldIsModuleInterface
1482       << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483     Diag(Old->getLocation(), diag::note_previous_declaration);
1484     New->setInvalidDecl();
1485     return true;
1486   }
1487 
1488   return false;
1489 }
1490 
1491 static bool isUsingDecl(NamedDecl *D) {
1492   return isa<UsingShadowDecl>(D) ||
1493          isa<UnresolvedUsingTypenameDecl>(D) ||
1494          isa<UnresolvedUsingValueDecl>(D);
1495 }
1496 
1497 /// Removes using shadow declarations from the lookup results.
1498 static void RemoveUsingDecls(LookupResult &R) {
1499   LookupResult::Filter F = R.makeFilter();
1500   while (F.hasNext())
1501     if (isUsingDecl(F.next()))
1502       F.erase();
1503 
1504   F.done();
1505 }
1506 
1507 /// \brief Check for this common pattern:
1508 /// @code
1509 /// class S {
1510 ///   S(const S&); // DO NOT IMPLEMENT
1511 ///   void operator=(const S&); // DO NOT IMPLEMENT
1512 /// };
1513 /// @endcode
1514 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1515   // FIXME: Should check for private access too but access is set after we get
1516   // the decl here.
1517   if (D->doesThisDeclarationHaveABody())
1518     return false;
1519 
1520   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521     return CD->isCopyConstructor();
1522   return D->isCopyAssignmentOperator();
1523 }
1524 
1525 // We need this to handle
1526 //
1527 // typedef struct {
1528 //   void *foo() { return 0; }
1529 // } A;
1530 //
1531 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1532 // for example. If 'A', foo will have external linkage. If we have '*A',
1533 // foo will have no linkage. Since we can't know until we get to the end
1534 // of the typedef, this function finds out if D might have non-external linkage.
1535 // Callers should verify at the end of the TU if it D has external linkage or
1536 // not.
1537 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1538   const DeclContext *DC = D->getDeclContext();
1539   while (!DC->isTranslationUnit()) {
1540     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1541       if (!RD->hasNameForLinkage())
1542         return true;
1543     }
1544     DC = DC->getParent();
1545   }
1546 
1547   return !D->isExternallyVisible();
1548 }
1549 
1550 // FIXME: This needs to be refactored; some other isInMainFile users want
1551 // these semantics.
1552 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1553   if (S.TUKind != TU_Complete)
1554     return false;
1555   return S.SourceMgr.isInMainFile(Loc);
1556 }
1557 
1558 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1559   assert(D);
1560 
1561   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1562     return false;
1563 
1564   // Ignore all entities declared within templates, and out-of-line definitions
1565   // of members of class templates.
1566   if (D->getDeclContext()->isDependentContext() ||
1567       D->getLexicalDeclContext()->isDependentContext())
1568     return false;
1569 
1570   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1571     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1572       return false;
1573     // A non-out-of-line declaration of a member specialization was implicitly
1574     // instantiated; it's the out-of-line declaration that we're interested in.
1575     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1576         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1577       return false;
1578 
1579     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1580       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1581         return false;
1582     } else {
1583       // 'static inline' functions are defined in headers; don't warn.
1584       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585         return false;
1586     }
1587 
1588     if (FD->doesThisDeclarationHaveABody() &&
1589         Context.DeclMustBeEmitted(FD))
1590       return false;
1591   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592     // Constants and utility variables are defined in headers with internal
1593     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1594     // like "inline".)
1595     if (!isMainFileLoc(*this, VD->getLocation()))
1596       return false;
1597 
1598     if (Context.DeclMustBeEmitted(VD))
1599       return false;
1600 
1601     if (VD->isStaticDataMember() &&
1602         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1603       return false;
1604     if (VD->isStaticDataMember() &&
1605         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1606         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1607       return false;
1608 
1609     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1610       return false;
1611   } else {
1612     return false;
1613   }
1614 
1615   // Only warn for unused decls internal to the translation unit.
1616   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1617   // for inline functions defined in the main source file, for instance.
1618   return mightHaveNonExternalLinkage(D);
1619 }
1620 
1621 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1622   if (!D)
1623     return;
1624 
1625   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1626     const FunctionDecl *First = FD->getFirstDecl();
1627     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1628       return; // First should already be in the vector.
1629   }
1630 
1631   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632     const VarDecl *First = VD->getFirstDecl();
1633     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1634       return; // First should already be in the vector.
1635   }
1636 
1637   if (ShouldWarnIfUnusedFileScopedDecl(D))
1638     UnusedFileScopedDecls.push_back(D);
1639 }
1640 
1641 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1642   if (D->isInvalidDecl())
1643     return false;
1644 
1645   bool Referenced = false;
1646   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1647     // For a decomposition declaration, warn if none of the bindings are
1648     // referenced, instead of if the variable itself is referenced (which
1649     // it is, by the bindings' expressions).
1650     for (auto *BD : DD->bindings()) {
1651       if (BD->isReferenced()) {
1652         Referenced = true;
1653         break;
1654       }
1655     }
1656   } else if (!D->getDeclName()) {
1657     return false;
1658   } else if (D->isReferenced() || D->isUsed()) {
1659     Referenced = true;
1660   }
1661 
1662   if (Referenced || D->hasAttr<UnusedAttr>() ||
1663       D->hasAttr<ObjCPreciseLifetimeAttr>())
1664     return false;
1665 
1666   if (isa<LabelDecl>(D))
1667     return true;
1668 
1669   // Except for labels, we only care about unused decls that are local to
1670   // functions.
1671   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1672   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1673     // For dependent types, the diagnostic is deferred.
1674     WithinFunction =
1675         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1676   if (!WithinFunction)
1677     return false;
1678 
1679   if (isa<TypedefNameDecl>(D))
1680     return true;
1681 
1682   // White-list anything that isn't a local variable.
1683   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1684     return false;
1685 
1686   // Types of valid local variables should be complete, so this should succeed.
1687   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1688 
1689     // White-list anything with an __attribute__((unused)) type.
1690     const auto *Ty = VD->getType().getTypePtr();
1691 
1692     // Only look at the outermost level of typedef.
1693     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1694       if (TT->getDecl()->hasAttr<UnusedAttr>())
1695         return false;
1696     }
1697 
1698     // If we failed to complete the type for some reason, or if the type is
1699     // dependent, don't diagnose the variable.
1700     if (Ty->isIncompleteType() || Ty->isDependentType())
1701       return false;
1702 
1703     // Look at the element type to ensure that the warning behaviour is
1704     // consistent for both scalars and arrays.
1705     Ty = Ty->getBaseElementTypeUnsafe();
1706 
1707     if (const TagType *TT = Ty->getAs<TagType>()) {
1708       const TagDecl *Tag = TT->getDecl();
1709       if (Tag->hasAttr<UnusedAttr>())
1710         return false;
1711 
1712       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1713         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1714           return false;
1715 
1716         if (const Expr *Init = VD->getInit()) {
1717           if (const ExprWithCleanups *Cleanups =
1718                   dyn_cast<ExprWithCleanups>(Init))
1719             Init = Cleanups->getSubExpr();
1720           const CXXConstructExpr *Construct =
1721             dyn_cast<CXXConstructExpr>(Init);
1722           if (Construct && !Construct->isElidable()) {
1723             CXXConstructorDecl *CD = Construct->getConstructor();
1724             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1725                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1726               return false;
1727           }
1728         }
1729       }
1730     }
1731 
1732     // TODO: __attribute__((unused)) templates?
1733   }
1734 
1735   return true;
1736 }
1737 
1738 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1739                                      FixItHint &Hint) {
1740   if (isa<LabelDecl>(D)) {
1741     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1742                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1743     if (AfterColon.isInvalid())
1744       return;
1745     Hint = FixItHint::CreateRemoval(CharSourceRange::
1746                                     getCharRange(D->getLocStart(), AfterColon));
1747   }
1748 }
1749 
1750 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1751   if (D->getTypeForDecl()->isDependentType())
1752     return;
1753 
1754   for (auto *TmpD : D->decls()) {
1755     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1756       DiagnoseUnusedDecl(T);
1757     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1758       DiagnoseUnusedNestedTypedefs(R);
1759   }
1760 }
1761 
1762 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1763 /// unless they are marked attr(unused).
1764 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1765   if (!ShouldDiagnoseUnusedDecl(D))
1766     return;
1767 
1768   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1769     // typedefs can be referenced later on, so the diagnostics are emitted
1770     // at end-of-translation-unit.
1771     UnusedLocalTypedefNameCandidates.insert(TD);
1772     return;
1773   }
1774 
1775   FixItHint Hint;
1776   GenerateFixForUnusedDecl(D, Context, Hint);
1777 
1778   unsigned DiagID;
1779   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1780     DiagID = diag::warn_unused_exception_param;
1781   else if (isa<LabelDecl>(D))
1782     DiagID = diag::warn_unused_label;
1783   else
1784     DiagID = diag::warn_unused_variable;
1785 
1786   Diag(D->getLocation(), DiagID) << D << Hint;
1787 }
1788 
1789 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1790   // Verify that we have no forward references left.  If so, there was a goto
1791   // or address of a label taken, but no definition of it.  Label fwd
1792   // definitions are indicated with a null substmt which is also not a resolved
1793   // MS inline assembly label name.
1794   bool Diagnose = false;
1795   if (L->isMSAsmLabel())
1796     Diagnose = !L->isResolvedMSAsmLabel();
1797   else
1798     Diagnose = L->getStmt() == nullptr;
1799   if (Diagnose)
1800     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1801 }
1802 
1803 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1804   S->mergeNRVOIntoParent();
1805 
1806   if (S->decl_empty()) return;
1807   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1808          "Scope shouldn't contain decls!");
1809 
1810   for (auto *TmpD : S->decls()) {
1811     assert(TmpD && "This decl didn't get pushed??");
1812 
1813     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1814     NamedDecl *D = cast<NamedDecl>(TmpD);
1815 
1816     // Diagnose unused variables in this scope.
1817     if (!S->hasUnrecoverableErrorOccurred()) {
1818       DiagnoseUnusedDecl(D);
1819       if (const auto *RD = dyn_cast<RecordDecl>(D))
1820         DiagnoseUnusedNestedTypedefs(RD);
1821     }
1822 
1823     if (!D->getDeclName()) continue;
1824 
1825     // If this was a forward reference to a label, verify it was defined.
1826     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1827       CheckPoppedLabel(LD, *this);
1828 
1829     // Remove this name from our lexical scope, and warn on it if we haven't
1830     // already.
1831     IdResolver.RemoveDecl(D);
1832     auto ShadowI = ShadowingDecls.find(D);
1833     if (ShadowI != ShadowingDecls.end()) {
1834       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1835         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1836             << D << FD << FD->getParent();
1837         Diag(FD->getLocation(), diag::note_previous_declaration);
1838       }
1839       ShadowingDecls.erase(ShadowI);
1840     }
1841   }
1842 }
1843 
1844 /// \brief Look for an Objective-C class in the translation unit.
1845 ///
1846 /// \param Id The name of the Objective-C class we're looking for. If
1847 /// typo-correction fixes this name, the Id will be updated
1848 /// to the fixed name.
1849 ///
1850 /// \param IdLoc The location of the name in the translation unit.
1851 ///
1852 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1853 /// if there is no class with the given name.
1854 ///
1855 /// \returns The declaration of the named Objective-C class, or NULL if the
1856 /// class could not be found.
1857 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1858                                               SourceLocation IdLoc,
1859                                               bool DoTypoCorrection) {
1860   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1861   // creation from this context.
1862   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1863 
1864   if (!IDecl && DoTypoCorrection) {
1865     // Perform typo correction at the given location, but only if we
1866     // find an Objective-C class name.
1867     if (TypoCorrection C = CorrectTypo(
1868             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1869             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1870             CTK_ErrorRecovery)) {
1871       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1872       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1873       Id = IDecl->getIdentifier();
1874     }
1875   }
1876   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1877   // This routine must always return a class definition, if any.
1878   if (Def && Def->getDefinition())
1879       Def = Def->getDefinition();
1880   return Def;
1881 }
1882 
1883 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1884 /// from S, where a non-field would be declared. This routine copes
1885 /// with the difference between C and C++ scoping rules in structs and
1886 /// unions. For example, the following code is well-formed in C but
1887 /// ill-formed in C++:
1888 /// @code
1889 /// struct S6 {
1890 ///   enum { BAR } e;
1891 /// };
1892 ///
1893 /// void test_S6() {
1894 ///   struct S6 a;
1895 ///   a.e = BAR;
1896 /// }
1897 /// @endcode
1898 /// For the declaration of BAR, this routine will return a different
1899 /// scope. The scope S will be the scope of the unnamed enumeration
1900 /// within S6. In C++, this routine will return the scope associated
1901 /// with S6, because the enumeration's scope is a transparent
1902 /// context but structures can contain non-field names. In C, this
1903 /// routine will return the translation unit scope, since the
1904 /// enumeration's scope is a transparent context and structures cannot
1905 /// contain non-field names.
1906 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1907   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1908          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1909          (S->isClassScope() && !getLangOpts().CPlusPlus))
1910     S = S->getParent();
1911   return S;
1912 }
1913 
1914 /// \brief Looks up the declaration of "struct objc_super" and
1915 /// saves it for later use in building builtin declaration of
1916 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1917 /// pre-existing declaration exists no action takes place.
1918 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1919                                         IdentifierInfo *II) {
1920   if (!II->isStr("objc_msgSendSuper"))
1921     return;
1922   ASTContext &Context = ThisSema.Context;
1923 
1924   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1925                       SourceLocation(), Sema::LookupTagName);
1926   ThisSema.LookupName(Result, S);
1927   if (Result.getResultKind() == LookupResult::Found)
1928     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1929       Context.setObjCSuperType(Context.getTagDeclType(TD));
1930 }
1931 
1932 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1933   switch (Error) {
1934   case ASTContext::GE_None:
1935     return "";
1936   case ASTContext::GE_Missing_stdio:
1937     return "stdio.h";
1938   case ASTContext::GE_Missing_setjmp:
1939     return "setjmp.h";
1940   case ASTContext::GE_Missing_ucontext:
1941     return "ucontext.h";
1942   }
1943   llvm_unreachable("unhandled error kind");
1944 }
1945 
1946 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1947 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1948 /// if we're creating this built-in in anticipation of redeclaring the
1949 /// built-in.
1950 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1951                                      Scope *S, bool ForRedeclaration,
1952                                      SourceLocation Loc) {
1953   LookupPredefedObjCSuperType(*this, S, II);
1954 
1955   ASTContext::GetBuiltinTypeError Error;
1956   QualType R = Context.GetBuiltinType(ID, Error);
1957   if (Error) {
1958     if (ForRedeclaration)
1959       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1960           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1961     return nullptr;
1962   }
1963 
1964   if (!ForRedeclaration &&
1965       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1966        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1967     Diag(Loc, diag::ext_implicit_lib_function_decl)
1968         << Context.BuiltinInfo.getName(ID) << R;
1969     if (Context.BuiltinInfo.getHeaderName(ID) &&
1970         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1971       Diag(Loc, diag::note_include_header_or_declare)
1972           << Context.BuiltinInfo.getHeaderName(ID)
1973           << Context.BuiltinInfo.getName(ID);
1974   }
1975 
1976   if (R.isNull())
1977     return nullptr;
1978 
1979   DeclContext *Parent = Context.getTranslationUnitDecl();
1980   if (getLangOpts().CPlusPlus) {
1981     LinkageSpecDecl *CLinkageDecl =
1982         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1983                                 LinkageSpecDecl::lang_c, false);
1984     CLinkageDecl->setImplicit();
1985     Parent->addDecl(CLinkageDecl);
1986     Parent = CLinkageDecl;
1987   }
1988 
1989   FunctionDecl *New = FunctionDecl::Create(Context,
1990                                            Parent,
1991                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1992                                            SC_Extern,
1993                                            false,
1994                                            R->isFunctionProtoType());
1995   New->setImplicit();
1996 
1997   // Create Decl objects for each parameter, adding them to the
1998   // FunctionDecl.
1999   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2000     SmallVector<ParmVarDecl*, 16> Params;
2001     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2002       ParmVarDecl *parm =
2003           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2004                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2005                               SC_None, nullptr);
2006       parm->setScopeInfo(0, i);
2007       Params.push_back(parm);
2008     }
2009     New->setParams(Params);
2010   }
2011 
2012   AddKnownFunctionAttributes(New);
2013   RegisterLocallyScopedExternCDecl(New, S);
2014 
2015   // TUScope is the translation-unit scope to insert this function into.
2016   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2017   // relate Scopes to DeclContexts, and probably eliminate CurContext
2018   // entirely, but we're not there yet.
2019   DeclContext *SavedContext = CurContext;
2020   CurContext = Parent;
2021   PushOnScopeChains(New, TUScope);
2022   CurContext = SavedContext;
2023   return New;
2024 }
2025 
2026 /// Typedef declarations don't have linkage, but they still denote the same
2027 /// entity if their types are the same.
2028 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2029 /// isSameEntity.
2030 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2031                                                      TypedefNameDecl *Decl,
2032                                                      LookupResult &Previous) {
2033   // This is only interesting when modules are enabled.
2034   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2035     return;
2036 
2037   // Empty sets are uninteresting.
2038   if (Previous.empty())
2039     return;
2040 
2041   LookupResult::Filter Filter = Previous.makeFilter();
2042   while (Filter.hasNext()) {
2043     NamedDecl *Old = Filter.next();
2044 
2045     // Non-hidden declarations are never ignored.
2046     if (S.isVisible(Old))
2047       continue;
2048 
2049     // Declarations of the same entity are not ignored, even if they have
2050     // different linkages.
2051     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2052       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2053                                 Decl->getUnderlyingType()))
2054         continue;
2055 
2056       // If both declarations give a tag declaration a typedef name for linkage
2057       // purposes, then they declare the same entity.
2058       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2059           Decl->getAnonDeclWithTypedefName())
2060         continue;
2061     }
2062 
2063     Filter.erase();
2064   }
2065 
2066   Filter.done();
2067 }
2068 
2069 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2070   QualType OldType;
2071   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2072     OldType = OldTypedef->getUnderlyingType();
2073   else
2074     OldType = Context.getTypeDeclType(Old);
2075   QualType NewType = New->getUnderlyingType();
2076 
2077   if (NewType->isVariablyModifiedType()) {
2078     // Must not redefine a typedef with a variably-modified type.
2079     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2080     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2081       << Kind << NewType;
2082     if (Old->getLocation().isValid())
2083       notePreviousDefinition(Old, New->getLocation());
2084     New->setInvalidDecl();
2085     return true;
2086   }
2087 
2088   if (OldType != NewType &&
2089       !OldType->isDependentType() &&
2090       !NewType->isDependentType() &&
2091       !Context.hasSameType(OldType, NewType)) {
2092     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2093     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2094       << Kind << NewType << OldType;
2095     if (Old->getLocation().isValid())
2096       notePreviousDefinition(Old, New->getLocation());
2097     New->setInvalidDecl();
2098     return true;
2099   }
2100   return false;
2101 }
2102 
2103 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2104 /// same name and scope as a previous declaration 'Old'.  Figure out
2105 /// how to resolve this situation, merging decls or emitting
2106 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2107 ///
2108 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2109                                 LookupResult &OldDecls) {
2110   // If the new decl is known invalid already, don't bother doing any
2111   // merging checks.
2112   if (New->isInvalidDecl()) return;
2113 
2114   // Allow multiple definitions for ObjC built-in typedefs.
2115   // FIXME: Verify the underlying types are equivalent!
2116   if (getLangOpts().ObjC1) {
2117     const IdentifierInfo *TypeID = New->getIdentifier();
2118     switch (TypeID->getLength()) {
2119     default: break;
2120     case 2:
2121       {
2122         if (!TypeID->isStr("id"))
2123           break;
2124         QualType T = New->getUnderlyingType();
2125         if (!T->isPointerType())
2126           break;
2127         if (!T->isVoidPointerType()) {
2128           QualType PT = T->getAs<PointerType>()->getPointeeType();
2129           if (!PT->isStructureType())
2130             break;
2131         }
2132         Context.setObjCIdRedefinitionType(T);
2133         // Install the built-in type for 'id', ignoring the current definition.
2134         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2135         return;
2136       }
2137     case 5:
2138       if (!TypeID->isStr("Class"))
2139         break;
2140       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2141       // Install the built-in type for 'Class', ignoring the current definition.
2142       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2143       return;
2144     case 3:
2145       if (!TypeID->isStr("SEL"))
2146         break;
2147       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2148       // Install the built-in type for 'SEL', ignoring the current definition.
2149       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2150       return;
2151     }
2152     // Fall through - the typedef name was not a builtin type.
2153   }
2154 
2155   // Verify the old decl was also a type.
2156   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2157   if (!Old) {
2158     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2159       << New->getDeclName();
2160 
2161     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2162     if (OldD->getLocation().isValid())
2163       notePreviousDefinition(OldD, New->getLocation());
2164 
2165     return New->setInvalidDecl();
2166   }
2167 
2168   // If the old declaration is invalid, just give up here.
2169   if (Old->isInvalidDecl())
2170     return New->setInvalidDecl();
2171 
2172   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2173     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2174     auto *NewTag = New->getAnonDeclWithTypedefName();
2175     NamedDecl *Hidden = nullptr;
2176     if (OldTag && NewTag &&
2177         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2178         !hasVisibleDefinition(OldTag, &Hidden)) {
2179       // There is a definition of this tag, but it is not visible. Use it
2180       // instead of our tag.
2181       New->setTypeForDecl(OldTD->getTypeForDecl());
2182       if (OldTD->isModed())
2183         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2184                                     OldTD->getUnderlyingType());
2185       else
2186         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2187 
2188       // Make the old tag definition visible.
2189       makeMergedDefinitionVisible(Hidden);
2190 
2191       // If this was an unscoped enumeration, yank all of its enumerators
2192       // out of the scope.
2193       if (isa<EnumDecl>(NewTag)) {
2194         Scope *EnumScope = getNonFieldDeclScope(S);
2195         for (auto *D : NewTag->decls()) {
2196           auto *ED = cast<EnumConstantDecl>(D);
2197           assert(EnumScope->isDeclScope(ED));
2198           EnumScope->RemoveDecl(ED);
2199           IdResolver.RemoveDecl(ED);
2200           ED->getLexicalDeclContext()->removeDecl(ED);
2201         }
2202       }
2203     }
2204   }
2205 
2206   // If the typedef types are not identical, reject them in all languages and
2207   // with any extensions enabled.
2208   if (isIncompatibleTypedef(Old, New))
2209     return;
2210 
2211   // The types match.  Link up the redeclaration chain and merge attributes if
2212   // the old declaration was a typedef.
2213   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2214     New->setPreviousDecl(Typedef);
2215     mergeDeclAttributes(New, Old);
2216   }
2217 
2218   if (getLangOpts().MicrosoftExt)
2219     return;
2220 
2221   if (getLangOpts().CPlusPlus) {
2222     // C++ [dcl.typedef]p2:
2223     //   In a given non-class scope, a typedef specifier can be used to
2224     //   redefine the name of any type declared in that scope to refer
2225     //   to the type to which it already refers.
2226     if (!isa<CXXRecordDecl>(CurContext))
2227       return;
2228 
2229     // C++0x [dcl.typedef]p4:
2230     //   In a given class scope, a typedef specifier can be used to redefine
2231     //   any class-name declared in that scope that is not also a typedef-name
2232     //   to refer to the type to which it already refers.
2233     //
2234     // This wording came in via DR424, which was a correction to the
2235     // wording in DR56, which accidentally banned code like:
2236     //
2237     //   struct S {
2238     //     typedef struct A { } A;
2239     //   };
2240     //
2241     // in the C++03 standard. We implement the C++0x semantics, which
2242     // allow the above but disallow
2243     //
2244     //   struct S {
2245     //     typedef int I;
2246     //     typedef int I;
2247     //   };
2248     //
2249     // since that was the intent of DR56.
2250     if (!isa<TypedefNameDecl>(Old))
2251       return;
2252 
2253     Diag(New->getLocation(), diag::err_redefinition)
2254       << New->getDeclName();
2255     notePreviousDefinition(Old, New->getLocation());
2256     return New->setInvalidDecl();
2257   }
2258 
2259   // Modules always permit redefinition of typedefs, as does C11.
2260   if (getLangOpts().Modules || getLangOpts().C11)
2261     return;
2262 
2263   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2264   // is normally mapped to an error, but can be controlled with
2265   // -Wtypedef-redefinition.  If either the original or the redefinition is
2266   // in a system header, don't emit this for compatibility with GCC.
2267   if (getDiagnostics().getSuppressSystemWarnings() &&
2268       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2269       (Old->isImplicit() ||
2270        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2271        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2272     return;
2273 
2274   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2275     << New->getDeclName();
2276   notePreviousDefinition(Old, New->getLocation());
2277 }
2278 
2279 /// DeclhasAttr - returns true if decl Declaration already has the target
2280 /// attribute.
2281 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2282   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2283   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2284   for (const auto *i : D->attrs())
2285     if (i->getKind() == A->getKind()) {
2286       if (Ann) {
2287         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2288           return true;
2289         continue;
2290       }
2291       // FIXME: Don't hardcode this check
2292       if (OA && isa<OwnershipAttr>(i))
2293         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2294       return true;
2295     }
2296 
2297   return false;
2298 }
2299 
2300 static bool isAttributeTargetADefinition(Decl *D) {
2301   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2302     return VD->isThisDeclarationADefinition();
2303   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2304     return TD->isCompleteDefinition() || TD->isBeingDefined();
2305   return true;
2306 }
2307 
2308 /// Merge alignment attributes from \p Old to \p New, taking into account the
2309 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2310 ///
2311 /// \return \c true if any attributes were added to \p New.
2312 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2313   // Look for alignas attributes on Old, and pick out whichever attribute
2314   // specifies the strictest alignment requirement.
2315   AlignedAttr *OldAlignasAttr = nullptr;
2316   AlignedAttr *OldStrictestAlignAttr = nullptr;
2317   unsigned OldAlign = 0;
2318   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2319     // FIXME: We have no way of representing inherited dependent alignments
2320     // in a case like:
2321     //   template<int A, int B> struct alignas(A) X;
2322     //   template<int A, int B> struct alignas(B) X {};
2323     // For now, we just ignore any alignas attributes which are not on the
2324     // definition in such a case.
2325     if (I->isAlignmentDependent())
2326       return false;
2327 
2328     if (I->isAlignas())
2329       OldAlignasAttr = I;
2330 
2331     unsigned Align = I->getAlignment(S.Context);
2332     if (Align > OldAlign) {
2333       OldAlign = Align;
2334       OldStrictestAlignAttr = I;
2335     }
2336   }
2337 
2338   // Look for alignas attributes on New.
2339   AlignedAttr *NewAlignasAttr = nullptr;
2340   unsigned NewAlign = 0;
2341   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2342     if (I->isAlignmentDependent())
2343       return false;
2344 
2345     if (I->isAlignas())
2346       NewAlignasAttr = I;
2347 
2348     unsigned Align = I->getAlignment(S.Context);
2349     if (Align > NewAlign)
2350       NewAlign = Align;
2351   }
2352 
2353   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2354     // Both declarations have 'alignas' attributes. We require them to match.
2355     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2356     // fall short. (If two declarations both have alignas, they must both match
2357     // every definition, and so must match each other if there is a definition.)
2358 
2359     // If either declaration only contains 'alignas(0)' specifiers, then it
2360     // specifies the natural alignment for the type.
2361     if (OldAlign == 0 || NewAlign == 0) {
2362       QualType Ty;
2363       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2364         Ty = VD->getType();
2365       else
2366         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2367 
2368       if (OldAlign == 0)
2369         OldAlign = S.Context.getTypeAlign(Ty);
2370       if (NewAlign == 0)
2371         NewAlign = S.Context.getTypeAlign(Ty);
2372     }
2373 
2374     if (OldAlign != NewAlign) {
2375       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2376         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2377         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2378       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2379     }
2380   }
2381 
2382   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2383     // C++11 [dcl.align]p6:
2384     //   if any declaration of an entity has an alignment-specifier,
2385     //   every defining declaration of that entity shall specify an
2386     //   equivalent alignment.
2387     // C11 6.7.5/7:
2388     //   If the definition of an object does not have an alignment
2389     //   specifier, any other declaration of that object shall also
2390     //   have no alignment specifier.
2391     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2392       << OldAlignasAttr;
2393     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2394       << OldAlignasAttr;
2395   }
2396 
2397   bool AnyAdded = false;
2398 
2399   // Ensure we have an attribute representing the strictest alignment.
2400   if (OldAlign > NewAlign) {
2401     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2402     Clone->setInherited(true);
2403     New->addAttr(Clone);
2404     AnyAdded = true;
2405   }
2406 
2407   // Ensure we have an alignas attribute if the old declaration had one.
2408   if (OldAlignasAttr && !NewAlignasAttr &&
2409       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2410     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2411     Clone->setInherited(true);
2412     New->addAttr(Clone);
2413     AnyAdded = true;
2414   }
2415 
2416   return AnyAdded;
2417 }
2418 
2419 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2420                                const InheritableAttr *Attr,
2421                                Sema::AvailabilityMergeKind AMK) {
2422   // This function copies an attribute Attr from a previous declaration to the
2423   // new declaration D if the new declaration doesn't itself have that attribute
2424   // yet or if that attribute allows duplicates.
2425   // If you're adding a new attribute that requires logic different from
2426   // "use explicit attribute on decl if present, else use attribute from
2427   // previous decl", for example if the attribute needs to be consistent
2428   // between redeclarations, you need to call a custom merge function here.
2429   InheritableAttr *NewAttr = nullptr;
2430   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2431   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2432     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2433                                       AA->isImplicit(), AA->getIntroduced(),
2434                                       AA->getDeprecated(),
2435                                       AA->getObsoleted(), AA->getUnavailable(),
2436                                       AA->getMessage(), AA->getStrict(),
2437                                       AA->getReplacement(), AMK,
2438                                       AttrSpellingListIndex);
2439   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2440     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441                                     AttrSpellingListIndex);
2442   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2443     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2444                                         AttrSpellingListIndex);
2445   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2446     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2447                                    AttrSpellingListIndex);
2448   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2449     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2450                                    AttrSpellingListIndex);
2451   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2452     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2453                                 FA->getFormatIdx(), FA->getFirstArg(),
2454                                 AttrSpellingListIndex);
2455   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2456     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2457                                  AttrSpellingListIndex);
2458   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2459     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2460                                        AttrSpellingListIndex,
2461                                        IA->getSemanticSpelling());
2462   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2463     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2464                                       &S.Context.Idents.get(AA->getSpelling()),
2465                                       AttrSpellingListIndex);
2466   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2467            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2468             isa<CUDAGlobalAttr>(Attr))) {
2469     // CUDA target attributes are part of function signature for
2470     // overloading purposes and must not be merged.
2471     return false;
2472   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2473     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2474   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2475     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2476   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2477     NewAttr = S.mergeInternalLinkageAttr(
2478         D, InternalLinkageA->getRange(),
2479         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2480         AttrSpellingListIndex);
2481   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2482     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2483                                 &S.Context.Idents.get(CommonA->getSpelling()),
2484                                 AttrSpellingListIndex);
2485   else if (isa<AlignedAttr>(Attr))
2486     // AlignedAttrs are handled separately, because we need to handle all
2487     // such attributes on a declaration at the same time.
2488     NewAttr = nullptr;
2489   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2490            (AMK == Sema::AMK_Override ||
2491             AMK == Sema::AMK_ProtocolImplementation))
2492     NewAttr = nullptr;
2493   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2494     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2495                               UA->getGuid());
2496   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2497     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2498 
2499   if (NewAttr) {
2500     NewAttr->setInherited(true);
2501     D->addAttr(NewAttr);
2502     if (isa<MSInheritanceAttr>(NewAttr))
2503       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2504     return true;
2505   }
2506 
2507   return false;
2508 }
2509 
2510 static const NamedDecl *getDefinition(const Decl *D) {
2511   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2512     return TD->getDefinition();
2513   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514     const VarDecl *Def = VD->getDefinition();
2515     if (Def)
2516       return Def;
2517     return VD->getActingDefinition();
2518   }
2519   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2520     return FD->getDefinition();
2521   return nullptr;
2522 }
2523 
2524 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2525   for (const auto *Attribute : D->attrs())
2526     if (Attribute->getKind() == Kind)
2527       return true;
2528   return false;
2529 }
2530 
2531 /// checkNewAttributesAfterDef - If we already have a definition, check that
2532 /// there are no new attributes in this declaration.
2533 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2534   if (!New->hasAttrs())
2535     return;
2536 
2537   const NamedDecl *Def = getDefinition(Old);
2538   if (!Def || Def == New)
2539     return;
2540 
2541   AttrVec &NewAttributes = New->getAttrs();
2542   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2543     const Attr *NewAttribute = NewAttributes[I];
2544 
2545     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2546       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2547         Sema::SkipBodyInfo SkipBody;
2548         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2549 
2550         // If we're skipping this definition, drop the "alias" attribute.
2551         if (SkipBody.ShouldSkip) {
2552           NewAttributes.erase(NewAttributes.begin() + I);
2553           --E;
2554           continue;
2555         }
2556       } else {
2557         VarDecl *VD = cast<VarDecl>(New);
2558         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2559                                 VarDecl::TentativeDefinition
2560                             ? diag::err_alias_after_tentative
2561                             : diag::err_redefinition;
2562         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2563         if (Diag == diag::err_redefinition)
2564           S.notePreviousDefinition(Def, VD->getLocation());
2565         else
2566           S.Diag(Def->getLocation(), diag::note_previous_definition);
2567         VD->setInvalidDecl();
2568       }
2569       ++I;
2570       continue;
2571     }
2572 
2573     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2574       // Tentative definitions are only interesting for the alias check above.
2575       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2576         ++I;
2577         continue;
2578       }
2579     }
2580 
2581     if (hasAttribute(Def, NewAttribute->getKind())) {
2582       ++I;
2583       continue; // regular attr merging will take care of validating this.
2584     }
2585 
2586     if (isa<C11NoReturnAttr>(NewAttribute)) {
2587       // C's _Noreturn is allowed to be added to a function after it is defined.
2588       ++I;
2589       continue;
2590     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2591       if (AA->isAlignas()) {
2592         // C++11 [dcl.align]p6:
2593         //   if any declaration of an entity has an alignment-specifier,
2594         //   every defining declaration of that entity shall specify an
2595         //   equivalent alignment.
2596         // C11 6.7.5/7:
2597         //   If the definition of an object does not have an alignment
2598         //   specifier, any other declaration of that object shall also
2599         //   have no alignment specifier.
2600         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2601           << AA;
2602         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2603           << AA;
2604         NewAttributes.erase(NewAttributes.begin() + I);
2605         --E;
2606         continue;
2607       }
2608     }
2609 
2610     S.Diag(NewAttribute->getLocation(),
2611            diag::warn_attribute_precede_definition);
2612     S.Diag(Def->getLocation(), diag::note_previous_definition);
2613     NewAttributes.erase(NewAttributes.begin() + I);
2614     --E;
2615   }
2616 }
2617 
2618 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2619 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2620                                AvailabilityMergeKind AMK) {
2621   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2622     UsedAttr *NewAttr = OldAttr->clone(Context);
2623     NewAttr->setInherited(true);
2624     New->addAttr(NewAttr);
2625   }
2626 
2627   if (!Old->hasAttrs() && !New->hasAttrs())
2628     return;
2629 
2630   // Attributes declared post-definition are currently ignored.
2631   checkNewAttributesAfterDef(*this, New, Old);
2632 
2633   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2634     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2635       if (OldA->getLabel() != NewA->getLabel()) {
2636         // This redeclaration changes __asm__ label.
2637         Diag(New->getLocation(), diag::err_different_asm_label);
2638         Diag(OldA->getLocation(), diag::note_previous_declaration);
2639       }
2640     } else if (Old->isUsed()) {
2641       // This redeclaration adds an __asm__ label to a declaration that has
2642       // already been ODR-used.
2643       Diag(New->getLocation(), diag::err_late_asm_label_name)
2644         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2645     }
2646   }
2647 
2648   // Re-declaration cannot add abi_tag's.
2649   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2650     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2651       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2652         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2653                       NewTag) == OldAbiTagAttr->tags_end()) {
2654           Diag(NewAbiTagAttr->getLocation(),
2655                diag::err_new_abi_tag_on_redeclaration)
2656               << NewTag;
2657           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2658         }
2659       }
2660     } else {
2661       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2662       Diag(Old->getLocation(), diag::note_previous_declaration);
2663     }
2664   }
2665 
2666   // This redeclaration adds a section attribute.
2667   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2668     if (auto *VD = dyn_cast<VarDecl>(New)) {
2669       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2670         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2671         Diag(Old->getLocation(), diag::note_previous_declaration);
2672       }
2673     }
2674   }
2675 
2676   if (!Old->hasAttrs())
2677     return;
2678 
2679   bool foundAny = New->hasAttrs();
2680 
2681   // Ensure that any moving of objects within the allocated map is done before
2682   // we process them.
2683   if (!foundAny) New->setAttrs(AttrVec());
2684 
2685   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2686     // Ignore deprecated/unavailable/availability attributes if requested.
2687     AvailabilityMergeKind LocalAMK = AMK_None;
2688     if (isa<DeprecatedAttr>(I) ||
2689         isa<UnavailableAttr>(I) ||
2690         isa<AvailabilityAttr>(I)) {
2691       switch (AMK) {
2692       case AMK_None:
2693         continue;
2694 
2695       case AMK_Redeclaration:
2696       case AMK_Override:
2697       case AMK_ProtocolImplementation:
2698         LocalAMK = AMK;
2699         break;
2700       }
2701     }
2702 
2703     // Already handled.
2704     if (isa<UsedAttr>(I))
2705       continue;
2706 
2707     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2708       foundAny = true;
2709   }
2710 
2711   if (mergeAlignedAttrs(*this, New, Old))
2712     foundAny = true;
2713 
2714   if (!foundAny) New->dropAttrs();
2715 }
2716 
2717 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2718 /// to the new one.
2719 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2720                                      const ParmVarDecl *oldDecl,
2721                                      Sema &S) {
2722   // C++11 [dcl.attr.depend]p2:
2723   //   The first declaration of a function shall specify the
2724   //   carries_dependency attribute for its declarator-id if any declaration
2725   //   of the function specifies the carries_dependency attribute.
2726   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2727   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2728     S.Diag(CDA->getLocation(),
2729            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2730     // Find the first declaration of the parameter.
2731     // FIXME: Should we build redeclaration chains for function parameters?
2732     const FunctionDecl *FirstFD =
2733       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2734     const ParmVarDecl *FirstVD =
2735       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2736     S.Diag(FirstVD->getLocation(),
2737            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2738   }
2739 
2740   if (!oldDecl->hasAttrs())
2741     return;
2742 
2743   bool foundAny = newDecl->hasAttrs();
2744 
2745   // Ensure that any moving of objects within the allocated map is
2746   // done before we process them.
2747   if (!foundAny) newDecl->setAttrs(AttrVec());
2748 
2749   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2750     if (!DeclHasAttr(newDecl, I)) {
2751       InheritableAttr *newAttr =
2752         cast<InheritableParamAttr>(I->clone(S.Context));
2753       newAttr->setInherited(true);
2754       newDecl->addAttr(newAttr);
2755       foundAny = true;
2756     }
2757   }
2758 
2759   if (!foundAny) newDecl->dropAttrs();
2760 }
2761 
2762 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2763                                 const ParmVarDecl *OldParam,
2764                                 Sema &S) {
2765   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2766     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2767       if (*Oldnullability != *Newnullability) {
2768         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2769           << DiagNullabilityKind(
2770                *Newnullability,
2771                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2772                 != 0))
2773           << DiagNullabilityKind(
2774                *Oldnullability,
2775                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2776                 != 0));
2777         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2778       }
2779     } else {
2780       QualType NewT = NewParam->getType();
2781       NewT = S.Context.getAttributedType(
2782                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2783                          NewT, NewT);
2784       NewParam->setType(NewT);
2785     }
2786   }
2787 }
2788 
2789 namespace {
2790 
2791 /// Used in MergeFunctionDecl to keep track of function parameters in
2792 /// C.
2793 struct GNUCompatibleParamWarning {
2794   ParmVarDecl *OldParm;
2795   ParmVarDecl *NewParm;
2796   QualType PromotedType;
2797 };
2798 
2799 } // end anonymous namespace
2800 
2801 /// getSpecialMember - get the special member enum for a method.
2802 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2803   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2804     if (Ctor->isDefaultConstructor())
2805       return Sema::CXXDefaultConstructor;
2806 
2807     if (Ctor->isCopyConstructor())
2808       return Sema::CXXCopyConstructor;
2809 
2810     if (Ctor->isMoveConstructor())
2811       return Sema::CXXMoveConstructor;
2812   } else if (isa<CXXDestructorDecl>(MD)) {
2813     return Sema::CXXDestructor;
2814   } else if (MD->isCopyAssignmentOperator()) {
2815     return Sema::CXXCopyAssignment;
2816   } else if (MD->isMoveAssignmentOperator()) {
2817     return Sema::CXXMoveAssignment;
2818   }
2819 
2820   return Sema::CXXInvalid;
2821 }
2822 
2823 // Determine whether the previous declaration was a definition, implicit
2824 // declaration, or a declaration.
2825 template <typename T>
2826 static std::pair<diag::kind, SourceLocation>
2827 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2828   diag::kind PrevDiag;
2829   SourceLocation OldLocation = Old->getLocation();
2830   if (Old->isThisDeclarationADefinition())
2831     PrevDiag = diag::note_previous_definition;
2832   else if (Old->isImplicit()) {
2833     PrevDiag = diag::note_previous_implicit_declaration;
2834     if (OldLocation.isInvalid())
2835       OldLocation = New->getLocation();
2836   } else
2837     PrevDiag = diag::note_previous_declaration;
2838   return std::make_pair(PrevDiag, OldLocation);
2839 }
2840 
2841 /// canRedefineFunction - checks if a function can be redefined. Currently,
2842 /// only extern inline functions can be redefined, and even then only in
2843 /// GNU89 mode.
2844 static bool canRedefineFunction(const FunctionDecl *FD,
2845                                 const LangOptions& LangOpts) {
2846   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2847           !LangOpts.CPlusPlus &&
2848           FD->isInlineSpecified() &&
2849           FD->getStorageClass() == SC_Extern);
2850 }
2851 
2852 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2853   const AttributedType *AT = T->getAs<AttributedType>();
2854   while (AT && !AT->isCallingConv())
2855     AT = AT->getModifiedType()->getAs<AttributedType>();
2856   return AT;
2857 }
2858 
2859 template <typename T>
2860 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2861   const DeclContext *DC = Old->getDeclContext();
2862   if (DC->isRecord())
2863     return false;
2864 
2865   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2866   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2867     return true;
2868   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2869     return true;
2870   return false;
2871 }
2872 
2873 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2874 static bool isExternC(VarTemplateDecl *) { return false; }
2875 
2876 /// \brief Check whether a redeclaration of an entity introduced by a
2877 /// using-declaration is valid, given that we know it's not an overload
2878 /// (nor a hidden tag declaration).
2879 template<typename ExpectedDecl>
2880 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2881                                    ExpectedDecl *New) {
2882   // C++11 [basic.scope.declarative]p4:
2883   //   Given a set of declarations in a single declarative region, each of
2884   //   which specifies the same unqualified name,
2885   //   -- they shall all refer to the same entity, or all refer to functions
2886   //      and function templates; or
2887   //   -- exactly one declaration shall declare a class name or enumeration
2888   //      name that is not a typedef name and the other declarations shall all
2889   //      refer to the same variable or enumerator, or all refer to functions
2890   //      and function templates; in this case the class name or enumeration
2891   //      name is hidden (3.3.10).
2892 
2893   // C++11 [namespace.udecl]p14:
2894   //   If a function declaration in namespace scope or block scope has the
2895   //   same name and the same parameter-type-list as a function introduced
2896   //   by a using-declaration, and the declarations do not declare the same
2897   //   function, the program is ill-formed.
2898 
2899   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2900   if (Old &&
2901       !Old->getDeclContext()->getRedeclContext()->Equals(
2902           New->getDeclContext()->getRedeclContext()) &&
2903       !(isExternC(Old) && isExternC(New)))
2904     Old = nullptr;
2905 
2906   if (!Old) {
2907     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2908     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2909     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2910     return true;
2911   }
2912   return false;
2913 }
2914 
2915 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2916                                             const FunctionDecl *B) {
2917   assert(A->getNumParams() == B->getNumParams());
2918 
2919   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2920     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2921     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2922     if (AttrA == AttrB)
2923       return true;
2924     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2925   };
2926 
2927   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2928 }
2929 
2930 /// If necessary, adjust the semantic declaration context for a qualified
2931 /// declaration to name the correct inline namespace within the qualifier.
2932 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2933                                                DeclaratorDecl *OldD) {
2934   // The only case where we need to update the DeclContext is when
2935   // redeclaration lookup for a qualified name finds a declaration
2936   // in an inline namespace within the context named by the qualifier:
2937   //
2938   //   inline namespace N { int f(); }
2939   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2940   //
2941   // For unqualified declarations, the semantic context *can* change
2942   // along the redeclaration chain (for local extern declarations,
2943   // extern "C" declarations, and friend declarations in particular).
2944   if (!NewD->getQualifier())
2945     return;
2946 
2947   // NewD is probably already in the right context.
2948   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2949   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2950   if (NamedDC->Equals(SemaDC))
2951     return;
2952 
2953   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2954           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2955          "unexpected context for redeclaration");
2956 
2957   auto *LexDC = NewD->getLexicalDeclContext();
2958   auto FixSemaDC = [=](NamedDecl *D) {
2959     if (!D)
2960       return;
2961     D->setDeclContext(SemaDC);
2962     D->setLexicalDeclContext(LexDC);
2963   };
2964 
2965   FixSemaDC(NewD);
2966   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2967     FixSemaDC(FD->getDescribedFunctionTemplate());
2968   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2969     FixSemaDC(VD->getDescribedVarTemplate());
2970 }
2971 
2972 /// MergeFunctionDecl - We just parsed a function 'New' from
2973 /// declarator D which has the same name and scope as a previous
2974 /// declaration 'Old'.  Figure out how to resolve this situation,
2975 /// merging decls or emitting diagnostics as appropriate.
2976 ///
2977 /// In C++, New and Old must be declarations that are not
2978 /// overloaded. Use IsOverload to determine whether New and Old are
2979 /// overloaded, and to select the Old declaration that New should be
2980 /// merged with.
2981 ///
2982 /// Returns true if there was an error, false otherwise.
2983 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2984                              Scope *S, bool MergeTypeWithOld) {
2985   // Verify the old decl was also a function.
2986   FunctionDecl *Old = OldD->getAsFunction();
2987   if (!Old) {
2988     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2989       if (New->getFriendObjectKind()) {
2990         Diag(New->getLocation(), diag::err_using_decl_friend);
2991         Diag(Shadow->getTargetDecl()->getLocation(),
2992              diag::note_using_decl_target);
2993         Diag(Shadow->getUsingDecl()->getLocation(),
2994              diag::note_using_decl) << 0;
2995         return true;
2996       }
2997 
2998       // Check whether the two declarations might declare the same function.
2999       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3000         return true;
3001       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3002     } else {
3003       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3004         << New->getDeclName();
3005       notePreviousDefinition(OldD, New->getLocation());
3006       return true;
3007     }
3008   }
3009 
3010   // If the old declaration is invalid, just give up here.
3011   if (Old->isInvalidDecl())
3012     return true;
3013 
3014   // Disallow redeclaration of some builtins.
3015   if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3016     Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3017     Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3018         << Old << Old->getType();
3019     return true;
3020   }
3021 
3022   diag::kind PrevDiag;
3023   SourceLocation OldLocation;
3024   std::tie(PrevDiag, OldLocation) =
3025       getNoteDiagForInvalidRedeclaration(Old, New);
3026 
3027   // Don't complain about this if we're in GNU89 mode and the old function
3028   // is an extern inline function.
3029   // Don't complain about specializations. They are not supposed to have
3030   // storage classes.
3031   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3032       New->getStorageClass() == SC_Static &&
3033       Old->hasExternalFormalLinkage() &&
3034       !New->getTemplateSpecializationInfo() &&
3035       !canRedefineFunction(Old, getLangOpts())) {
3036     if (getLangOpts().MicrosoftExt) {
3037       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3038       Diag(OldLocation, PrevDiag);
3039     } else {
3040       Diag(New->getLocation(), diag::err_static_non_static) << New;
3041       Diag(OldLocation, PrevDiag);
3042       return true;
3043     }
3044   }
3045 
3046   if (New->hasAttr<InternalLinkageAttr>() &&
3047       !Old->hasAttr<InternalLinkageAttr>()) {
3048     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3049         << New->getDeclName();
3050     notePreviousDefinition(Old, New->getLocation());
3051     New->dropAttr<InternalLinkageAttr>();
3052   }
3053 
3054   if (CheckRedeclarationModuleOwnership(New, Old))
3055     return true;
3056 
3057   if (!getLangOpts().CPlusPlus) {
3058     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3059     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3060       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3061         << New << OldOvl;
3062 
3063       // Try our best to find a decl that actually has the overloadable
3064       // attribute for the note. In most cases (e.g. programs with only one
3065       // broken declaration/definition), this won't matter.
3066       //
3067       // FIXME: We could do this if we juggled some extra state in
3068       // OverloadableAttr, rather than just removing it.
3069       const Decl *DiagOld = Old;
3070       if (OldOvl) {
3071         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3072           const auto *A = D->getAttr<OverloadableAttr>();
3073           return A && !A->isImplicit();
3074         });
3075         // If we've implicitly added *all* of the overloadable attrs to this
3076         // chain, emitting a "previous redecl" note is pointless.
3077         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3078       }
3079 
3080       if (DiagOld)
3081         Diag(DiagOld->getLocation(),
3082              diag::note_attribute_overloadable_prev_overload)
3083           << OldOvl;
3084 
3085       if (OldOvl)
3086         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3087       else
3088         New->dropAttr<OverloadableAttr>();
3089     }
3090   }
3091 
3092   // If a function is first declared with a calling convention, but is later
3093   // declared or defined without one, all following decls assume the calling
3094   // convention of the first.
3095   //
3096   // It's OK if a function is first declared without a calling convention,
3097   // but is later declared or defined with the default calling convention.
3098   //
3099   // To test if either decl has an explicit calling convention, we look for
3100   // AttributedType sugar nodes on the type as written.  If they are missing or
3101   // were canonicalized away, we assume the calling convention was implicit.
3102   //
3103   // Note also that we DO NOT return at this point, because we still have
3104   // other tests to run.
3105   QualType OldQType = Context.getCanonicalType(Old->getType());
3106   QualType NewQType = Context.getCanonicalType(New->getType());
3107   const FunctionType *OldType = cast<FunctionType>(OldQType);
3108   const FunctionType *NewType = cast<FunctionType>(NewQType);
3109   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3110   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3111   bool RequiresAdjustment = false;
3112 
3113   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3114     FunctionDecl *First = Old->getFirstDecl();
3115     const FunctionType *FT =
3116         First->getType().getCanonicalType()->castAs<FunctionType>();
3117     FunctionType::ExtInfo FI = FT->getExtInfo();
3118     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3119     if (!NewCCExplicit) {
3120       // Inherit the CC from the previous declaration if it was specified
3121       // there but not here.
3122       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3123       RequiresAdjustment = true;
3124     } else {
3125       // Calling conventions aren't compatible, so complain.
3126       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3127       Diag(New->getLocation(), diag::err_cconv_change)
3128         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3129         << !FirstCCExplicit
3130         << (!FirstCCExplicit ? "" :
3131             FunctionType::getNameForCallConv(FI.getCC()));
3132 
3133       // Put the note on the first decl, since it is the one that matters.
3134       Diag(First->getLocation(), diag::note_previous_declaration);
3135       return true;
3136     }
3137   }
3138 
3139   // FIXME: diagnose the other way around?
3140   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3141     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3142     RequiresAdjustment = true;
3143   }
3144 
3145   // Merge regparm attribute.
3146   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3147       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3148     if (NewTypeInfo.getHasRegParm()) {
3149       Diag(New->getLocation(), diag::err_regparm_mismatch)
3150         << NewType->getRegParmType()
3151         << OldType->getRegParmType();
3152       Diag(OldLocation, diag::note_previous_declaration);
3153       return true;
3154     }
3155 
3156     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3157     RequiresAdjustment = true;
3158   }
3159 
3160   // Merge ns_returns_retained attribute.
3161   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3162     if (NewTypeInfo.getProducesResult()) {
3163       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3164           << "'ns_returns_retained'";
3165       Diag(OldLocation, diag::note_previous_declaration);
3166       return true;
3167     }
3168 
3169     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3170     RequiresAdjustment = true;
3171   }
3172 
3173   if (OldTypeInfo.getNoCallerSavedRegs() !=
3174       NewTypeInfo.getNoCallerSavedRegs()) {
3175     if (NewTypeInfo.getNoCallerSavedRegs()) {
3176       AnyX86NoCallerSavedRegistersAttr *Attr =
3177         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3178       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3179       Diag(OldLocation, diag::note_previous_declaration);
3180       return true;
3181     }
3182 
3183     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3184     RequiresAdjustment = true;
3185   }
3186 
3187   if (RequiresAdjustment) {
3188     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3189     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3190     New->setType(QualType(AdjustedType, 0));
3191     NewQType = Context.getCanonicalType(New->getType());
3192     NewType = cast<FunctionType>(NewQType);
3193   }
3194 
3195   // If this redeclaration makes the function inline, we may need to add it to
3196   // UndefinedButUsed.
3197   if (!Old->isInlined() && New->isInlined() &&
3198       !New->hasAttr<GNUInlineAttr>() &&
3199       !getLangOpts().GNUInline &&
3200       Old->isUsed(false) &&
3201       !Old->isDefined() && !New->isThisDeclarationADefinition())
3202     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3203                                            SourceLocation()));
3204 
3205   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3206   // about it.
3207   if (New->hasAttr<GNUInlineAttr>() &&
3208       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3209     UndefinedButUsed.erase(Old->getCanonicalDecl());
3210   }
3211 
3212   // If pass_object_size params don't match up perfectly, this isn't a valid
3213   // redeclaration.
3214   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3215       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3216     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3217         << New->getDeclName();
3218     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3219     return true;
3220   }
3221 
3222   if (getLangOpts().CPlusPlus) {
3223     // C++1z [over.load]p2
3224     //   Certain function declarations cannot be overloaded:
3225     //     -- Function declarations that differ only in the return type,
3226     //        the exception specification, or both cannot be overloaded.
3227 
3228     // Check the exception specifications match. This may recompute the type of
3229     // both Old and New if it resolved exception specifications, so grab the
3230     // types again after this. Because this updates the type, we do this before
3231     // any of the other checks below, which may update the "de facto" NewQType
3232     // but do not necessarily update the type of New.
3233     if (CheckEquivalentExceptionSpec(Old, New))
3234       return true;
3235     OldQType = Context.getCanonicalType(Old->getType());
3236     NewQType = Context.getCanonicalType(New->getType());
3237 
3238     // Go back to the type source info to compare the declared return types,
3239     // per C++1y [dcl.type.auto]p13:
3240     //   Redeclarations or specializations of a function or function template
3241     //   with a declared return type that uses a placeholder type shall also
3242     //   use that placeholder, not a deduced type.
3243     QualType OldDeclaredReturnType =
3244         (Old->getTypeSourceInfo()
3245              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3246              : OldType)->getReturnType();
3247     QualType NewDeclaredReturnType =
3248         (New->getTypeSourceInfo()
3249              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3250              : NewType)->getReturnType();
3251     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3252         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3253           New->isLocalExternDecl())) {
3254       QualType ResQT;
3255       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3256           OldDeclaredReturnType->isObjCObjectPointerType())
3257         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3258       if (ResQT.isNull()) {
3259         if (New->isCXXClassMember() && New->isOutOfLine())
3260           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3261               << New << New->getReturnTypeSourceRange();
3262         else
3263           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3264               << New->getReturnTypeSourceRange();
3265         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3266                                     << Old->getReturnTypeSourceRange();
3267         return true;
3268       }
3269       else
3270         NewQType = ResQT;
3271     }
3272 
3273     QualType OldReturnType = OldType->getReturnType();
3274     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3275     if (OldReturnType != NewReturnType) {
3276       // If this function has a deduced return type and has already been
3277       // defined, copy the deduced value from the old declaration.
3278       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3279       if (OldAT && OldAT->isDeduced()) {
3280         New->setType(
3281             SubstAutoType(New->getType(),
3282                           OldAT->isDependentType() ? Context.DependentTy
3283                                                    : OldAT->getDeducedType()));
3284         NewQType = Context.getCanonicalType(
3285             SubstAutoType(NewQType,
3286                           OldAT->isDependentType() ? Context.DependentTy
3287                                                    : OldAT->getDeducedType()));
3288       }
3289     }
3290 
3291     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3292     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3293     if (OldMethod && NewMethod) {
3294       // Preserve triviality.
3295       NewMethod->setTrivial(OldMethod->isTrivial());
3296 
3297       // MSVC allows explicit template specialization at class scope:
3298       // 2 CXXMethodDecls referring to the same function will be injected.
3299       // We don't want a redeclaration error.
3300       bool IsClassScopeExplicitSpecialization =
3301                               OldMethod->isFunctionTemplateSpecialization() &&
3302                               NewMethod->isFunctionTemplateSpecialization();
3303       bool isFriend = NewMethod->getFriendObjectKind();
3304 
3305       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3306           !IsClassScopeExplicitSpecialization) {
3307         //    -- Member function declarations with the same name and the
3308         //       same parameter types cannot be overloaded if any of them
3309         //       is a static member function declaration.
3310         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3311           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3312           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3313           return true;
3314         }
3315 
3316         // C++ [class.mem]p1:
3317         //   [...] A member shall not be declared twice in the
3318         //   member-specification, except that a nested class or member
3319         //   class template can be declared and then later defined.
3320         if (!inTemplateInstantiation()) {
3321           unsigned NewDiag;
3322           if (isa<CXXConstructorDecl>(OldMethod))
3323             NewDiag = diag::err_constructor_redeclared;
3324           else if (isa<CXXDestructorDecl>(NewMethod))
3325             NewDiag = diag::err_destructor_redeclared;
3326           else if (isa<CXXConversionDecl>(NewMethod))
3327             NewDiag = diag::err_conv_function_redeclared;
3328           else
3329             NewDiag = diag::err_member_redeclared;
3330 
3331           Diag(New->getLocation(), NewDiag);
3332         } else {
3333           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3334             << New << New->getType();
3335         }
3336         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3337         return true;
3338 
3339       // Complain if this is an explicit declaration of a special
3340       // member that was initially declared implicitly.
3341       //
3342       // As an exception, it's okay to befriend such methods in order
3343       // to permit the implicit constructor/destructor/operator calls.
3344       } else if (OldMethod->isImplicit()) {
3345         if (isFriend) {
3346           NewMethod->setImplicit();
3347         } else {
3348           Diag(NewMethod->getLocation(),
3349                diag::err_definition_of_implicitly_declared_member)
3350             << New << getSpecialMember(OldMethod);
3351           return true;
3352         }
3353       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3354         Diag(NewMethod->getLocation(),
3355              diag::err_definition_of_explicitly_defaulted_member)
3356           << getSpecialMember(OldMethod);
3357         return true;
3358       }
3359     }
3360 
3361     // C++11 [dcl.attr.noreturn]p1:
3362     //   The first declaration of a function shall specify the noreturn
3363     //   attribute if any declaration of that function specifies the noreturn
3364     //   attribute.
3365     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3366     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3367       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3368       Diag(Old->getFirstDecl()->getLocation(),
3369            diag::note_noreturn_missing_first_decl);
3370     }
3371 
3372     // C++11 [dcl.attr.depend]p2:
3373     //   The first declaration of a function shall specify the
3374     //   carries_dependency attribute for its declarator-id if any declaration
3375     //   of the function specifies the carries_dependency attribute.
3376     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3377     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3378       Diag(CDA->getLocation(),
3379            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3380       Diag(Old->getFirstDecl()->getLocation(),
3381            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3382     }
3383 
3384     // (C++98 8.3.5p3):
3385     //   All declarations for a function shall agree exactly in both the
3386     //   return type and the parameter-type-list.
3387     // We also want to respect all the extended bits except noreturn.
3388 
3389     // noreturn should now match unless the old type info didn't have it.
3390     QualType OldQTypeForComparison = OldQType;
3391     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3392       auto *OldType = OldQType->castAs<FunctionProtoType>();
3393       const FunctionType *OldTypeForComparison
3394         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3395       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3396       assert(OldQTypeForComparison.isCanonical());
3397     }
3398 
3399     if (haveIncompatibleLanguageLinkages(Old, New)) {
3400       // As a special case, retain the language linkage from previous
3401       // declarations of a friend function as an extension.
3402       //
3403       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3404       // and is useful because there's otherwise no way to specify language
3405       // linkage within class scope.
3406       //
3407       // Check cautiously as the friend object kind isn't yet complete.
3408       if (New->getFriendObjectKind() != Decl::FOK_None) {
3409         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3410         Diag(OldLocation, PrevDiag);
3411       } else {
3412         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3413         Diag(OldLocation, PrevDiag);
3414         return true;
3415       }
3416     }
3417 
3418     if (OldQTypeForComparison == NewQType)
3419       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3420 
3421     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3422         New->isLocalExternDecl()) {
3423       // It's OK if we couldn't merge types for a local function declaraton
3424       // if either the old or new type is dependent. We'll merge the types
3425       // when we instantiate the function.
3426       return false;
3427     }
3428 
3429     // Fall through for conflicting redeclarations and redefinitions.
3430   }
3431 
3432   // C: Function types need to be compatible, not identical. This handles
3433   // duplicate function decls like "void f(int); void f(enum X);" properly.
3434   if (!getLangOpts().CPlusPlus &&
3435       Context.typesAreCompatible(OldQType, NewQType)) {
3436     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3437     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3438     const FunctionProtoType *OldProto = nullptr;
3439     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3440         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3441       // The old declaration provided a function prototype, but the
3442       // new declaration does not. Merge in the prototype.
3443       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3444       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3445       NewQType =
3446           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3447                                   OldProto->getExtProtoInfo());
3448       New->setType(NewQType);
3449       New->setHasInheritedPrototype();
3450 
3451       // Synthesize parameters with the same types.
3452       SmallVector<ParmVarDecl*, 16> Params;
3453       for (const auto &ParamType : OldProto->param_types()) {
3454         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3455                                                  SourceLocation(), nullptr,
3456                                                  ParamType, /*TInfo=*/nullptr,
3457                                                  SC_None, nullptr);
3458         Param->setScopeInfo(0, Params.size());
3459         Param->setImplicit();
3460         Params.push_back(Param);
3461       }
3462 
3463       New->setParams(Params);
3464     }
3465 
3466     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3467   }
3468 
3469   // GNU C permits a K&R definition to follow a prototype declaration
3470   // if the declared types of the parameters in the K&R definition
3471   // match the types in the prototype declaration, even when the
3472   // promoted types of the parameters from the K&R definition differ
3473   // from the types in the prototype. GCC then keeps the types from
3474   // the prototype.
3475   //
3476   // If a variadic prototype is followed by a non-variadic K&R definition,
3477   // the K&R definition becomes variadic.  This is sort of an edge case, but
3478   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3479   // C99 6.9.1p8.
3480   if (!getLangOpts().CPlusPlus &&
3481       Old->hasPrototype() && !New->hasPrototype() &&
3482       New->getType()->getAs<FunctionProtoType>() &&
3483       Old->getNumParams() == New->getNumParams()) {
3484     SmallVector<QualType, 16> ArgTypes;
3485     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3486     const FunctionProtoType *OldProto
3487       = Old->getType()->getAs<FunctionProtoType>();
3488     const FunctionProtoType *NewProto
3489       = New->getType()->getAs<FunctionProtoType>();
3490 
3491     // Determine whether this is the GNU C extension.
3492     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3493                                                NewProto->getReturnType());
3494     bool LooseCompatible = !MergedReturn.isNull();
3495     for (unsigned Idx = 0, End = Old->getNumParams();
3496          LooseCompatible && Idx != End; ++Idx) {
3497       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3498       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3499       if (Context.typesAreCompatible(OldParm->getType(),
3500                                      NewProto->getParamType(Idx))) {
3501         ArgTypes.push_back(NewParm->getType());
3502       } else if (Context.typesAreCompatible(OldParm->getType(),
3503                                             NewParm->getType(),
3504                                             /*CompareUnqualified=*/true)) {
3505         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3506                                            NewProto->getParamType(Idx) };
3507         Warnings.push_back(Warn);
3508         ArgTypes.push_back(NewParm->getType());
3509       } else
3510         LooseCompatible = false;
3511     }
3512 
3513     if (LooseCompatible) {
3514       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3515         Diag(Warnings[Warn].NewParm->getLocation(),
3516              diag::ext_param_promoted_not_compatible_with_prototype)
3517           << Warnings[Warn].PromotedType
3518           << Warnings[Warn].OldParm->getType();
3519         if (Warnings[Warn].OldParm->getLocation().isValid())
3520           Diag(Warnings[Warn].OldParm->getLocation(),
3521                diag::note_previous_declaration);
3522       }
3523 
3524       if (MergeTypeWithOld)
3525         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3526                                              OldProto->getExtProtoInfo()));
3527       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3528     }
3529 
3530     // Fall through to diagnose conflicting types.
3531   }
3532 
3533   // A function that has already been declared has been redeclared or
3534   // defined with a different type; show an appropriate diagnostic.
3535 
3536   // If the previous declaration was an implicitly-generated builtin
3537   // declaration, then at the very least we should use a specialized note.
3538   unsigned BuiltinID;
3539   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3540     // If it's actually a library-defined builtin function like 'malloc'
3541     // or 'printf', just warn about the incompatible redeclaration.
3542     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3543       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3544       Diag(OldLocation, diag::note_previous_builtin_declaration)
3545         << Old << Old->getType();
3546 
3547       // If this is a global redeclaration, just forget hereafter
3548       // about the "builtin-ness" of the function.
3549       //
3550       // Doing this for local extern declarations is problematic.  If
3551       // the builtin declaration remains visible, a second invalid
3552       // local declaration will produce a hard error; if it doesn't
3553       // remain visible, a single bogus local redeclaration (which is
3554       // actually only a warning) could break all the downstream code.
3555       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3556         New->getIdentifier()->revertBuiltin();
3557 
3558       return false;
3559     }
3560 
3561     PrevDiag = diag::note_previous_builtin_declaration;
3562   }
3563 
3564   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3565   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3566   return true;
3567 }
3568 
3569 /// \brief Completes the merge of two function declarations that are
3570 /// known to be compatible.
3571 ///
3572 /// This routine handles the merging of attributes and other
3573 /// properties of function declarations from the old declaration to
3574 /// the new declaration, once we know that New is in fact a
3575 /// redeclaration of Old.
3576 ///
3577 /// \returns false
3578 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3579                                         Scope *S, bool MergeTypeWithOld) {
3580   // Merge the attributes
3581   mergeDeclAttributes(New, Old);
3582 
3583   // Merge "pure" flag.
3584   if (Old->isPure())
3585     New->setPure();
3586 
3587   // Merge "used" flag.
3588   if (Old->getMostRecentDecl()->isUsed(false))
3589     New->setIsUsed();
3590 
3591   // Merge attributes from the parameters.  These can mismatch with K&R
3592   // declarations.
3593   if (New->getNumParams() == Old->getNumParams())
3594       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3595         ParmVarDecl *NewParam = New->getParamDecl(i);
3596         ParmVarDecl *OldParam = Old->getParamDecl(i);
3597         mergeParamDeclAttributes(NewParam, OldParam, *this);
3598         mergeParamDeclTypes(NewParam, OldParam, *this);
3599       }
3600 
3601   if (getLangOpts().CPlusPlus)
3602     return MergeCXXFunctionDecl(New, Old, S);
3603 
3604   // Merge the function types so the we get the composite types for the return
3605   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3606   // was visible.
3607   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3608   if (!Merged.isNull() && MergeTypeWithOld)
3609     New->setType(Merged);
3610 
3611   return false;
3612 }
3613 
3614 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3615                                 ObjCMethodDecl *oldMethod) {
3616   // Merge the attributes, including deprecated/unavailable
3617   AvailabilityMergeKind MergeKind =
3618     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3619       ? AMK_ProtocolImplementation
3620       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3621                                                        : AMK_Override;
3622 
3623   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3624 
3625   // Merge attributes from the parameters.
3626   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3627                                        oe = oldMethod->param_end();
3628   for (ObjCMethodDecl::param_iterator
3629          ni = newMethod->param_begin(), ne = newMethod->param_end();
3630        ni != ne && oi != oe; ++ni, ++oi)
3631     mergeParamDeclAttributes(*ni, *oi, *this);
3632 
3633   CheckObjCMethodOverride(newMethod, oldMethod);
3634 }
3635 
3636 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3637   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3638 
3639   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3640          ? diag::err_redefinition_different_type
3641          : diag::err_redeclaration_different_type)
3642     << New->getDeclName() << New->getType() << Old->getType();
3643 
3644   diag::kind PrevDiag;
3645   SourceLocation OldLocation;
3646   std::tie(PrevDiag, OldLocation)
3647     = getNoteDiagForInvalidRedeclaration(Old, New);
3648   S.Diag(OldLocation, PrevDiag);
3649   New->setInvalidDecl();
3650 }
3651 
3652 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3653 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3654 /// emitting diagnostics as appropriate.
3655 ///
3656 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3657 /// to here in AddInitializerToDecl. We can't check them before the initializer
3658 /// is attached.
3659 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3660                              bool MergeTypeWithOld) {
3661   if (New->isInvalidDecl() || Old->isInvalidDecl())
3662     return;
3663 
3664   QualType MergedT;
3665   if (getLangOpts().CPlusPlus) {
3666     if (New->getType()->isUndeducedType()) {
3667       // We don't know what the new type is until the initializer is attached.
3668       return;
3669     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3670       // These could still be something that needs exception specs checked.
3671       return MergeVarDeclExceptionSpecs(New, Old);
3672     }
3673     // C++ [basic.link]p10:
3674     //   [...] the types specified by all declarations referring to a given
3675     //   object or function shall be identical, except that declarations for an
3676     //   array object can specify array types that differ by the presence or
3677     //   absence of a major array bound (8.3.4).
3678     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3679       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3680       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3681 
3682       // We are merging a variable declaration New into Old. If it has an array
3683       // bound, and that bound differs from Old's bound, we should diagnose the
3684       // mismatch.
3685       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3686         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3687              PrevVD = PrevVD->getPreviousDecl()) {
3688           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3689           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3690             continue;
3691 
3692           if (!Context.hasSameType(NewArray, PrevVDTy))
3693             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3694         }
3695       }
3696 
3697       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3698         if (Context.hasSameType(OldArray->getElementType(),
3699                                 NewArray->getElementType()))
3700           MergedT = New->getType();
3701       }
3702       // FIXME: Check visibility. New is hidden but has a complete type. If New
3703       // has no array bound, it should not inherit one from Old, if Old is not
3704       // visible.
3705       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3706         if (Context.hasSameType(OldArray->getElementType(),
3707                                 NewArray->getElementType()))
3708           MergedT = Old->getType();
3709       }
3710     }
3711     else if (New->getType()->isObjCObjectPointerType() &&
3712                Old->getType()->isObjCObjectPointerType()) {
3713       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3714                                               Old->getType());
3715     }
3716   } else {
3717     // C 6.2.7p2:
3718     //   All declarations that refer to the same object or function shall have
3719     //   compatible type.
3720     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3721   }
3722   if (MergedT.isNull()) {
3723     // It's OK if we couldn't merge types if either type is dependent, for a
3724     // block-scope variable. In other cases (static data members of class
3725     // templates, variable templates, ...), we require the types to be
3726     // equivalent.
3727     // FIXME: The C++ standard doesn't say anything about this.
3728     if ((New->getType()->isDependentType() ||
3729          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3730       // If the old type was dependent, we can't merge with it, so the new type
3731       // becomes dependent for now. We'll reproduce the original type when we
3732       // instantiate the TypeSourceInfo for the variable.
3733       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3734         New->setType(Context.DependentTy);
3735       return;
3736     }
3737     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3738   }
3739 
3740   // Don't actually update the type on the new declaration if the old
3741   // declaration was an extern declaration in a different scope.
3742   if (MergeTypeWithOld)
3743     New->setType(MergedT);
3744 }
3745 
3746 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3747                                   LookupResult &Previous) {
3748   // C11 6.2.7p4:
3749   //   For an identifier with internal or external linkage declared
3750   //   in a scope in which a prior declaration of that identifier is
3751   //   visible, if the prior declaration specifies internal or
3752   //   external linkage, the type of the identifier at the later
3753   //   declaration becomes the composite type.
3754   //
3755   // If the variable isn't visible, we do not merge with its type.
3756   if (Previous.isShadowed())
3757     return false;
3758 
3759   if (S.getLangOpts().CPlusPlus) {
3760     // C++11 [dcl.array]p3:
3761     //   If there is a preceding declaration of the entity in the same
3762     //   scope in which the bound was specified, an omitted array bound
3763     //   is taken to be the same as in that earlier declaration.
3764     return NewVD->isPreviousDeclInSameBlockScope() ||
3765            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3766             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3767   } else {
3768     // If the old declaration was function-local, don't merge with its
3769     // type unless we're in the same function.
3770     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3771            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3772   }
3773 }
3774 
3775 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3776 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3777 /// situation, merging decls or emitting diagnostics as appropriate.
3778 ///
3779 /// Tentative definition rules (C99 6.9.2p2) are checked by
3780 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3781 /// definitions here, since the initializer hasn't been attached.
3782 ///
3783 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3784   // If the new decl is already invalid, don't do any other checking.
3785   if (New->isInvalidDecl())
3786     return;
3787 
3788   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3789     return;
3790 
3791   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3792 
3793   // Verify the old decl was also a variable or variable template.
3794   VarDecl *Old = nullptr;
3795   VarTemplateDecl *OldTemplate = nullptr;
3796   if (Previous.isSingleResult()) {
3797     if (NewTemplate) {
3798       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3799       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3800 
3801       if (auto *Shadow =
3802               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3803         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3804           return New->setInvalidDecl();
3805     } else {
3806       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3807 
3808       if (auto *Shadow =
3809               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3810         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3811           return New->setInvalidDecl();
3812     }
3813   }
3814   if (!Old) {
3815     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3816         << New->getDeclName();
3817     notePreviousDefinition(Previous.getRepresentativeDecl(),
3818                            New->getLocation());
3819     return New->setInvalidDecl();
3820   }
3821 
3822   // Ensure the template parameters are compatible.
3823   if (NewTemplate &&
3824       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3825                                       OldTemplate->getTemplateParameters(),
3826                                       /*Complain=*/true, TPL_TemplateMatch))
3827     return New->setInvalidDecl();
3828 
3829   // C++ [class.mem]p1:
3830   //   A member shall not be declared twice in the member-specification [...]
3831   //
3832   // Here, we need only consider static data members.
3833   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3834     Diag(New->getLocation(), diag::err_duplicate_member)
3835       << New->getIdentifier();
3836     Diag(Old->getLocation(), diag::note_previous_declaration);
3837     New->setInvalidDecl();
3838   }
3839 
3840   mergeDeclAttributes(New, Old);
3841   // Warn if an already-declared variable is made a weak_import in a subsequent
3842   // declaration
3843   if (New->hasAttr<WeakImportAttr>() &&
3844       Old->getStorageClass() == SC_None &&
3845       !Old->hasAttr<WeakImportAttr>()) {
3846     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3847     notePreviousDefinition(Old, New->getLocation());
3848     // Remove weak_import attribute on new declaration.
3849     New->dropAttr<WeakImportAttr>();
3850   }
3851 
3852   if (New->hasAttr<InternalLinkageAttr>() &&
3853       !Old->hasAttr<InternalLinkageAttr>()) {
3854     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3855         << New->getDeclName();
3856     notePreviousDefinition(Old, New->getLocation());
3857     New->dropAttr<InternalLinkageAttr>();
3858   }
3859 
3860   // Merge the types.
3861   VarDecl *MostRecent = Old->getMostRecentDecl();
3862   if (MostRecent != Old) {
3863     MergeVarDeclTypes(New, MostRecent,
3864                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3865     if (New->isInvalidDecl())
3866       return;
3867   }
3868 
3869   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3870   if (New->isInvalidDecl())
3871     return;
3872 
3873   diag::kind PrevDiag;
3874   SourceLocation OldLocation;
3875   std::tie(PrevDiag, OldLocation) =
3876       getNoteDiagForInvalidRedeclaration(Old, New);
3877 
3878   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3879   if (New->getStorageClass() == SC_Static &&
3880       !New->isStaticDataMember() &&
3881       Old->hasExternalFormalLinkage()) {
3882     if (getLangOpts().MicrosoftExt) {
3883       Diag(New->getLocation(), diag::ext_static_non_static)
3884           << New->getDeclName();
3885       Diag(OldLocation, PrevDiag);
3886     } else {
3887       Diag(New->getLocation(), diag::err_static_non_static)
3888           << New->getDeclName();
3889       Diag(OldLocation, PrevDiag);
3890       return New->setInvalidDecl();
3891     }
3892   }
3893   // C99 6.2.2p4:
3894   //   For an identifier declared with the storage-class specifier
3895   //   extern in a scope in which a prior declaration of that
3896   //   identifier is visible,23) if the prior declaration specifies
3897   //   internal or external linkage, the linkage of the identifier at
3898   //   the later declaration is the same as the linkage specified at
3899   //   the prior declaration. If no prior declaration is visible, or
3900   //   if the prior declaration specifies no linkage, then the
3901   //   identifier has external linkage.
3902   if (New->hasExternalStorage() && Old->hasLinkage())
3903     /* Okay */;
3904   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3905            !New->isStaticDataMember() &&
3906            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3907     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3908     Diag(OldLocation, PrevDiag);
3909     return New->setInvalidDecl();
3910   }
3911 
3912   // Check if extern is followed by non-extern and vice-versa.
3913   if (New->hasExternalStorage() &&
3914       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3915     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3916     Diag(OldLocation, PrevDiag);
3917     return New->setInvalidDecl();
3918   }
3919   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3920       !New->hasExternalStorage()) {
3921     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3922     Diag(OldLocation, PrevDiag);
3923     return New->setInvalidDecl();
3924   }
3925 
3926   if (CheckRedeclarationModuleOwnership(New, Old))
3927     return;
3928 
3929   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3930 
3931   // FIXME: The test for external storage here seems wrong? We still
3932   // need to check for mismatches.
3933   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3934       // Don't complain about out-of-line definitions of static members.
3935       !(Old->getLexicalDeclContext()->isRecord() &&
3936         !New->getLexicalDeclContext()->isRecord())) {
3937     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3938     Diag(OldLocation, PrevDiag);
3939     return New->setInvalidDecl();
3940   }
3941 
3942   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3943     if (VarDecl *Def = Old->getDefinition()) {
3944       // C++1z [dcl.fcn.spec]p4:
3945       //   If the definition of a variable appears in a translation unit before
3946       //   its first declaration as inline, the program is ill-formed.
3947       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3948       Diag(Def->getLocation(), diag::note_previous_definition);
3949     }
3950   }
3951 
3952   // If this redeclaration makes the variable inline, we may need to add it to
3953   // UndefinedButUsed.
3954   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3955       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3956     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3957                                            SourceLocation()));
3958 
3959   if (New->getTLSKind() != Old->getTLSKind()) {
3960     if (!Old->getTLSKind()) {
3961       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3962       Diag(OldLocation, PrevDiag);
3963     } else if (!New->getTLSKind()) {
3964       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3965       Diag(OldLocation, PrevDiag);
3966     } else {
3967       // Do not allow redeclaration to change the variable between requiring
3968       // static and dynamic initialization.
3969       // FIXME: GCC allows this, but uses the TLS keyword on the first
3970       // declaration to determine the kind. Do we need to be compatible here?
3971       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3972         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3973       Diag(OldLocation, PrevDiag);
3974     }
3975   }
3976 
3977   // C++ doesn't have tentative definitions, so go right ahead and check here.
3978   if (getLangOpts().CPlusPlus &&
3979       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3980     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3981         Old->getCanonicalDecl()->isConstexpr()) {
3982       // This definition won't be a definition any more once it's been merged.
3983       Diag(New->getLocation(),
3984            diag::warn_deprecated_redundant_constexpr_static_def);
3985     } else if (VarDecl *Def = Old->getDefinition()) {
3986       if (checkVarDeclRedefinition(Def, New))
3987         return;
3988     }
3989   }
3990 
3991   if (haveIncompatibleLanguageLinkages(Old, New)) {
3992     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3993     Diag(OldLocation, PrevDiag);
3994     New->setInvalidDecl();
3995     return;
3996   }
3997 
3998   // Merge "used" flag.
3999   if (Old->getMostRecentDecl()->isUsed(false))
4000     New->setIsUsed();
4001 
4002   // Keep a chain of previous declarations.
4003   New->setPreviousDecl(Old);
4004   if (NewTemplate)
4005     NewTemplate->setPreviousDecl(OldTemplate);
4006   adjustDeclContextForDeclaratorDecl(New, Old);
4007 
4008   // Inherit access appropriately.
4009   New->setAccess(Old->getAccess());
4010   if (NewTemplate)
4011     NewTemplate->setAccess(New->getAccess());
4012 
4013   if (Old->isInline())
4014     New->setImplicitlyInline();
4015 }
4016 
4017 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4018   SourceManager &SrcMgr = getSourceManager();
4019   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4020   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4021   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4022   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4023   auto &HSI = PP.getHeaderSearchInfo();
4024   StringRef HdrFilename =
4025       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4026 
4027   auto noteFromModuleOrInclude = [&](Module *Mod,
4028                                      SourceLocation IncLoc) -> bool {
4029     // Redefinition errors with modules are common with non modular mapped
4030     // headers, example: a non-modular header H in module A that also gets
4031     // included directly in a TU. Pointing twice to the same header/definition
4032     // is confusing, try to get better diagnostics when modules is on.
4033     if (IncLoc.isValid()) {
4034       if (Mod) {
4035         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4036             << HdrFilename.str() << Mod->getFullModuleName();
4037         if (!Mod->DefinitionLoc.isInvalid())
4038           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4039               << Mod->getFullModuleName();
4040       } else {
4041         Diag(IncLoc, diag::note_redefinition_include_same_file)
4042             << HdrFilename.str();
4043       }
4044       return true;
4045     }
4046 
4047     return false;
4048   };
4049 
4050   // Is it the same file and same offset? Provide more information on why
4051   // this leads to a redefinition error.
4052   bool EmittedDiag = false;
4053   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4054     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4055     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4056     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4057     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4058 
4059     // If the header has no guards, emit a note suggesting one.
4060     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4061       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4062 
4063     if (EmittedDiag)
4064       return;
4065   }
4066 
4067   // Redefinition coming from different files or couldn't do better above.
4068   if (Old->getLocation().isValid())
4069     Diag(Old->getLocation(), diag::note_previous_definition);
4070 }
4071 
4072 /// We've just determined that \p Old and \p New both appear to be definitions
4073 /// of the same variable. Either diagnose or fix the problem.
4074 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4075   if (!hasVisibleDefinition(Old) &&
4076       (New->getFormalLinkage() == InternalLinkage ||
4077        New->isInline() ||
4078        New->getDescribedVarTemplate() ||
4079        New->getNumTemplateParameterLists() ||
4080        New->getDeclContext()->isDependentContext())) {
4081     // The previous definition is hidden, and multiple definitions are
4082     // permitted (in separate TUs). Demote this to a declaration.
4083     New->demoteThisDefinitionToDeclaration();
4084 
4085     // Make the canonical definition visible.
4086     if (auto *OldTD = Old->getDescribedVarTemplate())
4087       makeMergedDefinitionVisible(OldTD);
4088     makeMergedDefinitionVisible(Old);
4089     return false;
4090   } else {
4091     Diag(New->getLocation(), diag::err_redefinition) << New;
4092     notePreviousDefinition(Old, New->getLocation());
4093     New->setInvalidDecl();
4094     return true;
4095   }
4096 }
4097 
4098 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4099 /// no declarator (e.g. "struct foo;") is parsed.
4100 Decl *
4101 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4102                                  RecordDecl *&AnonRecord) {
4103   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4104                                     AnonRecord);
4105 }
4106 
4107 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4108 // disambiguate entities defined in different scopes.
4109 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4110 // compatibility.
4111 // We will pick our mangling number depending on which version of MSVC is being
4112 // targeted.
4113 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4114   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4115              ? S->getMSCurManglingNumber()
4116              : S->getMSLastManglingNumber();
4117 }
4118 
4119 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4120   if (!Context.getLangOpts().CPlusPlus)
4121     return;
4122 
4123   if (isa<CXXRecordDecl>(Tag->getParent())) {
4124     // If this tag is the direct child of a class, number it if
4125     // it is anonymous.
4126     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4127       return;
4128     MangleNumberingContext &MCtx =
4129         Context.getManglingNumberContext(Tag->getParent());
4130     Context.setManglingNumber(
4131         Tag, MCtx.getManglingNumber(
4132                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4133     return;
4134   }
4135 
4136   // If this tag isn't a direct child of a class, number it if it is local.
4137   Decl *ManglingContextDecl;
4138   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4139           Tag->getDeclContext(), ManglingContextDecl)) {
4140     Context.setManglingNumber(
4141         Tag, MCtx->getManglingNumber(
4142                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4143   }
4144 }
4145 
4146 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4147                                         TypedefNameDecl *NewTD) {
4148   if (TagFromDeclSpec->isInvalidDecl())
4149     return;
4150 
4151   // Do nothing if the tag already has a name for linkage purposes.
4152   if (TagFromDeclSpec->hasNameForLinkage())
4153     return;
4154 
4155   // A well-formed anonymous tag must always be a TUK_Definition.
4156   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4157 
4158   // The type must match the tag exactly;  no qualifiers allowed.
4159   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4160                            Context.getTagDeclType(TagFromDeclSpec))) {
4161     if (getLangOpts().CPlusPlus)
4162       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4163     return;
4164   }
4165 
4166   // If we've already computed linkage for the anonymous tag, then
4167   // adding a typedef name for the anonymous decl can change that
4168   // linkage, which might be a serious problem.  Diagnose this as
4169   // unsupported and ignore the typedef name.  TODO: we should
4170   // pursue this as a language defect and establish a formal rule
4171   // for how to handle it.
4172   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4173     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4174 
4175     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4176     tagLoc = getLocForEndOfToken(tagLoc);
4177 
4178     llvm::SmallString<40> textToInsert;
4179     textToInsert += ' ';
4180     textToInsert += NewTD->getIdentifier()->getName();
4181     Diag(tagLoc, diag::note_typedef_changes_linkage)
4182         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4183     return;
4184   }
4185 
4186   // Otherwise, set this is the anon-decl typedef for the tag.
4187   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4188 }
4189 
4190 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4191   switch (T) {
4192   case DeclSpec::TST_class:
4193     return 0;
4194   case DeclSpec::TST_struct:
4195     return 1;
4196   case DeclSpec::TST_interface:
4197     return 2;
4198   case DeclSpec::TST_union:
4199     return 3;
4200   case DeclSpec::TST_enum:
4201     return 4;
4202   default:
4203     llvm_unreachable("unexpected type specifier");
4204   }
4205 }
4206 
4207 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4208 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4209 /// parameters to cope with template friend declarations.
4210 Decl *
4211 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4212                                  MultiTemplateParamsArg TemplateParams,
4213                                  bool IsExplicitInstantiation,
4214                                  RecordDecl *&AnonRecord) {
4215   Decl *TagD = nullptr;
4216   TagDecl *Tag = nullptr;
4217   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4218       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4219       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4220       DS.getTypeSpecType() == DeclSpec::TST_union ||
4221       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4222     TagD = DS.getRepAsDecl();
4223 
4224     if (!TagD) // We probably had an error
4225       return nullptr;
4226 
4227     // Note that the above type specs guarantee that the
4228     // type rep is a Decl, whereas in many of the others
4229     // it's a Type.
4230     if (isa<TagDecl>(TagD))
4231       Tag = cast<TagDecl>(TagD);
4232     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4233       Tag = CTD->getTemplatedDecl();
4234   }
4235 
4236   if (Tag) {
4237     handleTagNumbering(Tag, S);
4238     Tag->setFreeStanding();
4239     if (Tag->isInvalidDecl())
4240       return Tag;
4241   }
4242 
4243   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4244     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4245     // or incomplete types shall not be restrict-qualified."
4246     if (TypeQuals & DeclSpec::TQ_restrict)
4247       Diag(DS.getRestrictSpecLoc(),
4248            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4249            << DS.getSourceRange();
4250   }
4251 
4252   if (DS.isInlineSpecified())
4253     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4254         << getLangOpts().CPlusPlus17;
4255 
4256   if (DS.isConstexprSpecified()) {
4257     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4258     // and definitions of functions and variables.
4259     if (Tag)
4260       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4261           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4262     else
4263       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4264     // Don't emit warnings after this error.
4265     return TagD;
4266   }
4267 
4268   DiagnoseFunctionSpecifiers(DS);
4269 
4270   if (DS.isFriendSpecified()) {
4271     // If we're dealing with a decl but not a TagDecl, assume that
4272     // whatever routines created it handled the friendship aspect.
4273     if (TagD && !Tag)
4274       return nullptr;
4275     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4276   }
4277 
4278   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4279   bool IsExplicitSpecialization =
4280     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4281   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4282       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4283       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4284     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4285     // nested-name-specifier unless it is an explicit instantiation
4286     // or an explicit specialization.
4287     //
4288     // FIXME: We allow class template partial specializations here too, per the
4289     // obvious intent of DR1819.
4290     //
4291     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4292     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4293         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4294     return nullptr;
4295   }
4296 
4297   // Track whether this decl-specifier declares anything.
4298   bool DeclaresAnything = true;
4299 
4300   // Handle anonymous struct definitions.
4301   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4302     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4303         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4304       if (getLangOpts().CPlusPlus ||
4305           Record->getDeclContext()->isRecord()) {
4306         // If CurContext is a DeclContext that can contain statements,
4307         // RecursiveASTVisitor won't visit the decls that
4308         // BuildAnonymousStructOrUnion() will put into CurContext.
4309         // Also store them here so that they can be part of the
4310         // DeclStmt that gets created in this case.
4311         // FIXME: Also return the IndirectFieldDecls created by
4312         // BuildAnonymousStructOr union, for the same reason?
4313         if (CurContext->isFunctionOrMethod())
4314           AnonRecord = Record;
4315         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4316                                            Context.getPrintingPolicy());
4317       }
4318 
4319       DeclaresAnything = false;
4320     }
4321   }
4322 
4323   // C11 6.7.2.1p2:
4324   //   A struct-declaration that does not declare an anonymous structure or
4325   //   anonymous union shall contain a struct-declarator-list.
4326   //
4327   // This rule also existed in C89 and C99; the grammar for struct-declaration
4328   // did not permit a struct-declaration without a struct-declarator-list.
4329   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4330       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4331     // Check for Microsoft C extension: anonymous struct/union member.
4332     // Handle 2 kinds of anonymous struct/union:
4333     //   struct STRUCT;
4334     //   union UNION;
4335     // and
4336     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4337     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4338     if ((Tag && Tag->getDeclName()) ||
4339         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4340       RecordDecl *Record = nullptr;
4341       if (Tag)
4342         Record = dyn_cast<RecordDecl>(Tag);
4343       else if (const RecordType *RT =
4344                    DS.getRepAsType().get()->getAsStructureType())
4345         Record = RT->getDecl();
4346       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4347         Record = UT->getDecl();
4348 
4349       if (Record && getLangOpts().MicrosoftExt) {
4350         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4351           << Record->isUnion() << DS.getSourceRange();
4352         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4353       }
4354 
4355       DeclaresAnything = false;
4356     }
4357   }
4358 
4359   // Skip all the checks below if we have a type error.
4360   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4361       (TagD && TagD->isInvalidDecl()))
4362     return TagD;
4363 
4364   if (getLangOpts().CPlusPlus &&
4365       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4366     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4367       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4368           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4369         DeclaresAnything = false;
4370 
4371   if (!DS.isMissingDeclaratorOk()) {
4372     // Customize diagnostic for a typedef missing a name.
4373     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4374       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4375         << DS.getSourceRange();
4376     else
4377       DeclaresAnything = false;
4378   }
4379 
4380   if (DS.isModulePrivateSpecified() &&
4381       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4382     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4383       << Tag->getTagKind()
4384       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4385 
4386   ActOnDocumentableDecl(TagD);
4387 
4388   // C 6.7/2:
4389   //   A declaration [...] shall declare at least a declarator [...], a tag,
4390   //   or the members of an enumeration.
4391   // C++ [dcl.dcl]p3:
4392   //   [If there are no declarators], and except for the declaration of an
4393   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4394   //   names into the program, or shall redeclare a name introduced by a
4395   //   previous declaration.
4396   if (!DeclaresAnything) {
4397     // In C, we allow this as a (popular) extension / bug. Don't bother
4398     // producing further diagnostics for redundant qualifiers after this.
4399     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4400     return TagD;
4401   }
4402 
4403   // C++ [dcl.stc]p1:
4404   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4405   //   init-declarator-list of the declaration shall not be empty.
4406   // C++ [dcl.fct.spec]p1:
4407   //   If a cv-qualifier appears in a decl-specifier-seq, the
4408   //   init-declarator-list of the declaration shall not be empty.
4409   //
4410   // Spurious qualifiers here appear to be valid in C.
4411   unsigned DiagID = diag::warn_standalone_specifier;
4412   if (getLangOpts().CPlusPlus)
4413     DiagID = diag::ext_standalone_specifier;
4414 
4415   // Note that a linkage-specification sets a storage class, but
4416   // 'extern "C" struct foo;' is actually valid and not theoretically
4417   // useless.
4418   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4419     if (SCS == DeclSpec::SCS_mutable)
4420       // Since mutable is not a viable storage class specifier in C, there is
4421       // no reason to treat it as an extension. Instead, diagnose as an error.
4422       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4423     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4424       Diag(DS.getStorageClassSpecLoc(), DiagID)
4425         << DeclSpec::getSpecifierName(SCS);
4426   }
4427 
4428   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4429     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4430       << DeclSpec::getSpecifierName(TSCS);
4431   if (DS.getTypeQualifiers()) {
4432     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4433       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4434     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4435       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4436     // Restrict is covered above.
4437     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4438       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4439     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4440       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4441   }
4442 
4443   // Warn about ignored type attributes, for example:
4444   // __attribute__((aligned)) struct A;
4445   // Attributes should be placed after tag to apply to type declaration.
4446   if (!DS.getAttributes().empty()) {
4447     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4448     if (TypeSpecType == DeclSpec::TST_class ||
4449         TypeSpecType == DeclSpec::TST_struct ||
4450         TypeSpecType == DeclSpec::TST_interface ||
4451         TypeSpecType == DeclSpec::TST_union ||
4452         TypeSpecType == DeclSpec::TST_enum) {
4453       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4454            attrs = attrs->getNext())
4455         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4456             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4457     }
4458   }
4459 
4460   return TagD;
4461 }
4462 
4463 /// We are trying to inject an anonymous member into the given scope;
4464 /// check if there's an existing declaration that can't be overloaded.
4465 ///
4466 /// \return true if this is a forbidden redeclaration
4467 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4468                                          Scope *S,
4469                                          DeclContext *Owner,
4470                                          DeclarationName Name,
4471                                          SourceLocation NameLoc,
4472                                          bool IsUnion) {
4473   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4474                  Sema::ForVisibleRedeclaration);
4475   if (!SemaRef.LookupName(R, S)) return false;
4476 
4477   // Pick a representative declaration.
4478   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4479   assert(PrevDecl && "Expected a non-null Decl");
4480 
4481   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4482     return false;
4483 
4484   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4485     << IsUnion << Name;
4486   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4487 
4488   return true;
4489 }
4490 
4491 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4492 /// anonymous struct or union AnonRecord into the owning context Owner
4493 /// and scope S. This routine will be invoked just after we realize
4494 /// that an unnamed union or struct is actually an anonymous union or
4495 /// struct, e.g.,
4496 ///
4497 /// @code
4498 /// union {
4499 ///   int i;
4500 ///   float f;
4501 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4502 ///    // f into the surrounding scope.x
4503 /// @endcode
4504 ///
4505 /// This routine is recursive, injecting the names of nested anonymous
4506 /// structs/unions into the owning context and scope as well.
4507 static bool
4508 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4509                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4510                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4511   bool Invalid = false;
4512 
4513   // Look every FieldDecl and IndirectFieldDecl with a name.
4514   for (auto *D : AnonRecord->decls()) {
4515     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4516         cast<NamedDecl>(D)->getDeclName()) {
4517       ValueDecl *VD = cast<ValueDecl>(D);
4518       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4519                                        VD->getLocation(),
4520                                        AnonRecord->isUnion())) {
4521         // C++ [class.union]p2:
4522         //   The names of the members of an anonymous union shall be
4523         //   distinct from the names of any other entity in the
4524         //   scope in which the anonymous union is declared.
4525         Invalid = true;
4526       } else {
4527         // C++ [class.union]p2:
4528         //   For the purpose of name lookup, after the anonymous union
4529         //   definition, the members of the anonymous union are
4530         //   considered to have been defined in the scope in which the
4531         //   anonymous union is declared.
4532         unsigned OldChainingSize = Chaining.size();
4533         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4534           Chaining.append(IF->chain_begin(), IF->chain_end());
4535         else
4536           Chaining.push_back(VD);
4537 
4538         assert(Chaining.size() >= 2);
4539         NamedDecl **NamedChain =
4540           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4541         for (unsigned i = 0; i < Chaining.size(); i++)
4542           NamedChain[i] = Chaining[i];
4543 
4544         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4545             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4546             VD->getType(), {NamedChain, Chaining.size()});
4547 
4548         for (const auto *Attr : VD->attrs())
4549           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4550 
4551         IndirectField->setAccess(AS);
4552         IndirectField->setImplicit();
4553         SemaRef.PushOnScopeChains(IndirectField, S);
4554 
4555         // That includes picking up the appropriate access specifier.
4556         if (AS != AS_none) IndirectField->setAccess(AS);
4557 
4558         Chaining.resize(OldChainingSize);
4559       }
4560     }
4561   }
4562 
4563   return Invalid;
4564 }
4565 
4566 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4567 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4568 /// illegal input values are mapped to SC_None.
4569 static StorageClass
4570 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4571   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4572   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4573          "Parser allowed 'typedef' as storage class VarDecl.");
4574   switch (StorageClassSpec) {
4575   case DeclSpec::SCS_unspecified:    return SC_None;
4576   case DeclSpec::SCS_extern:
4577     if (DS.isExternInLinkageSpec())
4578       return SC_None;
4579     return SC_Extern;
4580   case DeclSpec::SCS_static:         return SC_Static;
4581   case DeclSpec::SCS_auto:           return SC_Auto;
4582   case DeclSpec::SCS_register:       return SC_Register;
4583   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4584     // Illegal SCSs map to None: error reporting is up to the caller.
4585   case DeclSpec::SCS_mutable:        // Fall through.
4586   case DeclSpec::SCS_typedef:        return SC_None;
4587   }
4588   llvm_unreachable("unknown storage class specifier");
4589 }
4590 
4591 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4592   assert(Record->hasInClassInitializer());
4593 
4594   for (const auto *I : Record->decls()) {
4595     const auto *FD = dyn_cast<FieldDecl>(I);
4596     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4597       FD = IFD->getAnonField();
4598     if (FD && FD->hasInClassInitializer())
4599       return FD->getLocation();
4600   }
4601 
4602   llvm_unreachable("couldn't find in-class initializer");
4603 }
4604 
4605 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4606                                       SourceLocation DefaultInitLoc) {
4607   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4608     return;
4609 
4610   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4611   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4612 }
4613 
4614 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4615                                       CXXRecordDecl *AnonUnion) {
4616   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4617     return;
4618 
4619   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4620 }
4621 
4622 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4623 /// anonymous structure or union. Anonymous unions are a C++ feature
4624 /// (C++ [class.union]) and a C11 feature; anonymous structures
4625 /// are a C11 feature and GNU C++ extension.
4626 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4627                                         AccessSpecifier AS,
4628                                         RecordDecl *Record,
4629                                         const PrintingPolicy &Policy) {
4630   DeclContext *Owner = Record->getDeclContext();
4631 
4632   // Diagnose whether this anonymous struct/union is an extension.
4633   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4634     Diag(Record->getLocation(), diag::ext_anonymous_union);
4635   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4636     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4637   else if (!Record->isUnion() && !getLangOpts().C11)
4638     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4639 
4640   // C and C++ require different kinds of checks for anonymous
4641   // structs/unions.
4642   bool Invalid = false;
4643   if (getLangOpts().CPlusPlus) {
4644     const char *PrevSpec = nullptr;
4645     unsigned DiagID;
4646     if (Record->isUnion()) {
4647       // C++ [class.union]p6:
4648       //   Anonymous unions declared in a named namespace or in the
4649       //   global namespace shall be declared static.
4650       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4651           (isa<TranslationUnitDecl>(Owner) ||
4652            (isa<NamespaceDecl>(Owner) &&
4653             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4654         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4655           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4656 
4657         // Recover by adding 'static'.
4658         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4659                                PrevSpec, DiagID, Policy);
4660       }
4661       // C++ [class.union]p6:
4662       //   A storage class is not allowed in a declaration of an
4663       //   anonymous union in a class scope.
4664       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4665                isa<RecordDecl>(Owner)) {
4666         Diag(DS.getStorageClassSpecLoc(),
4667              diag::err_anonymous_union_with_storage_spec)
4668           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4669 
4670         // Recover by removing the storage specifier.
4671         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4672                                SourceLocation(),
4673                                PrevSpec, DiagID, Context.getPrintingPolicy());
4674       }
4675     }
4676 
4677     // Ignore const/volatile/restrict qualifiers.
4678     if (DS.getTypeQualifiers()) {
4679       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4680         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4681           << Record->isUnion() << "const"
4682           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4683       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4684         Diag(DS.getVolatileSpecLoc(),
4685              diag::ext_anonymous_struct_union_qualified)
4686           << Record->isUnion() << "volatile"
4687           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4688       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4689         Diag(DS.getRestrictSpecLoc(),
4690              diag::ext_anonymous_struct_union_qualified)
4691           << Record->isUnion() << "restrict"
4692           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4693       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4694         Diag(DS.getAtomicSpecLoc(),
4695              diag::ext_anonymous_struct_union_qualified)
4696           << Record->isUnion() << "_Atomic"
4697           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4698       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4699         Diag(DS.getUnalignedSpecLoc(),
4700              diag::ext_anonymous_struct_union_qualified)
4701           << Record->isUnion() << "__unaligned"
4702           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4703 
4704       DS.ClearTypeQualifiers();
4705     }
4706 
4707     // C++ [class.union]p2:
4708     //   The member-specification of an anonymous union shall only
4709     //   define non-static data members. [Note: nested types and
4710     //   functions cannot be declared within an anonymous union. ]
4711     for (auto *Mem : Record->decls()) {
4712       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4713         // C++ [class.union]p3:
4714         //   An anonymous union shall not have private or protected
4715         //   members (clause 11).
4716         assert(FD->getAccess() != AS_none);
4717         if (FD->getAccess() != AS_public) {
4718           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4719             << Record->isUnion() << (FD->getAccess() == AS_protected);
4720           Invalid = true;
4721         }
4722 
4723         // C++ [class.union]p1
4724         //   An object of a class with a non-trivial constructor, a non-trivial
4725         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4726         //   assignment operator cannot be a member of a union, nor can an
4727         //   array of such objects.
4728         if (CheckNontrivialField(FD))
4729           Invalid = true;
4730       } else if (Mem->isImplicit()) {
4731         // Any implicit members are fine.
4732       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4733         // This is a type that showed up in an
4734         // elaborated-type-specifier inside the anonymous struct or
4735         // union, but which actually declares a type outside of the
4736         // anonymous struct or union. It's okay.
4737       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4738         if (!MemRecord->isAnonymousStructOrUnion() &&
4739             MemRecord->getDeclName()) {
4740           // Visual C++ allows type definition in anonymous struct or union.
4741           if (getLangOpts().MicrosoftExt)
4742             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4743               << Record->isUnion();
4744           else {
4745             // This is a nested type declaration.
4746             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4747               << Record->isUnion();
4748             Invalid = true;
4749           }
4750         } else {
4751           // This is an anonymous type definition within another anonymous type.
4752           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4753           // not part of standard C++.
4754           Diag(MemRecord->getLocation(),
4755                diag::ext_anonymous_record_with_anonymous_type)
4756             << Record->isUnion();
4757         }
4758       } else if (isa<AccessSpecDecl>(Mem)) {
4759         // Any access specifier is fine.
4760       } else if (isa<StaticAssertDecl>(Mem)) {
4761         // In C++1z, static_assert declarations are also fine.
4762       } else {
4763         // We have something that isn't a non-static data
4764         // member. Complain about it.
4765         unsigned DK = diag::err_anonymous_record_bad_member;
4766         if (isa<TypeDecl>(Mem))
4767           DK = diag::err_anonymous_record_with_type;
4768         else if (isa<FunctionDecl>(Mem))
4769           DK = diag::err_anonymous_record_with_function;
4770         else if (isa<VarDecl>(Mem))
4771           DK = diag::err_anonymous_record_with_static;
4772 
4773         // Visual C++ allows type definition in anonymous struct or union.
4774         if (getLangOpts().MicrosoftExt &&
4775             DK == diag::err_anonymous_record_with_type)
4776           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4777             << Record->isUnion();
4778         else {
4779           Diag(Mem->getLocation(), DK) << Record->isUnion();
4780           Invalid = true;
4781         }
4782       }
4783     }
4784 
4785     // C++11 [class.union]p8 (DR1460):
4786     //   At most one variant member of a union may have a
4787     //   brace-or-equal-initializer.
4788     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4789         Owner->isRecord())
4790       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4791                                 cast<CXXRecordDecl>(Record));
4792   }
4793 
4794   if (!Record->isUnion() && !Owner->isRecord()) {
4795     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4796       << getLangOpts().CPlusPlus;
4797     Invalid = true;
4798   }
4799 
4800   // Mock up a declarator.
4801   Declarator Dc(DS, DeclaratorContext::MemberContext);
4802   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4803   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4804 
4805   // Create a declaration for this anonymous struct/union.
4806   NamedDecl *Anon = nullptr;
4807   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4808     Anon = FieldDecl::Create(Context, OwningClass,
4809                              DS.getLocStart(),
4810                              Record->getLocation(),
4811                              /*IdentifierInfo=*/nullptr,
4812                              Context.getTypeDeclType(Record),
4813                              TInfo,
4814                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4815                              /*InitStyle=*/ICIS_NoInit);
4816     Anon->setAccess(AS);
4817     if (getLangOpts().CPlusPlus)
4818       FieldCollector->Add(cast<FieldDecl>(Anon));
4819   } else {
4820     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4821     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4822     if (SCSpec == DeclSpec::SCS_mutable) {
4823       // mutable can only appear on non-static class members, so it's always
4824       // an error here
4825       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4826       Invalid = true;
4827       SC = SC_None;
4828     }
4829 
4830     Anon = VarDecl::Create(Context, Owner,
4831                            DS.getLocStart(),
4832                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4833                            Context.getTypeDeclType(Record),
4834                            TInfo, SC);
4835 
4836     // Default-initialize the implicit variable. This initialization will be
4837     // trivial in almost all cases, except if a union member has an in-class
4838     // initializer:
4839     //   union { int n = 0; };
4840     ActOnUninitializedDecl(Anon);
4841   }
4842   Anon->setImplicit();
4843 
4844   // Mark this as an anonymous struct/union type.
4845   Record->setAnonymousStructOrUnion(true);
4846 
4847   // Add the anonymous struct/union object to the current
4848   // context. We'll be referencing this object when we refer to one of
4849   // its members.
4850   Owner->addDecl(Anon);
4851 
4852   // Inject the members of the anonymous struct/union into the owning
4853   // context and into the identifier resolver chain for name lookup
4854   // purposes.
4855   SmallVector<NamedDecl*, 2> Chain;
4856   Chain.push_back(Anon);
4857 
4858   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4859     Invalid = true;
4860 
4861   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4862     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4863       Decl *ManglingContextDecl;
4864       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4865               NewVD->getDeclContext(), ManglingContextDecl)) {
4866         Context.setManglingNumber(
4867             NewVD, MCtx->getManglingNumber(
4868                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4869         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4870       }
4871     }
4872   }
4873 
4874   if (Invalid)
4875     Anon->setInvalidDecl();
4876 
4877   return Anon;
4878 }
4879 
4880 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4881 /// Microsoft C anonymous structure.
4882 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4883 /// Example:
4884 ///
4885 /// struct A { int a; };
4886 /// struct B { struct A; int b; };
4887 ///
4888 /// void foo() {
4889 ///   B var;
4890 ///   var.a = 3;
4891 /// }
4892 ///
4893 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4894                                            RecordDecl *Record) {
4895   assert(Record && "expected a record!");
4896 
4897   // Mock up a declarator.
4898   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4899   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4900   assert(TInfo && "couldn't build declarator info for anonymous struct");
4901 
4902   auto *ParentDecl = cast<RecordDecl>(CurContext);
4903   QualType RecTy = Context.getTypeDeclType(Record);
4904 
4905   // Create a declaration for this anonymous struct.
4906   NamedDecl *Anon = FieldDecl::Create(Context,
4907                              ParentDecl,
4908                              DS.getLocStart(),
4909                              DS.getLocStart(),
4910                              /*IdentifierInfo=*/nullptr,
4911                              RecTy,
4912                              TInfo,
4913                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4914                              /*InitStyle=*/ICIS_NoInit);
4915   Anon->setImplicit();
4916 
4917   // Add the anonymous struct object to the current context.
4918   CurContext->addDecl(Anon);
4919 
4920   // Inject the members of the anonymous struct into the current
4921   // context and into the identifier resolver chain for name lookup
4922   // purposes.
4923   SmallVector<NamedDecl*, 2> Chain;
4924   Chain.push_back(Anon);
4925 
4926   RecordDecl *RecordDef = Record->getDefinition();
4927   if (RequireCompleteType(Anon->getLocation(), RecTy,
4928                           diag::err_field_incomplete) ||
4929       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4930                                           AS_none, Chain)) {
4931     Anon->setInvalidDecl();
4932     ParentDecl->setInvalidDecl();
4933   }
4934 
4935   return Anon;
4936 }
4937 
4938 /// GetNameForDeclarator - Determine the full declaration name for the
4939 /// given Declarator.
4940 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4941   return GetNameFromUnqualifiedId(D.getName());
4942 }
4943 
4944 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4945 DeclarationNameInfo
4946 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4947   DeclarationNameInfo NameInfo;
4948   NameInfo.setLoc(Name.StartLocation);
4949 
4950   switch (Name.getKind()) {
4951 
4952   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4953   case UnqualifiedIdKind::IK_Identifier:
4954     NameInfo.setName(Name.Identifier);
4955     NameInfo.setLoc(Name.StartLocation);
4956     return NameInfo;
4957 
4958   case UnqualifiedIdKind::IK_DeductionGuideName: {
4959     // C++ [temp.deduct.guide]p3:
4960     //   The simple-template-id shall name a class template specialization.
4961     //   The template-name shall be the same identifier as the template-name
4962     //   of the simple-template-id.
4963     // These together intend to imply that the template-name shall name a
4964     // class template.
4965     // FIXME: template<typename T> struct X {};
4966     //        template<typename T> using Y = X<T>;
4967     //        Y(int) -> Y<int>;
4968     //   satisfies these rules but does not name a class template.
4969     TemplateName TN = Name.TemplateName.get().get();
4970     auto *Template = TN.getAsTemplateDecl();
4971     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4972       Diag(Name.StartLocation,
4973            diag::err_deduction_guide_name_not_class_template)
4974         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4975       if (Template)
4976         Diag(Template->getLocation(), diag::note_template_decl_here);
4977       return DeclarationNameInfo();
4978     }
4979 
4980     NameInfo.setName(
4981         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4982     NameInfo.setLoc(Name.StartLocation);
4983     return NameInfo;
4984   }
4985 
4986   case UnqualifiedIdKind::IK_OperatorFunctionId:
4987     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4988                                            Name.OperatorFunctionId.Operator));
4989     NameInfo.setLoc(Name.StartLocation);
4990     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4991       = Name.OperatorFunctionId.SymbolLocations[0];
4992     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4993       = Name.EndLocation.getRawEncoding();
4994     return NameInfo;
4995 
4996   case UnqualifiedIdKind::IK_LiteralOperatorId:
4997     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4998                                                            Name.Identifier));
4999     NameInfo.setLoc(Name.StartLocation);
5000     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5001     return NameInfo;
5002 
5003   case UnqualifiedIdKind::IK_ConversionFunctionId: {
5004     TypeSourceInfo *TInfo;
5005     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5006     if (Ty.isNull())
5007       return DeclarationNameInfo();
5008     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5009                                                Context.getCanonicalType(Ty)));
5010     NameInfo.setLoc(Name.StartLocation);
5011     NameInfo.setNamedTypeInfo(TInfo);
5012     return NameInfo;
5013   }
5014 
5015   case UnqualifiedIdKind::IK_ConstructorName: {
5016     TypeSourceInfo *TInfo;
5017     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5018     if (Ty.isNull())
5019       return DeclarationNameInfo();
5020     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5021                                               Context.getCanonicalType(Ty)));
5022     NameInfo.setLoc(Name.StartLocation);
5023     NameInfo.setNamedTypeInfo(TInfo);
5024     return NameInfo;
5025   }
5026 
5027   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5028     // In well-formed code, we can only have a constructor
5029     // template-id that refers to the current context, so go there
5030     // to find the actual type being constructed.
5031     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5032     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5033       return DeclarationNameInfo();
5034 
5035     // Determine the type of the class being constructed.
5036     QualType CurClassType = Context.getTypeDeclType(CurClass);
5037 
5038     // FIXME: Check two things: that the template-id names the same type as
5039     // CurClassType, and that the template-id does not occur when the name
5040     // was qualified.
5041 
5042     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5043                                     Context.getCanonicalType(CurClassType)));
5044     NameInfo.setLoc(Name.StartLocation);
5045     // FIXME: should we retrieve TypeSourceInfo?
5046     NameInfo.setNamedTypeInfo(nullptr);
5047     return NameInfo;
5048   }
5049 
5050   case UnqualifiedIdKind::IK_DestructorName: {
5051     TypeSourceInfo *TInfo;
5052     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5053     if (Ty.isNull())
5054       return DeclarationNameInfo();
5055     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5056                                               Context.getCanonicalType(Ty)));
5057     NameInfo.setLoc(Name.StartLocation);
5058     NameInfo.setNamedTypeInfo(TInfo);
5059     return NameInfo;
5060   }
5061 
5062   case UnqualifiedIdKind::IK_TemplateId: {
5063     TemplateName TName = Name.TemplateId->Template.get();
5064     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5065     return Context.getNameForTemplate(TName, TNameLoc);
5066   }
5067 
5068   } // switch (Name.getKind())
5069 
5070   llvm_unreachable("Unknown name kind");
5071 }
5072 
5073 static QualType getCoreType(QualType Ty) {
5074   do {
5075     if (Ty->isPointerType() || Ty->isReferenceType())
5076       Ty = Ty->getPointeeType();
5077     else if (Ty->isArrayType())
5078       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5079     else
5080       return Ty.withoutLocalFastQualifiers();
5081   } while (true);
5082 }
5083 
5084 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5085 /// and Definition have "nearly" matching parameters. This heuristic is
5086 /// used to improve diagnostics in the case where an out-of-line function
5087 /// definition doesn't match any declaration within the class or namespace.
5088 /// Also sets Params to the list of indices to the parameters that differ
5089 /// between the declaration and the definition. If hasSimilarParameters
5090 /// returns true and Params is empty, then all of the parameters match.
5091 static bool hasSimilarParameters(ASTContext &Context,
5092                                      FunctionDecl *Declaration,
5093                                      FunctionDecl *Definition,
5094                                      SmallVectorImpl<unsigned> &Params) {
5095   Params.clear();
5096   if (Declaration->param_size() != Definition->param_size())
5097     return false;
5098   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5099     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5100     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5101 
5102     // The parameter types are identical
5103     if (Context.hasSameType(DefParamTy, DeclParamTy))
5104       continue;
5105 
5106     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5107     QualType DefParamBaseTy = getCoreType(DefParamTy);
5108     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5109     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5110 
5111     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5112         (DeclTyName && DeclTyName == DefTyName))
5113       Params.push_back(Idx);
5114     else  // The two parameters aren't even close
5115       return false;
5116   }
5117 
5118   return true;
5119 }
5120 
5121 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5122 /// declarator needs to be rebuilt in the current instantiation.
5123 /// Any bits of declarator which appear before the name are valid for
5124 /// consideration here.  That's specifically the type in the decl spec
5125 /// and the base type in any member-pointer chunks.
5126 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5127                                                     DeclarationName Name) {
5128   // The types we specifically need to rebuild are:
5129   //   - typenames, typeofs, and decltypes
5130   //   - types which will become injected class names
5131   // Of course, we also need to rebuild any type referencing such a
5132   // type.  It's safest to just say "dependent", but we call out a
5133   // few cases here.
5134 
5135   DeclSpec &DS = D.getMutableDeclSpec();
5136   switch (DS.getTypeSpecType()) {
5137   case DeclSpec::TST_typename:
5138   case DeclSpec::TST_typeofType:
5139   case DeclSpec::TST_underlyingType:
5140   case DeclSpec::TST_atomic: {
5141     // Grab the type from the parser.
5142     TypeSourceInfo *TSI = nullptr;
5143     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5144     if (T.isNull() || !T->isDependentType()) break;
5145 
5146     // Make sure there's a type source info.  This isn't really much
5147     // of a waste; most dependent types should have type source info
5148     // attached already.
5149     if (!TSI)
5150       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5151 
5152     // Rebuild the type in the current instantiation.
5153     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5154     if (!TSI) return true;
5155 
5156     // Store the new type back in the decl spec.
5157     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5158     DS.UpdateTypeRep(LocType);
5159     break;
5160   }
5161 
5162   case DeclSpec::TST_decltype:
5163   case DeclSpec::TST_typeofExpr: {
5164     Expr *E = DS.getRepAsExpr();
5165     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5166     if (Result.isInvalid()) return true;
5167     DS.UpdateExprRep(Result.get());
5168     break;
5169   }
5170 
5171   default:
5172     // Nothing to do for these decl specs.
5173     break;
5174   }
5175 
5176   // It doesn't matter what order we do this in.
5177   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5178     DeclaratorChunk &Chunk = D.getTypeObject(I);
5179 
5180     // The only type information in the declarator which can come
5181     // before the declaration name is the base type of a member
5182     // pointer.
5183     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5184       continue;
5185 
5186     // Rebuild the scope specifier in-place.
5187     CXXScopeSpec &SS = Chunk.Mem.Scope();
5188     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5189       return true;
5190   }
5191 
5192   return false;
5193 }
5194 
5195 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5196   D.setFunctionDefinitionKind(FDK_Declaration);
5197   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5198 
5199   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5200       Dcl && Dcl->getDeclContext()->isFileContext())
5201     Dcl->setTopLevelDeclInObjCContainer();
5202 
5203   if (getLangOpts().OpenCL)
5204     setCurrentOpenCLExtensionForDecl(Dcl);
5205 
5206   return Dcl;
5207 }
5208 
5209 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5210 ///   If T is the name of a class, then each of the following shall have a
5211 ///   name different from T:
5212 ///     - every static data member of class T;
5213 ///     - every member function of class T
5214 ///     - every member of class T that is itself a type;
5215 /// \returns true if the declaration name violates these rules.
5216 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5217                                    DeclarationNameInfo NameInfo) {
5218   DeclarationName Name = NameInfo.getName();
5219 
5220   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5221   while (Record && Record->isAnonymousStructOrUnion())
5222     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5223   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5224     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5225     return true;
5226   }
5227 
5228   return false;
5229 }
5230 
5231 /// \brief Diagnose a declaration whose declarator-id has the given
5232 /// nested-name-specifier.
5233 ///
5234 /// \param SS The nested-name-specifier of the declarator-id.
5235 ///
5236 /// \param DC The declaration context to which the nested-name-specifier
5237 /// resolves.
5238 ///
5239 /// \param Name The name of the entity being declared.
5240 ///
5241 /// \param Loc The location of the name of the entity being declared.
5242 ///
5243 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5244 /// we're declaring an explicit / partial specialization / instantiation.
5245 ///
5246 /// \returns true if we cannot safely recover from this error, false otherwise.
5247 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5248                                         DeclarationName Name,
5249                                         SourceLocation Loc, bool IsTemplateId) {
5250   DeclContext *Cur = CurContext;
5251   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5252     Cur = Cur->getParent();
5253 
5254   // If the user provided a superfluous scope specifier that refers back to the
5255   // class in which the entity is already declared, diagnose and ignore it.
5256   //
5257   // class X {
5258   //   void X::f();
5259   // };
5260   //
5261   // Note, it was once ill-formed to give redundant qualification in all
5262   // contexts, but that rule was removed by DR482.
5263   if (Cur->Equals(DC)) {
5264     if (Cur->isRecord()) {
5265       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5266                                       : diag::err_member_extra_qualification)
5267         << Name << FixItHint::CreateRemoval(SS.getRange());
5268       SS.clear();
5269     } else {
5270       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5271     }
5272     return false;
5273   }
5274 
5275   // Check whether the qualifying scope encloses the scope of the original
5276   // declaration. For a template-id, we perform the checks in
5277   // CheckTemplateSpecializationScope.
5278   if (!Cur->Encloses(DC) && !IsTemplateId) {
5279     if (Cur->isRecord())
5280       Diag(Loc, diag::err_member_qualification)
5281         << Name << SS.getRange();
5282     else if (isa<TranslationUnitDecl>(DC))
5283       Diag(Loc, diag::err_invalid_declarator_global_scope)
5284         << Name << SS.getRange();
5285     else if (isa<FunctionDecl>(Cur))
5286       Diag(Loc, diag::err_invalid_declarator_in_function)
5287         << Name << SS.getRange();
5288     else if (isa<BlockDecl>(Cur))
5289       Diag(Loc, diag::err_invalid_declarator_in_block)
5290         << Name << SS.getRange();
5291     else
5292       Diag(Loc, diag::err_invalid_declarator_scope)
5293       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5294 
5295     return true;
5296   }
5297 
5298   if (Cur->isRecord()) {
5299     // Cannot qualify members within a class.
5300     Diag(Loc, diag::err_member_qualification)
5301       << Name << SS.getRange();
5302     SS.clear();
5303 
5304     // C++ constructors and destructors with incorrect scopes can break
5305     // our AST invariants by having the wrong underlying types. If
5306     // that's the case, then drop this declaration entirely.
5307     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5308          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5309         !Context.hasSameType(Name.getCXXNameType(),
5310                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5311       return true;
5312 
5313     return false;
5314   }
5315 
5316   // C++11 [dcl.meaning]p1:
5317   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5318   //   not begin with a decltype-specifer"
5319   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5320   while (SpecLoc.getPrefix())
5321     SpecLoc = SpecLoc.getPrefix();
5322   if (dyn_cast_or_null<DecltypeType>(
5323         SpecLoc.getNestedNameSpecifier()->getAsType()))
5324     Diag(Loc, diag::err_decltype_in_declarator)
5325       << SpecLoc.getTypeLoc().getSourceRange();
5326 
5327   return false;
5328 }
5329 
5330 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5331                                   MultiTemplateParamsArg TemplateParamLists) {
5332   // TODO: consider using NameInfo for diagnostic.
5333   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5334   DeclarationName Name = NameInfo.getName();
5335 
5336   // All of these full declarators require an identifier.  If it doesn't have
5337   // one, the ParsedFreeStandingDeclSpec action should be used.
5338   if (D.isDecompositionDeclarator()) {
5339     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5340   } else if (!Name) {
5341     if (!D.isInvalidType())  // Reject this if we think it is valid.
5342       Diag(D.getDeclSpec().getLocStart(),
5343            diag::err_declarator_need_ident)
5344         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5345     return nullptr;
5346   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5347     return nullptr;
5348 
5349   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5350   // we find one that is.
5351   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5352          (S->getFlags() & Scope::TemplateParamScope) != 0)
5353     S = S->getParent();
5354 
5355   DeclContext *DC = CurContext;
5356   if (D.getCXXScopeSpec().isInvalid())
5357     D.setInvalidType();
5358   else if (D.getCXXScopeSpec().isSet()) {
5359     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5360                                         UPPC_DeclarationQualifier))
5361       return nullptr;
5362 
5363     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5364     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5365     if (!DC || isa<EnumDecl>(DC)) {
5366       // If we could not compute the declaration context, it's because the
5367       // declaration context is dependent but does not refer to a class,
5368       // class template, or class template partial specialization. Complain
5369       // and return early, to avoid the coming semantic disaster.
5370       Diag(D.getIdentifierLoc(),
5371            diag::err_template_qualified_declarator_no_match)
5372         << D.getCXXScopeSpec().getScopeRep()
5373         << D.getCXXScopeSpec().getRange();
5374       return nullptr;
5375     }
5376     bool IsDependentContext = DC->isDependentContext();
5377 
5378     if (!IsDependentContext &&
5379         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5380       return nullptr;
5381 
5382     // If a class is incomplete, do not parse entities inside it.
5383     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5384       Diag(D.getIdentifierLoc(),
5385            diag::err_member_def_undefined_record)
5386         << Name << DC << D.getCXXScopeSpec().getRange();
5387       return nullptr;
5388     }
5389     if (!D.getDeclSpec().isFriendSpecified()) {
5390       if (diagnoseQualifiedDeclaration(
5391               D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5392               D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5393         if (DC->isRecord())
5394           return nullptr;
5395 
5396         D.setInvalidType();
5397       }
5398     }
5399 
5400     // Check whether we need to rebuild the type of the given
5401     // declaration in the current instantiation.
5402     if (EnteringContext && IsDependentContext &&
5403         TemplateParamLists.size() != 0) {
5404       ContextRAII SavedContext(*this, DC);
5405       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5406         D.setInvalidType();
5407     }
5408   }
5409 
5410   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5411   QualType R = TInfo->getType();
5412 
5413   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5414                                       UPPC_DeclarationType))
5415     D.setInvalidType();
5416 
5417   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5418                         forRedeclarationInCurContext());
5419 
5420   // See if this is a redefinition of a variable in the same scope.
5421   if (!D.getCXXScopeSpec().isSet()) {
5422     bool IsLinkageLookup = false;
5423     bool CreateBuiltins = false;
5424 
5425     // If the declaration we're planning to build will be a function
5426     // or object with linkage, then look for another declaration with
5427     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5428     //
5429     // If the declaration we're planning to build will be declared with
5430     // external linkage in the translation unit, create any builtin with
5431     // the same name.
5432     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5433       /* Do nothing*/;
5434     else if (CurContext->isFunctionOrMethod() &&
5435              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5436               R->isFunctionType())) {
5437       IsLinkageLookup = true;
5438       CreateBuiltins =
5439           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5440     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5441                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5442       CreateBuiltins = true;
5443 
5444     if (IsLinkageLookup) {
5445       Previous.clear(LookupRedeclarationWithLinkage);
5446       Previous.setRedeclarationKind(ForExternalRedeclaration);
5447     }
5448 
5449     LookupName(Previous, S, CreateBuiltins);
5450   } else { // Something like "int foo::x;"
5451     LookupQualifiedName(Previous, DC);
5452 
5453     // C++ [dcl.meaning]p1:
5454     //   When the declarator-id is qualified, the declaration shall refer to a
5455     //  previously declared member of the class or namespace to which the
5456     //  qualifier refers (or, in the case of a namespace, of an element of the
5457     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5458     //  thereof; [...]
5459     //
5460     // Note that we already checked the context above, and that we do not have
5461     // enough information to make sure that Previous contains the declaration
5462     // we want to match. For example, given:
5463     //
5464     //   class X {
5465     //     void f();
5466     //     void f(float);
5467     //   };
5468     //
5469     //   void X::f(int) { } // ill-formed
5470     //
5471     // In this case, Previous will point to the overload set
5472     // containing the two f's declared in X, but neither of them
5473     // matches.
5474 
5475     // C++ [dcl.meaning]p1:
5476     //   [...] the member shall not merely have been introduced by a
5477     //   using-declaration in the scope of the class or namespace nominated by
5478     //   the nested-name-specifier of the declarator-id.
5479     RemoveUsingDecls(Previous);
5480   }
5481 
5482   if (Previous.isSingleResult() &&
5483       Previous.getFoundDecl()->isTemplateParameter()) {
5484     // Maybe we will complain about the shadowed template parameter.
5485     if (!D.isInvalidType())
5486       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5487                                       Previous.getFoundDecl());
5488 
5489     // Just pretend that we didn't see the previous declaration.
5490     Previous.clear();
5491   }
5492 
5493   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5494     // Forget that the previous declaration is the injected-class-name.
5495     Previous.clear();
5496 
5497   // In C++, the previous declaration we find might be a tag type
5498   // (class or enum). In this case, the new declaration will hide the
5499   // tag type. Note that this applies to functions, function templates, and
5500   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5501   if (Previous.isSingleTagDecl() &&
5502       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5503       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5504     Previous.clear();
5505 
5506   // Check that there are no default arguments other than in the parameters
5507   // of a function declaration (C++ only).
5508   if (getLangOpts().CPlusPlus)
5509     CheckExtraCXXDefaultArguments(D);
5510 
5511   NamedDecl *New;
5512 
5513   bool AddToScope = true;
5514   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5515     if (TemplateParamLists.size()) {
5516       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5517       return nullptr;
5518     }
5519 
5520     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5521   } else if (R->isFunctionType()) {
5522     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5523                                   TemplateParamLists,
5524                                   AddToScope);
5525   } else {
5526     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5527                                   AddToScope);
5528   }
5529 
5530   if (!New)
5531     return nullptr;
5532 
5533   // If this has an identifier and is not a function template specialization,
5534   // add it to the scope stack.
5535   if (New->getDeclName() && AddToScope) {
5536     // Only make a locally-scoped extern declaration visible if it is the first
5537     // declaration of this entity. Qualified lookup for such an entity should
5538     // only find this declaration if there is no visible declaration of it.
5539     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5540     PushOnScopeChains(New, S, AddToContext);
5541     if (!AddToContext)
5542       CurContext->addHiddenDecl(New);
5543   }
5544 
5545   if (isInOpenMPDeclareTargetContext())
5546     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5547 
5548   return New;
5549 }
5550 
5551 /// Helper method to turn variable array types into constant array
5552 /// types in certain situations which would otherwise be errors (for
5553 /// GCC compatibility).
5554 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5555                                                     ASTContext &Context,
5556                                                     bool &SizeIsNegative,
5557                                                     llvm::APSInt &Oversized) {
5558   // This method tries to turn a variable array into a constant
5559   // array even when the size isn't an ICE.  This is necessary
5560   // for compatibility with code that depends on gcc's buggy
5561   // constant expression folding, like struct {char x[(int)(char*)2];}
5562   SizeIsNegative = false;
5563   Oversized = 0;
5564 
5565   if (T->isDependentType())
5566     return QualType();
5567 
5568   QualifierCollector Qs;
5569   const Type *Ty = Qs.strip(T);
5570 
5571   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5572     QualType Pointee = PTy->getPointeeType();
5573     QualType FixedType =
5574         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5575                                             Oversized);
5576     if (FixedType.isNull()) return FixedType;
5577     FixedType = Context.getPointerType(FixedType);
5578     return Qs.apply(Context, FixedType);
5579   }
5580   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5581     QualType Inner = PTy->getInnerType();
5582     QualType FixedType =
5583         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5584                                             Oversized);
5585     if (FixedType.isNull()) return FixedType;
5586     FixedType = Context.getParenType(FixedType);
5587     return Qs.apply(Context, FixedType);
5588   }
5589 
5590   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5591   if (!VLATy)
5592     return QualType();
5593   // FIXME: We should probably handle this case
5594   if (VLATy->getElementType()->isVariablyModifiedType())
5595     return QualType();
5596 
5597   llvm::APSInt Res;
5598   if (!VLATy->getSizeExpr() ||
5599       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5600     return QualType();
5601 
5602   // Check whether the array size is negative.
5603   if (Res.isSigned() && Res.isNegative()) {
5604     SizeIsNegative = true;
5605     return QualType();
5606   }
5607 
5608   // Check whether the array is too large to be addressed.
5609   unsigned ActiveSizeBits
5610     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5611                                               Res);
5612   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5613     Oversized = Res;
5614     return QualType();
5615   }
5616 
5617   return Context.getConstantArrayType(VLATy->getElementType(),
5618                                       Res, ArrayType::Normal, 0);
5619 }
5620 
5621 static void
5622 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5623   SrcTL = SrcTL.getUnqualifiedLoc();
5624   DstTL = DstTL.getUnqualifiedLoc();
5625   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5626     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5627     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5628                                       DstPTL.getPointeeLoc());
5629     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5630     return;
5631   }
5632   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5633     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5634     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5635                                       DstPTL.getInnerLoc());
5636     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5637     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5638     return;
5639   }
5640   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5641   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5642   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5643   TypeLoc DstElemTL = DstATL.getElementLoc();
5644   DstElemTL.initializeFullCopy(SrcElemTL);
5645   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5646   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5647   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5648 }
5649 
5650 /// Helper method to turn variable array types into constant array
5651 /// types in certain situations which would otherwise be errors (for
5652 /// GCC compatibility).
5653 static TypeSourceInfo*
5654 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5655                                               ASTContext &Context,
5656                                               bool &SizeIsNegative,
5657                                               llvm::APSInt &Oversized) {
5658   QualType FixedTy
5659     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5660                                           SizeIsNegative, Oversized);
5661   if (FixedTy.isNull())
5662     return nullptr;
5663   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5664   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5665                                     FixedTInfo->getTypeLoc());
5666   return FixedTInfo;
5667 }
5668 
5669 /// \brief Register the given locally-scoped extern "C" declaration so
5670 /// that it can be found later for redeclarations. We include any extern "C"
5671 /// declaration that is not visible in the translation unit here, not just
5672 /// function-scope declarations.
5673 void
5674 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5675   if (!getLangOpts().CPlusPlus &&
5676       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5677     // Don't need to track declarations in the TU in C.
5678     return;
5679 
5680   // Note that we have a locally-scoped external with this name.
5681   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5682 }
5683 
5684 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5685   // FIXME: We can have multiple results via __attribute__((overloadable)).
5686   auto Result = Context.getExternCContextDecl()->lookup(Name);
5687   return Result.empty() ? nullptr : *Result.begin();
5688 }
5689 
5690 /// \brief Diagnose function specifiers on a declaration of an identifier that
5691 /// does not identify a function.
5692 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5693   // FIXME: We should probably indicate the identifier in question to avoid
5694   // confusion for constructs like "virtual int a(), b;"
5695   if (DS.isVirtualSpecified())
5696     Diag(DS.getVirtualSpecLoc(),
5697          diag::err_virtual_non_function);
5698 
5699   if (DS.isExplicitSpecified())
5700     Diag(DS.getExplicitSpecLoc(),
5701          diag::err_explicit_non_function);
5702 
5703   if (DS.isNoreturnSpecified())
5704     Diag(DS.getNoreturnSpecLoc(),
5705          diag::err_noreturn_non_function);
5706 }
5707 
5708 NamedDecl*
5709 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5710                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5711   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5712   if (D.getCXXScopeSpec().isSet()) {
5713     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5714       << D.getCXXScopeSpec().getRange();
5715     D.setInvalidType();
5716     // Pretend we didn't see the scope specifier.
5717     DC = CurContext;
5718     Previous.clear();
5719   }
5720 
5721   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5722 
5723   if (D.getDeclSpec().isInlineSpecified())
5724     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5725         << getLangOpts().CPlusPlus17;
5726   if (D.getDeclSpec().isConstexprSpecified())
5727     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5728       << 1;
5729 
5730   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5731     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5732       Diag(D.getName().StartLocation,
5733            diag::err_deduction_guide_invalid_specifier)
5734           << "typedef";
5735     else
5736       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5737           << D.getName().getSourceRange();
5738     return nullptr;
5739   }
5740 
5741   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5742   if (!NewTD) return nullptr;
5743 
5744   // Handle attributes prior to checking for duplicates in MergeVarDecl
5745   ProcessDeclAttributes(S, NewTD, D);
5746 
5747   CheckTypedefForVariablyModifiedType(S, NewTD);
5748 
5749   bool Redeclaration = D.isRedeclaration();
5750   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5751   D.setRedeclaration(Redeclaration);
5752   return ND;
5753 }
5754 
5755 void
5756 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5757   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5758   // then it shall have block scope.
5759   // Note that variably modified types must be fixed before merging the decl so
5760   // that redeclarations will match.
5761   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5762   QualType T = TInfo->getType();
5763   if (T->isVariablyModifiedType()) {
5764     setFunctionHasBranchProtectedScope();
5765 
5766     if (S->getFnParent() == nullptr) {
5767       bool SizeIsNegative;
5768       llvm::APSInt Oversized;
5769       TypeSourceInfo *FixedTInfo =
5770         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5771                                                       SizeIsNegative,
5772                                                       Oversized);
5773       if (FixedTInfo) {
5774         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5775         NewTD->setTypeSourceInfo(FixedTInfo);
5776       } else {
5777         if (SizeIsNegative)
5778           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5779         else if (T->isVariableArrayType())
5780           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5781         else if (Oversized.getBoolValue())
5782           Diag(NewTD->getLocation(), diag::err_array_too_large)
5783             << Oversized.toString(10);
5784         else
5785           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5786         NewTD->setInvalidDecl();
5787       }
5788     }
5789   }
5790 }
5791 
5792 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5793 /// declares a typedef-name, either using the 'typedef' type specifier or via
5794 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5795 NamedDecl*
5796 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5797                            LookupResult &Previous, bool &Redeclaration) {
5798 
5799   // Find the shadowed declaration before filtering for scope.
5800   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5801 
5802   // Merge the decl with the existing one if appropriate. If the decl is
5803   // in an outer scope, it isn't the same thing.
5804   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5805                        /*AllowInlineNamespace*/false);
5806   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5807   if (!Previous.empty()) {
5808     Redeclaration = true;
5809     MergeTypedefNameDecl(S, NewTD, Previous);
5810   }
5811 
5812   if (ShadowedDecl && !Redeclaration)
5813     CheckShadow(NewTD, ShadowedDecl, Previous);
5814 
5815   // If this is the C FILE type, notify the AST context.
5816   if (IdentifierInfo *II = NewTD->getIdentifier())
5817     if (!NewTD->isInvalidDecl() &&
5818         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5819       if (II->isStr("FILE"))
5820         Context.setFILEDecl(NewTD);
5821       else if (II->isStr("jmp_buf"))
5822         Context.setjmp_bufDecl(NewTD);
5823       else if (II->isStr("sigjmp_buf"))
5824         Context.setsigjmp_bufDecl(NewTD);
5825       else if (II->isStr("ucontext_t"))
5826         Context.setucontext_tDecl(NewTD);
5827     }
5828 
5829   return NewTD;
5830 }
5831 
5832 /// \brief Determines whether the given declaration is an out-of-scope
5833 /// previous declaration.
5834 ///
5835 /// This routine should be invoked when name lookup has found a
5836 /// previous declaration (PrevDecl) that is not in the scope where a
5837 /// new declaration by the same name is being introduced. If the new
5838 /// declaration occurs in a local scope, previous declarations with
5839 /// linkage may still be considered previous declarations (C99
5840 /// 6.2.2p4-5, C++ [basic.link]p6).
5841 ///
5842 /// \param PrevDecl the previous declaration found by name
5843 /// lookup
5844 ///
5845 /// \param DC the context in which the new declaration is being
5846 /// declared.
5847 ///
5848 /// \returns true if PrevDecl is an out-of-scope previous declaration
5849 /// for a new delcaration with the same name.
5850 static bool
5851 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5852                                 ASTContext &Context) {
5853   if (!PrevDecl)
5854     return false;
5855 
5856   if (!PrevDecl->hasLinkage())
5857     return false;
5858 
5859   if (Context.getLangOpts().CPlusPlus) {
5860     // C++ [basic.link]p6:
5861     //   If there is a visible declaration of an entity with linkage
5862     //   having the same name and type, ignoring entities declared
5863     //   outside the innermost enclosing namespace scope, the block
5864     //   scope declaration declares that same entity and receives the
5865     //   linkage of the previous declaration.
5866     DeclContext *OuterContext = DC->getRedeclContext();
5867     if (!OuterContext->isFunctionOrMethod())
5868       // This rule only applies to block-scope declarations.
5869       return false;
5870 
5871     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5872     if (PrevOuterContext->isRecord())
5873       // We found a member function: ignore it.
5874       return false;
5875 
5876     // Find the innermost enclosing namespace for the new and
5877     // previous declarations.
5878     OuterContext = OuterContext->getEnclosingNamespaceContext();
5879     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5880 
5881     // The previous declaration is in a different namespace, so it
5882     // isn't the same function.
5883     if (!OuterContext->Equals(PrevOuterContext))
5884       return false;
5885   }
5886 
5887   return true;
5888 }
5889 
5890 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5891   CXXScopeSpec &SS = D.getCXXScopeSpec();
5892   if (!SS.isSet()) return;
5893   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5894 }
5895 
5896 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5897   QualType type = decl->getType();
5898   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5899   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5900     // Various kinds of declaration aren't allowed to be __autoreleasing.
5901     unsigned kind = -1U;
5902     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5903       if (var->hasAttr<BlocksAttr>())
5904         kind = 0; // __block
5905       else if (!var->hasLocalStorage())
5906         kind = 1; // global
5907     } else if (isa<ObjCIvarDecl>(decl)) {
5908       kind = 3; // ivar
5909     } else if (isa<FieldDecl>(decl)) {
5910       kind = 2; // field
5911     }
5912 
5913     if (kind != -1U) {
5914       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5915         << kind;
5916     }
5917   } else if (lifetime == Qualifiers::OCL_None) {
5918     // Try to infer lifetime.
5919     if (!type->isObjCLifetimeType())
5920       return false;
5921 
5922     lifetime = type->getObjCARCImplicitLifetime();
5923     type = Context.getLifetimeQualifiedType(type, lifetime);
5924     decl->setType(type);
5925   }
5926 
5927   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5928     // Thread-local variables cannot have lifetime.
5929     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5930         var->getTLSKind()) {
5931       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5932         << var->getType();
5933       return true;
5934     }
5935   }
5936 
5937   return false;
5938 }
5939 
5940 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5941   // Ensure that an auto decl is deduced otherwise the checks below might cache
5942   // the wrong linkage.
5943   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5944 
5945   // 'weak' only applies to declarations with external linkage.
5946   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5947     if (!ND.isExternallyVisible()) {
5948       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5949       ND.dropAttr<WeakAttr>();
5950     }
5951   }
5952   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5953     if (ND.isExternallyVisible()) {
5954       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5955       ND.dropAttr<WeakRefAttr>();
5956       ND.dropAttr<AliasAttr>();
5957     }
5958   }
5959 
5960   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5961     if (VD->hasInit()) {
5962       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5963         assert(VD->isThisDeclarationADefinition() &&
5964                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5965         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5966         VD->dropAttr<AliasAttr>();
5967       }
5968     }
5969   }
5970 
5971   // 'selectany' only applies to externally visible variable declarations.
5972   // It does not apply to functions.
5973   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5974     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5975       S.Diag(Attr->getLocation(),
5976              diag::err_attribute_selectany_non_extern_data);
5977       ND.dropAttr<SelectAnyAttr>();
5978     }
5979   }
5980 
5981   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5982     // dll attributes require external linkage. Static locals may have external
5983     // linkage but still cannot be explicitly imported or exported.
5984     auto *VD = dyn_cast<VarDecl>(&ND);
5985     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5986       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5987         << &ND << Attr;
5988       ND.setInvalidDecl();
5989     }
5990   }
5991 
5992   // Virtual functions cannot be marked as 'notail'.
5993   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5994     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5995       if (MD->isVirtual()) {
5996         S.Diag(ND.getLocation(),
5997                diag::err_invalid_attribute_on_virtual_function)
5998             << Attr;
5999         ND.dropAttr<NotTailCalledAttr>();
6000       }
6001 }
6002 
6003 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6004                                            NamedDecl *NewDecl,
6005                                            bool IsSpecialization,
6006                                            bool IsDefinition) {
6007   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6008     return;
6009 
6010   bool IsTemplate = false;
6011   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6012     OldDecl = OldTD->getTemplatedDecl();
6013     IsTemplate = true;
6014     if (!IsSpecialization)
6015       IsDefinition = false;
6016   }
6017   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6018     NewDecl = NewTD->getTemplatedDecl();
6019     IsTemplate = true;
6020   }
6021 
6022   if (!OldDecl || !NewDecl)
6023     return;
6024 
6025   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6026   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6027   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6028   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6029 
6030   // dllimport and dllexport are inheritable attributes so we have to exclude
6031   // inherited attribute instances.
6032   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6033                     (NewExportAttr && !NewExportAttr->isInherited());
6034 
6035   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6036   // the only exception being explicit specializations.
6037   // Implicitly generated declarations are also excluded for now because there
6038   // is no other way to switch these to use dllimport or dllexport.
6039   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6040 
6041   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6042     // Allow with a warning for free functions and global variables.
6043     bool JustWarn = false;
6044     if (!OldDecl->isCXXClassMember()) {
6045       auto *VD = dyn_cast<VarDecl>(OldDecl);
6046       if (VD && !VD->getDescribedVarTemplate())
6047         JustWarn = true;
6048       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6049       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6050         JustWarn = true;
6051     }
6052 
6053     // We cannot change a declaration that's been used because IR has already
6054     // been emitted. Dllimported functions will still work though (modulo
6055     // address equality) as they can use the thunk.
6056     if (OldDecl->isUsed())
6057       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6058         JustWarn = false;
6059 
6060     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6061                                : diag::err_attribute_dll_redeclaration;
6062     S.Diag(NewDecl->getLocation(), DiagID)
6063         << NewDecl
6064         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6065     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6066     if (!JustWarn) {
6067       NewDecl->setInvalidDecl();
6068       return;
6069     }
6070   }
6071 
6072   // A redeclaration is not allowed to drop a dllimport attribute, the only
6073   // exceptions being inline function definitions (except for function
6074   // templates), local extern declarations, qualified friend declarations or
6075   // special MSVC extension: in the last case, the declaration is treated as if
6076   // it were marked dllexport.
6077   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6078   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6079   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6080     // Ignore static data because out-of-line definitions are diagnosed
6081     // separately.
6082     IsStaticDataMember = VD->isStaticDataMember();
6083     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6084                    VarDecl::DeclarationOnly;
6085   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6086     IsInline = FD->isInlined();
6087     IsQualifiedFriend = FD->getQualifier() &&
6088                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6089   }
6090 
6091   if (OldImportAttr && !HasNewAttr &&
6092       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6093       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6094     if (IsMicrosoft && IsDefinition) {
6095       S.Diag(NewDecl->getLocation(),
6096              diag::warn_redeclaration_without_import_attribute)
6097           << NewDecl;
6098       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6099       NewDecl->dropAttr<DLLImportAttr>();
6100       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6101           NewImportAttr->getRange(), S.Context,
6102           NewImportAttr->getSpellingListIndex()));
6103     } else {
6104       S.Diag(NewDecl->getLocation(),
6105              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6106           << NewDecl << OldImportAttr;
6107       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6108       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6109       OldDecl->dropAttr<DLLImportAttr>();
6110       NewDecl->dropAttr<DLLImportAttr>();
6111     }
6112   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6113     // In MinGW, seeing a function declared inline drops the dllimport
6114     // attribute.
6115     OldDecl->dropAttr<DLLImportAttr>();
6116     NewDecl->dropAttr<DLLImportAttr>();
6117     S.Diag(NewDecl->getLocation(),
6118            diag::warn_dllimport_dropped_from_inline_function)
6119         << NewDecl << OldImportAttr;
6120   }
6121 
6122   // A specialization of a class template member function is processed here
6123   // since it's a redeclaration. If the parent class is dllexport, the
6124   // specialization inherits that attribute. This doesn't happen automatically
6125   // since the parent class isn't instantiated until later.
6126   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6127     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6128         !NewImportAttr && !NewExportAttr) {
6129       if (const DLLExportAttr *ParentExportAttr =
6130               MD->getParent()->getAttr<DLLExportAttr>()) {
6131         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6132         NewAttr->setInherited(true);
6133         NewDecl->addAttr(NewAttr);
6134       }
6135     }
6136   }
6137 }
6138 
6139 /// Given that we are within the definition of the given function,
6140 /// will that definition behave like C99's 'inline', where the
6141 /// definition is discarded except for optimization purposes?
6142 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6143   // Try to avoid calling GetGVALinkageForFunction.
6144 
6145   // All cases of this require the 'inline' keyword.
6146   if (!FD->isInlined()) return false;
6147 
6148   // This is only possible in C++ with the gnu_inline attribute.
6149   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6150     return false;
6151 
6152   // Okay, go ahead and call the relatively-more-expensive function.
6153   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6154 }
6155 
6156 /// Determine whether a variable is extern "C" prior to attaching
6157 /// an initializer. We can't just call isExternC() here, because that
6158 /// will also compute and cache whether the declaration is externally
6159 /// visible, which might change when we attach the initializer.
6160 ///
6161 /// This can only be used if the declaration is known to not be a
6162 /// redeclaration of an internal linkage declaration.
6163 ///
6164 /// For instance:
6165 ///
6166 ///   auto x = []{};
6167 ///
6168 /// Attaching the initializer here makes this declaration not externally
6169 /// visible, because its type has internal linkage.
6170 ///
6171 /// FIXME: This is a hack.
6172 template<typename T>
6173 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6174   if (S.getLangOpts().CPlusPlus) {
6175     // In C++, the overloadable attribute negates the effects of extern "C".
6176     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6177       return false;
6178 
6179     // So do CUDA's host/device attributes.
6180     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6181                                  D->template hasAttr<CUDAHostAttr>()))
6182       return false;
6183   }
6184   return D->isExternC();
6185 }
6186 
6187 static bool shouldConsiderLinkage(const VarDecl *VD) {
6188   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6189   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6190     return VD->hasExternalStorage();
6191   if (DC->isFileContext())
6192     return true;
6193   if (DC->isRecord())
6194     return false;
6195   llvm_unreachable("Unexpected context");
6196 }
6197 
6198 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6199   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6200   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6201       isa<OMPDeclareReductionDecl>(DC))
6202     return true;
6203   if (DC->isRecord())
6204     return false;
6205   llvm_unreachable("Unexpected context");
6206 }
6207 
6208 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6209                           AttributeList::Kind Kind) {
6210   for (const AttributeList *L = AttrList; L; L = L->getNext())
6211     if (L->getKind() == Kind)
6212       return true;
6213   return false;
6214 }
6215 
6216 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6217                           AttributeList::Kind Kind) {
6218   // Check decl attributes on the DeclSpec.
6219   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6220     return true;
6221 
6222   // Walk the declarator structure, checking decl attributes that were in a type
6223   // position to the decl itself.
6224   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6225     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6226       return true;
6227   }
6228 
6229   // Finally, check attributes on the decl itself.
6230   return hasParsedAttr(S, PD.getAttributes(), Kind);
6231 }
6232 
6233 /// Adjust the \c DeclContext for a function or variable that might be a
6234 /// function-local external declaration.
6235 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6236   if (!DC->isFunctionOrMethod())
6237     return false;
6238 
6239   // If this is a local extern function or variable declared within a function
6240   // template, don't add it into the enclosing namespace scope until it is
6241   // instantiated; it might have a dependent type right now.
6242   if (DC->isDependentContext())
6243     return true;
6244 
6245   // C++11 [basic.link]p7:
6246   //   When a block scope declaration of an entity with linkage is not found to
6247   //   refer to some other declaration, then that entity is a member of the
6248   //   innermost enclosing namespace.
6249   //
6250   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6251   // semantically-enclosing namespace, not a lexically-enclosing one.
6252   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6253     DC = DC->getParent();
6254   return true;
6255 }
6256 
6257 /// \brief Returns true if given declaration has external C language linkage.
6258 static bool isDeclExternC(const Decl *D) {
6259   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6260     return FD->isExternC();
6261   if (const auto *VD = dyn_cast<VarDecl>(D))
6262     return VD->isExternC();
6263 
6264   llvm_unreachable("Unknown type of decl!");
6265 }
6266 
6267 NamedDecl *Sema::ActOnVariableDeclarator(
6268     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6269     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6270     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6271   QualType R = TInfo->getType();
6272   DeclarationName Name = GetNameForDeclarator(D).getName();
6273 
6274   IdentifierInfo *II = Name.getAsIdentifierInfo();
6275 
6276   if (D.isDecompositionDeclarator()) {
6277     // Take the name of the first declarator as our name for diagnostic
6278     // purposes.
6279     auto &Decomp = D.getDecompositionDeclarator();
6280     if (!Decomp.bindings().empty()) {
6281       II = Decomp.bindings()[0].Name;
6282       Name = II;
6283     }
6284   } else if (!II) {
6285     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6286     return nullptr;
6287   }
6288 
6289   if (getLangOpts().OpenCL) {
6290     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6291     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6292     // argument.
6293     if (R->isImageType() || R->isPipeType()) {
6294       Diag(D.getIdentifierLoc(),
6295            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6296           << R;
6297       D.setInvalidType();
6298       return nullptr;
6299     }
6300 
6301     // OpenCL v1.2 s6.9.r:
6302     // The event type cannot be used to declare a program scope variable.
6303     // OpenCL v2.0 s6.9.q:
6304     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6305     if (NULL == S->getParent()) {
6306       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6307         Diag(D.getIdentifierLoc(),
6308              diag::err_invalid_type_for_program_scope_var) << R;
6309         D.setInvalidType();
6310         return nullptr;
6311       }
6312     }
6313 
6314     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6315     QualType NR = R;
6316     while (NR->isPointerType()) {
6317       if (NR->isFunctionPointerType()) {
6318         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6319         D.setInvalidType();
6320         break;
6321       }
6322       NR = NR->getPointeeType();
6323     }
6324 
6325     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6326       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6327       // half array type (unless the cl_khr_fp16 extension is enabled).
6328       if (Context.getBaseElementType(R)->isHalfType()) {
6329         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6330         D.setInvalidType();
6331       }
6332     }
6333 
6334     if (R->isSamplerT()) {
6335       // OpenCL v1.2 s6.9.b p4:
6336       // The sampler type cannot be used with the __local and __global address
6337       // space qualifiers.
6338       if (R.getAddressSpace() == LangAS::opencl_local ||
6339           R.getAddressSpace() == LangAS::opencl_global) {
6340         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6341       }
6342 
6343       // OpenCL v1.2 s6.12.14.1:
6344       // A global sampler must be declared with either the constant address
6345       // space qualifier or with the const qualifier.
6346       if (DC->isTranslationUnit() &&
6347           !(R.getAddressSpace() == LangAS::opencl_constant ||
6348           R.isConstQualified())) {
6349         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6350         D.setInvalidType();
6351       }
6352     }
6353 
6354     // OpenCL v1.2 s6.9.r:
6355     // The event type cannot be used with the __local, __constant and __global
6356     // address space qualifiers.
6357     if (R->isEventT()) {
6358       if (R.getAddressSpace() != LangAS::opencl_private) {
6359         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6360         D.setInvalidType();
6361       }
6362     }
6363   }
6364 
6365   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6366   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6367 
6368   // dllimport globals without explicit storage class are treated as extern. We
6369   // have to change the storage class this early to get the right DeclContext.
6370   if (SC == SC_None && !DC->isRecord() &&
6371       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6372       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6373     SC = SC_Extern;
6374 
6375   DeclContext *OriginalDC = DC;
6376   bool IsLocalExternDecl = SC == SC_Extern &&
6377                            adjustContextForLocalExternDecl(DC);
6378 
6379   if (SCSpec == DeclSpec::SCS_mutable) {
6380     // mutable can only appear on non-static class members, so it's always
6381     // an error here
6382     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6383     D.setInvalidType();
6384     SC = SC_None;
6385   }
6386 
6387   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6388       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6389                               D.getDeclSpec().getStorageClassSpecLoc())) {
6390     // In C++11, the 'register' storage class specifier is deprecated.
6391     // Suppress the warning in system macros, it's used in macros in some
6392     // popular C system headers, such as in glibc's htonl() macro.
6393     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6394          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6395                                    : diag::warn_deprecated_register)
6396       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6397   }
6398 
6399   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6400 
6401   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6402     // C99 6.9p2: The storage-class specifiers auto and register shall not
6403     // appear in the declaration specifiers in an external declaration.
6404     // Global Register+Asm is a GNU extension we support.
6405     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6406       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6407       D.setInvalidType();
6408     }
6409   }
6410 
6411   bool IsMemberSpecialization = false;
6412   bool IsVariableTemplateSpecialization = false;
6413   bool IsPartialSpecialization = false;
6414   bool IsVariableTemplate = false;
6415   VarDecl *NewVD = nullptr;
6416   VarTemplateDecl *NewTemplate = nullptr;
6417   TemplateParameterList *TemplateParams = nullptr;
6418   if (!getLangOpts().CPlusPlus) {
6419     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6420                             D.getIdentifierLoc(), II,
6421                             R, TInfo, SC);
6422 
6423     if (R->getContainedDeducedType())
6424       ParsingInitForAutoVars.insert(NewVD);
6425 
6426     if (D.isInvalidType())
6427       NewVD->setInvalidDecl();
6428   } else {
6429     bool Invalid = false;
6430 
6431     if (DC->isRecord() && !CurContext->isRecord()) {
6432       // This is an out-of-line definition of a static data member.
6433       switch (SC) {
6434       case SC_None:
6435         break;
6436       case SC_Static:
6437         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6438              diag::err_static_out_of_line)
6439           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6440         break;
6441       case SC_Auto:
6442       case SC_Register:
6443       case SC_Extern:
6444         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6445         // to names of variables declared in a block or to function parameters.
6446         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6447         // of class members
6448 
6449         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6450              diag::err_storage_class_for_static_member)
6451           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6452         break;
6453       case SC_PrivateExtern:
6454         llvm_unreachable("C storage class in c++!");
6455       }
6456     }
6457 
6458     if (SC == SC_Static && CurContext->isRecord()) {
6459       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6460         if (RD->isLocalClass())
6461           Diag(D.getIdentifierLoc(),
6462                diag::err_static_data_member_not_allowed_in_local_class)
6463             << Name << RD->getDeclName();
6464 
6465         // C++98 [class.union]p1: If a union contains a static data member,
6466         // the program is ill-formed. C++11 drops this restriction.
6467         if (RD->isUnion())
6468           Diag(D.getIdentifierLoc(),
6469                getLangOpts().CPlusPlus11
6470                  ? diag::warn_cxx98_compat_static_data_member_in_union
6471                  : diag::ext_static_data_member_in_union) << Name;
6472         // We conservatively disallow static data members in anonymous structs.
6473         else if (!RD->getDeclName())
6474           Diag(D.getIdentifierLoc(),
6475                diag::err_static_data_member_not_allowed_in_anon_struct)
6476             << Name << RD->isUnion();
6477       }
6478     }
6479 
6480     // Match up the template parameter lists with the scope specifier, then
6481     // determine whether we have a template or a template specialization.
6482     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6483         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6484         D.getCXXScopeSpec(),
6485         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6486             ? D.getName().TemplateId
6487             : nullptr,
6488         TemplateParamLists,
6489         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6490 
6491     if (TemplateParams) {
6492       if (!TemplateParams->size() &&
6493           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6494         // There is an extraneous 'template<>' for this variable. Complain
6495         // about it, but allow the declaration of the variable.
6496         Diag(TemplateParams->getTemplateLoc(),
6497              diag::err_template_variable_noparams)
6498           << II
6499           << SourceRange(TemplateParams->getTemplateLoc(),
6500                          TemplateParams->getRAngleLoc());
6501         TemplateParams = nullptr;
6502       } else {
6503         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6504           // This is an explicit specialization or a partial specialization.
6505           // FIXME: Check that we can declare a specialization here.
6506           IsVariableTemplateSpecialization = true;
6507           IsPartialSpecialization = TemplateParams->size() > 0;
6508         } else { // if (TemplateParams->size() > 0)
6509           // This is a template declaration.
6510           IsVariableTemplate = true;
6511 
6512           // Check that we can declare a template here.
6513           if (CheckTemplateDeclScope(S, TemplateParams))
6514             return nullptr;
6515 
6516           // Only C++1y supports variable templates (N3651).
6517           Diag(D.getIdentifierLoc(),
6518                getLangOpts().CPlusPlus14
6519                    ? diag::warn_cxx11_compat_variable_template
6520                    : diag::ext_variable_template);
6521         }
6522       }
6523     } else {
6524       assert((Invalid ||
6525               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6526              "should have a 'template<>' for this decl");
6527     }
6528 
6529     if (IsVariableTemplateSpecialization) {
6530       SourceLocation TemplateKWLoc =
6531           TemplateParamLists.size() > 0
6532               ? TemplateParamLists[0]->getTemplateLoc()
6533               : SourceLocation();
6534       DeclResult Res = ActOnVarTemplateSpecialization(
6535           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6536           IsPartialSpecialization);
6537       if (Res.isInvalid())
6538         return nullptr;
6539       NewVD = cast<VarDecl>(Res.get());
6540       AddToScope = false;
6541     } else if (D.isDecompositionDeclarator()) {
6542       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6543                                         D.getIdentifierLoc(), R, TInfo, SC,
6544                                         Bindings);
6545     } else
6546       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6547                               D.getIdentifierLoc(), II, R, TInfo, SC);
6548 
6549     // If this is supposed to be a variable template, create it as such.
6550     if (IsVariableTemplate) {
6551       NewTemplate =
6552           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6553                                   TemplateParams, NewVD);
6554       NewVD->setDescribedVarTemplate(NewTemplate);
6555     }
6556 
6557     // If this decl has an auto type in need of deduction, make a note of the
6558     // Decl so we can diagnose uses of it in its own initializer.
6559     if (R->getContainedDeducedType())
6560       ParsingInitForAutoVars.insert(NewVD);
6561 
6562     if (D.isInvalidType() || Invalid) {
6563       NewVD->setInvalidDecl();
6564       if (NewTemplate)
6565         NewTemplate->setInvalidDecl();
6566     }
6567 
6568     SetNestedNameSpecifier(NewVD, D);
6569 
6570     // If we have any template parameter lists that don't directly belong to
6571     // the variable (matching the scope specifier), store them.
6572     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6573     if (TemplateParamLists.size() > VDTemplateParamLists)
6574       NewVD->setTemplateParameterListsInfo(
6575           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6576 
6577     if (D.getDeclSpec().isConstexprSpecified()) {
6578       NewVD->setConstexpr(true);
6579       // C++1z [dcl.spec.constexpr]p1:
6580       //   A static data member declared with the constexpr specifier is
6581       //   implicitly an inline variable.
6582       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6583         NewVD->setImplicitlyInline();
6584     }
6585   }
6586 
6587   if (D.getDeclSpec().isInlineSpecified()) {
6588     if (!getLangOpts().CPlusPlus) {
6589       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6590           << 0;
6591     } else if (CurContext->isFunctionOrMethod()) {
6592       // 'inline' is not allowed on block scope variable declaration.
6593       Diag(D.getDeclSpec().getInlineSpecLoc(),
6594            diag::err_inline_declaration_block_scope) << Name
6595         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6596     } else {
6597       Diag(D.getDeclSpec().getInlineSpecLoc(),
6598            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6599                                      : diag::ext_inline_variable);
6600       NewVD->setInlineSpecified();
6601     }
6602   }
6603 
6604   // Set the lexical context. If the declarator has a C++ scope specifier, the
6605   // lexical context will be different from the semantic context.
6606   NewVD->setLexicalDeclContext(CurContext);
6607   if (NewTemplate)
6608     NewTemplate->setLexicalDeclContext(CurContext);
6609 
6610   if (IsLocalExternDecl) {
6611     if (D.isDecompositionDeclarator())
6612       for (auto *B : Bindings)
6613         B->setLocalExternDecl();
6614     else
6615       NewVD->setLocalExternDecl();
6616   }
6617 
6618   bool EmitTLSUnsupportedError = false;
6619   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6620     // C++11 [dcl.stc]p4:
6621     //   When thread_local is applied to a variable of block scope the
6622     //   storage-class-specifier static is implied if it does not appear
6623     //   explicitly.
6624     // Core issue: 'static' is not implied if the variable is declared
6625     //   'extern'.
6626     if (NewVD->hasLocalStorage() &&
6627         (SCSpec != DeclSpec::SCS_unspecified ||
6628          TSCS != DeclSpec::TSCS_thread_local ||
6629          !DC->isFunctionOrMethod()))
6630       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6631            diag::err_thread_non_global)
6632         << DeclSpec::getSpecifierName(TSCS);
6633     else if (!Context.getTargetInfo().isTLSSupported()) {
6634       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6635         // Postpone error emission until we've collected attributes required to
6636         // figure out whether it's a host or device variable and whether the
6637         // error should be ignored.
6638         EmitTLSUnsupportedError = true;
6639         // We still need to mark the variable as TLS so it shows up in AST with
6640         // proper storage class for other tools to use even if we're not going
6641         // to emit any code for it.
6642         NewVD->setTSCSpec(TSCS);
6643       } else
6644         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6645              diag::err_thread_unsupported);
6646     } else
6647       NewVD->setTSCSpec(TSCS);
6648   }
6649 
6650   // C99 6.7.4p3
6651   //   An inline definition of a function with external linkage shall
6652   //   not contain a definition of a modifiable object with static or
6653   //   thread storage duration...
6654   // We only apply this when the function is required to be defined
6655   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6656   // that a local variable with thread storage duration still has to
6657   // be marked 'static'.  Also note that it's possible to get these
6658   // semantics in C++ using __attribute__((gnu_inline)).
6659   if (SC == SC_Static && S->getFnParent() != nullptr &&
6660       !NewVD->getType().isConstQualified()) {
6661     FunctionDecl *CurFD = getCurFunctionDecl();
6662     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6663       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6664            diag::warn_static_local_in_extern_inline);
6665       MaybeSuggestAddingStaticToDecl(CurFD);
6666     }
6667   }
6668 
6669   if (D.getDeclSpec().isModulePrivateSpecified()) {
6670     if (IsVariableTemplateSpecialization)
6671       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6672           << (IsPartialSpecialization ? 1 : 0)
6673           << FixItHint::CreateRemoval(
6674                  D.getDeclSpec().getModulePrivateSpecLoc());
6675     else if (IsMemberSpecialization)
6676       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6677         << 2
6678         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6679     else if (NewVD->hasLocalStorage())
6680       Diag(NewVD->getLocation(), diag::err_module_private_local)
6681         << 0 << NewVD->getDeclName()
6682         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6683         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6684     else {
6685       NewVD->setModulePrivate();
6686       if (NewTemplate)
6687         NewTemplate->setModulePrivate();
6688       for (auto *B : Bindings)
6689         B->setModulePrivate();
6690     }
6691   }
6692 
6693   // Handle attributes prior to checking for duplicates in MergeVarDecl
6694   ProcessDeclAttributes(S, NewVD, D);
6695 
6696   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6697     if (EmitTLSUnsupportedError &&
6698         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6699          (getLangOpts().OpenMPIsDevice &&
6700           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6701       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6702            diag::err_thread_unsupported);
6703     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6704     // storage [duration]."
6705     if (SC == SC_None && S->getFnParent() != nullptr &&
6706         (NewVD->hasAttr<CUDASharedAttr>() ||
6707          NewVD->hasAttr<CUDAConstantAttr>())) {
6708       NewVD->setStorageClass(SC_Static);
6709     }
6710   }
6711 
6712   // Ensure that dllimport globals without explicit storage class are treated as
6713   // extern. The storage class is set above using parsed attributes. Now we can
6714   // check the VarDecl itself.
6715   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6716          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6717          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6718 
6719   // In auto-retain/release, infer strong retension for variables of
6720   // retainable type.
6721   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6722     NewVD->setInvalidDecl();
6723 
6724   // Handle GNU asm-label extension (encoded as an attribute).
6725   if (Expr *E = (Expr*)D.getAsmLabel()) {
6726     // The parser guarantees this is a string.
6727     StringLiteral *SE = cast<StringLiteral>(E);
6728     StringRef Label = SE->getString();
6729     if (S->getFnParent() != nullptr) {
6730       switch (SC) {
6731       case SC_None:
6732       case SC_Auto:
6733         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6734         break;
6735       case SC_Register:
6736         // Local Named register
6737         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6738             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6739           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6740         break;
6741       case SC_Static:
6742       case SC_Extern:
6743       case SC_PrivateExtern:
6744         break;
6745       }
6746     } else if (SC == SC_Register) {
6747       // Global Named register
6748       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6749         const auto &TI = Context.getTargetInfo();
6750         bool HasSizeMismatch;
6751 
6752         if (!TI.isValidGCCRegisterName(Label))
6753           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6754         else if (!TI.validateGlobalRegisterVariable(Label,
6755                                                     Context.getTypeSize(R),
6756                                                     HasSizeMismatch))
6757           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6758         else if (HasSizeMismatch)
6759           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6760       }
6761 
6762       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6763         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6764         NewVD->setInvalidDecl(true);
6765       }
6766     }
6767 
6768     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6769                                                 Context, Label, 0));
6770   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6771     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6772       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6773     if (I != ExtnameUndeclaredIdentifiers.end()) {
6774       if (isDeclExternC(NewVD)) {
6775         NewVD->addAttr(I->second);
6776         ExtnameUndeclaredIdentifiers.erase(I);
6777       } else
6778         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6779             << /*Variable*/1 << NewVD;
6780     }
6781   }
6782 
6783   // Find the shadowed declaration before filtering for scope.
6784   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6785                                 ? getShadowedDeclaration(NewVD, Previous)
6786                                 : nullptr;
6787 
6788   // Don't consider existing declarations that are in a different
6789   // scope and are out-of-semantic-context declarations (if the new
6790   // declaration has linkage).
6791   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6792                        D.getCXXScopeSpec().isNotEmpty() ||
6793                        IsMemberSpecialization ||
6794                        IsVariableTemplateSpecialization);
6795 
6796   // Check whether the previous declaration is in the same block scope. This
6797   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6798   if (getLangOpts().CPlusPlus &&
6799       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6800     NewVD->setPreviousDeclInSameBlockScope(
6801         Previous.isSingleResult() && !Previous.isShadowed() &&
6802         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6803 
6804   if (!getLangOpts().CPlusPlus) {
6805     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6806   } else {
6807     // If this is an explicit specialization of a static data member, check it.
6808     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6809         CheckMemberSpecialization(NewVD, Previous))
6810       NewVD->setInvalidDecl();
6811 
6812     // Merge the decl with the existing one if appropriate.
6813     if (!Previous.empty()) {
6814       if (Previous.isSingleResult() &&
6815           isa<FieldDecl>(Previous.getFoundDecl()) &&
6816           D.getCXXScopeSpec().isSet()) {
6817         // The user tried to define a non-static data member
6818         // out-of-line (C++ [dcl.meaning]p1).
6819         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6820           << D.getCXXScopeSpec().getRange();
6821         Previous.clear();
6822         NewVD->setInvalidDecl();
6823       }
6824     } else if (D.getCXXScopeSpec().isSet()) {
6825       // No previous declaration in the qualifying scope.
6826       Diag(D.getIdentifierLoc(), diag::err_no_member)
6827         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6828         << D.getCXXScopeSpec().getRange();
6829       NewVD->setInvalidDecl();
6830     }
6831 
6832     if (!IsVariableTemplateSpecialization)
6833       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6834 
6835     if (NewTemplate) {
6836       VarTemplateDecl *PrevVarTemplate =
6837           NewVD->getPreviousDecl()
6838               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6839               : nullptr;
6840 
6841       // Check the template parameter list of this declaration, possibly
6842       // merging in the template parameter list from the previous variable
6843       // template declaration.
6844       if (CheckTemplateParameterList(
6845               TemplateParams,
6846               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6847                               : nullptr,
6848               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6849                DC->isDependentContext())
6850                   ? TPC_ClassTemplateMember
6851                   : TPC_VarTemplate))
6852         NewVD->setInvalidDecl();
6853 
6854       // If we are providing an explicit specialization of a static variable
6855       // template, make a note of that.
6856       if (PrevVarTemplate &&
6857           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6858         PrevVarTemplate->setMemberSpecialization();
6859     }
6860   }
6861 
6862   // Diagnose shadowed variables iff this isn't a redeclaration.
6863   if (ShadowedDecl && !D.isRedeclaration())
6864     CheckShadow(NewVD, ShadowedDecl, Previous);
6865 
6866   ProcessPragmaWeak(S, NewVD);
6867 
6868   // If this is the first declaration of an extern C variable, update
6869   // the map of such variables.
6870   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6871       isIncompleteDeclExternC(*this, NewVD))
6872     RegisterLocallyScopedExternCDecl(NewVD, S);
6873 
6874   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6875     Decl *ManglingContextDecl;
6876     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6877             NewVD->getDeclContext(), ManglingContextDecl)) {
6878       Context.setManglingNumber(
6879           NewVD, MCtx->getManglingNumber(
6880                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6881       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6882     }
6883   }
6884 
6885   // Special handling of variable named 'main'.
6886   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6887       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6888       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6889 
6890     // C++ [basic.start.main]p3
6891     // A program that declares a variable main at global scope is ill-formed.
6892     if (getLangOpts().CPlusPlus)
6893       Diag(D.getLocStart(), diag::err_main_global_variable);
6894 
6895     // In C, and external-linkage variable named main results in undefined
6896     // behavior.
6897     else if (NewVD->hasExternalFormalLinkage())
6898       Diag(D.getLocStart(), diag::warn_main_redefined);
6899   }
6900 
6901   if (D.isRedeclaration() && !Previous.empty()) {
6902     NamedDecl *Prev = Previous.getRepresentativeDecl();
6903     checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6904                                    D.isFunctionDefinition());
6905   }
6906 
6907   if (NewTemplate) {
6908     if (NewVD->isInvalidDecl())
6909       NewTemplate->setInvalidDecl();
6910     ActOnDocumentableDecl(NewTemplate);
6911     return NewTemplate;
6912   }
6913 
6914   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6915     CompleteMemberSpecialization(NewVD, Previous);
6916 
6917   return NewVD;
6918 }
6919 
6920 /// Enum describing the %select options in diag::warn_decl_shadow.
6921 enum ShadowedDeclKind {
6922   SDK_Local,
6923   SDK_Global,
6924   SDK_StaticMember,
6925   SDK_Field,
6926   SDK_Typedef,
6927   SDK_Using
6928 };
6929 
6930 /// Determine what kind of declaration we're shadowing.
6931 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6932                                                 const DeclContext *OldDC) {
6933   if (isa<TypeAliasDecl>(ShadowedDecl))
6934     return SDK_Using;
6935   else if (isa<TypedefDecl>(ShadowedDecl))
6936     return SDK_Typedef;
6937   else if (isa<RecordDecl>(OldDC))
6938     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6939 
6940   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6941 }
6942 
6943 /// Return the location of the capture if the given lambda captures the given
6944 /// variable \p VD, or an invalid source location otherwise.
6945 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6946                                          const VarDecl *VD) {
6947   for (const Capture &Capture : LSI->Captures) {
6948     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6949       return Capture.getLocation();
6950   }
6951   return SourceLocation();
6952 }
6953 
6954 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6955                                      const LookupResult &R) {
6956   // Only diagnose if we're shadowing an unambiguous field or variable.
6957   if (R.getResultKind() != LookupResult::Found)
6958     return false;
6959 
6960   // Return false if warning is ignored.
6961   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6962 }
6963 
6964 /// \brief Return the declaration shadowed by the given variable \p D, or null
6965 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6966 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6967                                         const LookupResult &R) {
6968   if (!shouldWarnIfShadowedDecl(Diags, R))
6969     return nullptr;
6970 
6971   // Don't diagnose declarations at file scope.
6972   if (D->hasGlobalStorage())
6973     return nullptr;
6974 
6975   NamedDecl *ShadowedDecl = R.getFoundDecl();
6976   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6977              ? ShadowedDecl
6978              : nullptr;
6979 }
6980 
6981 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6982 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6983 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6984                                         const LookupResult &R) {
6985   // Don't warn if typedef declaration is part of a class
6986   if (D->getDeclContext()->isRecord())
6987     return nullptr;
6988 
6989   if (!shouldWarnIfShadowedDecl(Diags, R))
6990     return nullptr;
6991 
6992   NamedDecl *ShadowedDecl = R.getFoundDecl();
6993   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6994 }
6995 
6996 /// \brief Diagnose variable or built-in function shadowing.  Implements
6997 /// -Wshadow.
6998 ///
6999 /// This method is called whenever a VarDecl is added to a "useful"
7000 /// scope.
7001 ///
7002 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7003 /// \param R the lookup of the name
7004 ///
7005 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7006                        const LookupResult &R) {
7007   DeclContext *NewDC = D->getDeclContext();
7008 
7009   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7010     // Fields are not shadowed by variables in C++ static methods.
7011     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7012       if (MD->isStatic())
7013         return;
7014 
7015     // Fields shadowed by constructor parameters are a special case. Usually
7016     // the constructor initializes the field with the parameter.
7017     if (isa<CXXConstructorDecl>(NewDC))
7018       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7019         // Remember that this was shadowed so we can either warn about its
7020         // modification or its existence depending on warning settings.
7021         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7022         return;
7023       }
7024   }
7025 
7026   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7027     if (shadowedVar->isExternC()) {
7028       // For shadowing external vars, make sure that we point to the global
7029       // declaration, not a locally scoped extern declaration.
7030       for (auto I : shadowedVar->redecls())
7031         if (I->isFileVarDecl()) {
7032           ShadowedDecl = I;
7033           break;
7034         }
7035     }
7036 
7037   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7038 
7039   unsigned WarningDiag = diag::warn_decl_shadow;
7040   SourceLocation CaptureLoc;
7041   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7042       isa<CXXMethodDecl>(NewDC)) {
7043     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7044       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7045         if (RD->getLambdaCaptureDefault() == LCD_None) {
7046           // Try to avoid warnings for lambdas with an explicit capture list.
7047           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7048           // Warn only when the lambda captures the shadowed decl explicitly.
7049           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7050           if (CaptureLoc.isInvalid())
7051             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7052         } else {
7053           // Remember that this was shadowed so we can avoid the warning if the
7054           // shadowed decl isn't captured and the warning settings allow it.
7055           cast<LambdaScopeInfo>(getCurFunction())
7056               ->ShadowingDecls.push_back(
7057                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7058           return;
7059         }
7060       }
7061 
7062       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7063         // A variable can't shadow a local variable in an enclosing scope, if
7064         // they are separated by a non-capturing declaration context.
7065         for (DeclContext *ParentDC = NewDC;
7066              ParentDC && !ParentDC->Equals(OldDC);
7067              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7068           // Only block literals, captured statements, and lambda expressions
7069           // can capture; other scopes don't.
7070           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7071               !isLambdaCallOperator(ParentDC)) {
7072             return;
7073           }
7074         }
7075       }
7076     }
7077   }
7078 
7079   // Only warn about certain kinds of shadowing for class members.
7080   if (NewDC && NewDC->isRecord()) {
7081     // In particular, don't warn about shadowing non-class members.
7082     if (!OldDC->isRecord())
7083       return;
7084 
7085     // TODO: should we warn about static data members shadowing
7086     // static data members from base classes?
7087 
7088     // TODO: don't diagnose for inaccessible shadowed members.
7089     // This is hard to do perfectly because we might friend the
7090     // shadowing context, but that's just a false negative.
7091   }
7092 
7093 
7094   DeclarationName Name = R.getLookupName();
7095 
7096   // Emit warning and note.
7097   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7098     return;
7099   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7100   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7101   if (!CaptureLoc.isInvalid())
7102     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7103         << Name << /*explicitly*/ 1;
7104   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7105 }
7106 
7107 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7108 /// when these variables are captured by the lambda.
7109 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7110   for (const auto &Shadow : LSI->ShadowingDecls) {
7111     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7112     // Try to avoid the warning when the shadowed decl isn't captured.
7113     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7114     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7115     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7116                                        ? diag::warn_decl_shadow_uncaptured_local
7117                                        : diag::warn_decl_shadow)
7118         << Shadow.VD->getDeclName()
7119         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7120     if (!CaptureLoc.isInvalid())
7121       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7122           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7123     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7124   }
7125 }
7126 
7127 /// \brief Check -Wshadow without the advantage of a previous lookup.
7128 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7129   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7130     return;
7131 
7132   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7133                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7134   LookupName(R, S);
7135   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7136     CheckShadow(D, ShadowedDecl, R);
7137 }
7138 
7139 /// Check if 'E', which is an expression that is about to be modified, refers
7140 /// to a constructor parameter that shadows a field.
7141 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7142   // Quickly ignore expressions that can't be shadowing ctor parameters.
7143   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7144     return;
7145   E = E->IgnoreParenImpCasts();
7146   auto *DRE = dyn_cast<DeclRefExpr>(E);
7147   if (!DRE)
7148     return;
7149   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7150   auto I = ShadowingDecls.find(D);
7151   if (I == ShadowingDecls.end())
7152     return;
7153   const NamedDecl *ShadowedDecl = I->second;
7154   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7155   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7156   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7157   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7158 
7159   // Avoid issuing multiple warnings about the same decl.
7160   ShadowingDecls.erase(I);
7161 }
7162 
7163 /// Check for conflict between this global or extern "C" declaration and
7164 /// previous global or extern "C" declarations. This is only used in C++.
7165 template<typename T>
7166 static bool checkGlobalOrExternCConflict(
7167     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7168   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7169   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7170 
7171   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7172     // The common case: this global doesn't conflict with any extern "C"
7173     // declaration.
7174     return false;
7175   }
7176 
7177   if (Prev) {
7178     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7179       // Both the old and new declarations have C language linkage. This is a
7180       // redeclaration.
7181       Previous.clear();
7182       Previous.addDecl(Prev);
7183       return true;
7184     }
7185 
7186     // This is a global, non-extern "C" declaration, and there is a previous
7187     // non-global extern "C" declaration. Diagnose if this is a variable
7188     // declaration.
7189     if (!isa<VarDecl>(ND))
7190       return false;
7191   } else {
7192     // The declaration is extern "C". Check for any declaration in the
7193     // translation unit which might conflict.
7194     if (IsGlobal) {
7195       // We have already performed the lookup into the translation unit.
7196       IsGlobal = false;
7197       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7198            I != E; ++I) {
7199         if (isa<VarDecl>(*I)) {
7200           Prev = *I;
7201           break;
7202         }
7203       }
7204     } else {
7205       DeclContext::lookup_result R =
7206           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7207       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7208            I != E; ++I) {
7209         if (isa<VarDecl>(*I)) {
7210           Prev = *I;
7211           break;
7212         }
7213         // FIXME: If we have any other entity with this name in global scope,
7214         // the declaration is ill-formed, but that is a defect: it breaks the
7215         // 'stat' hack, for instance. Only variables can have mangled name
7216         // clashes with extern "C" declarations, so only they deserve a
7217         // diagnostic.
7218       }
7219     }
7220 
7221     if (!Prev)
7222       return false;
7223   }
7224 
7225   // Use the first declaration's location to ensure we point at something which
7226   // is lexically inside an extern "C" linkage-spec.
7227   assert(Prev && "should have found a previous declaration to diagnose");
7228   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7229     Prev = FD->getFirstDecl();
7230   else
7231     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7232 
7233   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7234     << IsGlobal << ND;
7235   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7236     << IsGlobal;
7237   return false;
7238 }
7239 
7240 /// Apply special rules for handling extern "C" declarations. Returns \c true
7241 /// if we have found that this is a redeclaration of some prior entity.
7242 ///
7243 /// Per C++ [dcl.link]p6:
7244 ///   Two declarations [for a function or variable] with C language linkage
7245 ///   with the same name that appear in different scopes refer to the same
7246 ///   [entity]. An entity with C language linkage shall not be declared with
7247 ///   the same name as an entity in global scope.
7248 template<typename T>
7249 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7250                                                   LookupResult &Previous) {
7251   if (!S.getLangOpts().CPlusPlus) {
7252     // In C, when declaring a global variable, look for a corresponding 'extern'
7253     // variable declared in function scope. We don't need this in C++, because
7254     // we find local extern decls in the surrounding file-scope DeclContext.
7255     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7256       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7257         Previous.clear();
7258         Previous.addDecl(Prev);
7259         return true;
7260       }
7261     }
7262     return false;
7263   }
7264 
7265   // A declaration in the translation unit can conflict with an extern "C"
7266   // declaration.
7267   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7268     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7269 
7270   // An extern "C" declaration can conflict with a declaration in the
7271   // translation unit or can be a redeclaration of an extern "C" declaration
7272   // in another scope.
7273   if (isIncompleteDeclExternC(S,ND))
7274     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7275 
7276   // Neither global nor extern "C": nothing to do.
7277   return false;
7278 }
7279 
7280 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7281   // If the decl is already known invalid, don't check it.
7282   if (NewVD->isInvalidDecl())
7283     return;
7284 
7285   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7286   QualType T = TInfo->getType();
7287 
7288   // Defer checking an 'auto' type until its initializer is attached.
7289   if (T->isUndeducedType())
7290     return;
7291 
7292   if (NewVD->hasAttrs())
7293     CheckAlignasUnderalignment(NewVD);
7294 
7295   if (T->isObjCObjectType()) {
7296     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7297       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7298     T = Context.getObjCObjectPointerType(T);
7299     NewVD->setType(T);
7300   }
7301 
7302   // Emit an error if an address space was applied to decl with local storage.
7303   // This includes arrays of objects with address space qualifiers, but not
7304   // automatic variables that point to other address spaces.
7305   // ISO/IEC TR 18037 S5.1.2
7306   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7307       T.getAddressSpace() != LangAS::Default) {
7308     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7309     NewVD->setInvalidDecl();
7310     return;
7311   }
7312 
7313   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7314   // scope.
7315   if (getLangOpts().OpenCLVersion == 120 &&
7316       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7317       NewVD->isStaticLocal()) {
7318     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7319     NewVD->setInvalidDecl();
7320     return;
7321   }
7322 
7323   if (getLangOpts().OpenCL) {
7324     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7325     if (NewVD->hasAttr<BlocksAttr>()) {
7326       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7327       return;
7328     }
7329 
7330     if (T->isBlockPointerType()) {
7331       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7332       // can't use 'extern' storage class.
7333       if (!T.isConstQualified()) {
7334         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7335             << 0 /*const*/;
7336         NewVD->setInvalidDecl();
7337         return;
7338       }
7339       if (NewVD->hasExternalStorage()) {
7340         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7341         NewVD->setInvalidDecl();
7342         return;
7343       }
7344     }
7345     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7346     // __constant address space.
7347     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7348     // variables inside a function can also be declared in the global
7349     // address space.
7350     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7351         NewVD->hasExternalStorage()) {
7352       if (!T->isSamplerT() &&
7353           !(T.getAddressSpace() == LangAS::opencl_constant ||
7354             (T.getAddressSpace() == LangAS::opencl_global &&
7355              getLangOpts().OpenCLVersion == 200))) {
7356         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7357         if (getLangOpts().OpenCLVersion == 200)
7358           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7359               << Scope << "global or constant";
7360         else
7361           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7362               << Scope << "constant";
7363         NewVD->setInvalidDecl();
7364         return;
7365       }
7366     } else {
7367       if (T.getAddressSpace() == LangAS::opencl_global) {
7368         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7369             << 1 /*is any function*/ << "global";
7370         NewVD->setInvalidDecl();
7371         return;
7372       }
7373       if (T.getAddressSpace() == LangAS::opencl_constant ||
7374           T.getAddressSpace() == LangAS::opencl_local) {
7375         FunctionDecl *FD = getCurFunctionDecl();
7376         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7377         // in functions.
7378         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7379           if (T.getAddressSpace() == LangAS::opencl_constant)
7380             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7381                 << 0 /*non-kernel only*/ << "constant";
7382           else
7383             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7384                 << 0 /*non-kernel only*/ << "local";
7385           NewVD->setInvalidDecl();
7386           return;
7387         }
7388         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7389         // in the outermost scope of a kernel function.
7390         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7391           if (!getCurScope()->isFunctionScope()) {
7392             if (T.getAddressSpace() == LangAS::opencl_constant)
7393               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7394                   << "constant";
7395             else
7396               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7397                   << "local";
7398             NewVD->setInvalidDecl();
7399             return;
7400           }
7401         }
7402       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7403         // Do not allow other address spaces on automatic variable.
7404         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7405         NewVD->setInvalidDecl();
7406         return;
7407       }
7408     }
7409   }
7410 
7411   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7412       && !NewVD->hasAttr<BlocksAttr>()) {
7413     if (getLangOpts().getGC() != LangOptions::NonGC)
7414       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7415     else {
7416       assert(!getLangOpts().ObjCAutoRefCount);
7417       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7418     }
7419   }
7420 
7421   bool isVM = T->isVariablyModifiedType();
7422   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7423       NewVD->hasAttr<BlocksAttr>())
7424     setFunctionHasBranchProtectedScope();
7425 
7426   if ((isVM && NewVD->hasLinkage()) ||
7427       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7428     bool SizeIsNegative;
7429     llvm::APSInt Oversized;
7430     TypeSourceInfo *FixedTInfo =
7431       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7432                                                     SizeIsNegative, Oversized);
7433     if (!FixedTInfo && T->isVariableArrayType()) {
7434       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7435       // FIXME: This won't give the correct result for
7436       // int a[10][n];
7437       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7438 
7439       if (NewVD->isFileVarDecl())
7440         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7441         << SizeRange;
7442       else if (NewVD->isStaticLocal())
7443         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7444         << SizeRange;
7445       else
7446         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7447         << SizeRange;
7448       NewVD->setInvalidDecl();
7449       return;
7450     }
7451 
7452     if (!FixedTInfo) {
7453       if (NewVD->isFileVarDecl())
7454         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7455       else
7456         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7457       NewVD->setInvalidDecl();
7458       return;
7459     }
7460 
7461     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7462     NewVD->setType(FixedTInfo->getType());
7463     NewVD->setTypeSourceInfo(FixedTInfo);
7464   }
7465 
7466   if (T->isVoidType()) {
7467     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7468     //                    of objects and functions.
7469     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7470       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7471         << T;
7472       NewVD->setInvalidDecl();
7473       return;
7474     }
7475   }
7476 
7477   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7478     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7479     NewVD->setInvalidDecl();
7480     return;
7481   }
7482 
7483   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7484     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7485     NewVD->setInvalidDecl();
7486     return;
7487   }
7488 
7489   if (NewVD->isConstexpr() && !T->isDependentType() &&
7490       RequireLiteralType(NewVD->getLocation(), T,
7491                          diag::err_constexpr_var_non_literal)) {
7492     NewVD->setInvalidDecl();
7493     return;
7494   }
7495 }
7496 
7497 /// \brief Perform semantic checking on a newly-created variable
7498 /// declaration.
7499 ///
7500 /// This routine performs all of the type-checking required for a
7501 /// variable declaration once it has been built. It is used both to
7502 /// check variables after they have been parsed and their declarators
7503 /// have been translated into a declaration, and to check variables
7504 /// that have been instantiated from a template.
7505 ///
7506 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7507 ///
7508 /// Returns true if the variable declaration is a redeclaration.
7509 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7510   CheckVariableDeclarationType(NewVD);
7511 
7512   // If the decl is already known invalid, don't check it.
7513   if (NewVD->isInvalidDecl())
7514     return false;
7515 
7516   // If we did not find anything by this name, look for a non-visible
7517   // extern "C" declaration with the same name.
7518   if (Previous.empty() &&
7519       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7520     Previous.setShadowed();
7521 
7522   if (!Previous.empty()) {
7523     MergeVarDecl(NewVD, Previous);
7524     return true;
7525   }
7526   return false;
7527 }
7528 
7529 namespace {
7530 struct FindOverriddenMethod {
7531   Sema *S;
7532   CXXMethodDecl *Method;
7533 
7534   /// Member lookup function that determines whether a given C++
7535   /// method overrides a method in a base class, to be used with
7536   /// CXXRecordDecl::lookupInBases().
7537   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7538     RecordDecl *BaseRecord =
7539         Specifier->getType()->getAs<RecordType>()->getDecl();
7540 
7541     DeclarationName Name = Method->getDeclName();
7542 
7543     // FIXME: Do we care about other names here too?
7544     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7545       // We really want to find the base class destructor here.
7546       QualType T = S->Context.getTypeDeclType(BaseRecord);
7547       CanQualType CT = S->Context.getCanonicalType(T);
7548 
7549       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7550     }
7551 
7552     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7553          Path.Decls = Path.Decls.slice(1)) {
7554       NamedDecl *D = Path.Decls.front();
7555       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7556         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7557           return true;
7558       }
7559     }
7560 
7561     return false;
7562   }
7563 };
7564 
7565 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7566 } // end anonymous namespace
7567 
7568 /// \brief Report an error regarding overriding, along with any relevant
7569 /// overridden methods.
7570 ///
7571 /// \param DiagID the primary error to report.
7572 /// \param MD the overriding method.
7573 /// \param OEK which overrides to include as notes.
7574 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7575                             OverrideErrorKind OEK = OEK_All) {
7576   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7577   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7578     // This check (& the OEK parameter) could be replaced by a predicate, but
7579     // without lambdas that would be overkill. This is still nicer than writing
7580     // out the diag loop 3 times.
7581     if ((OEK == OEK_All) ||
7582         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7583         (OEK == OEK_Deleted && O->isDeleted()))
7584       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7585   }
7586 }
7587 
7588 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7589 /// and if so, check that it's a valid override and remember it.
7590 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7591   // Look for methods in base classes that this method might override.
7592   CXXBasePaths Paths;
7593   FindOverriddenMethod FOM;
7594   FOM.Method = MD;
7595   FOM.S = this;
7596   bool hasDeletedOverridenMethods = false;
7597   bool hasNonDeletedOverridenMethods = false;
7598   bool AddedAny = false;
7599   if (DC->lookupInBases(FOM, Paths)) {
7600     for (auto *I : Paths.found_decls()) {
7601       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7602         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7603         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7604             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7605             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7606             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7607           hasDeletedOverridenMethods |= OldMD->isDeleted();
7608           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7609           AddedAny = true;
7610         }
7611       }
7612     }
7613   }
7614 
7615   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7616     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7617   }
7618   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7619     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7620   }
7621 
7622   return AddedAny;
7623 }
7624 
7625 namespace {
7626   // Struct for holding all of the extra arguments needed by
7627   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7628   struct ActOnFDArgs {
7629     Scope *S;
7630     Declarator &D;
7631     MultiTemplateParamsArg TemplateParamLists;
7632     bool AddToScope;
7633   };
7634 } // end anonymous namespace
7635 
7636 namespace {
7637 
7638 // Callback to only accept typo corrections that have a non-zero edit distance.
7639 // Also only accept corrections that have the same parent decl.
7640 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7641  public:
7642   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7643                             CXXRecordDecl *Parent)
7644       : Context(Context), OriginalFD(TypoFD),
7645         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7646 
7647   bool ValidateCandidate(const TypoCorrection &candidate) override {
7648     if (candidate.getEditDistance() == 0)
7649       return false;
7650 
7651     SmallVector<unsigned, 1> MismatchedParams;
7652     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7653                                           CDeclEnd = candidate.end();
7654          CDecl != CDeclEnd; ++CDecl) {
7655       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7656 
7657       if (FD && !FD->hasBody() &&
7658           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7659         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7660           CXXRecordDecl *Parent = MD->getParent();
7661           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7662             return true;
7663         } else if (!ExpectedParent) {
7664           return true;
7665         }
7666       }
7667     }
7668 
7669     return false;
7670   }
7671 
7672  private:
7673   ASTContext &Context;
7674   FunctionDecl *OriginalFD;
7675   CXXRecordDecl *ExpectedParent;
7676 };
7677 
7678 } // end anonymous namespace
7679 
7680 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7681   TypoCorrectedFunctionDefinitions.insert(F);
7682 }
7683 
7684 /// \brief Generate diagnostics for an invalid function redeclaration.
7685 ///
7686 /// This routine handles generating the diagnostic messages for an invalid
7687 /// function redeclaration, including finding possible similar declarations
7688 /// or performing typo correction if there are no previous declarations with
7689 /// the same name.
7690 ///
7691 /// Returns a NamedDecl iff typo correction was performed and substituting in
7692 /// the new declaration name does not cause new errors.
7693 static NamedDecl *DiagnoseInvalidRedeclaration(
7694     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7695     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7696   DeclarationName Name = NewFD->getDeclName();
7697   DeclContext *NewDC = NewFD->getDeclContext();
7698   SmallVector<unsigned, 1> MismatchedParams;
7699   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7700   TypoCorrection Correction;
7701   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7702   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7703                                    : diag::err_member_decl_does_not_match;
7704   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7705                     IsLocalFriend ? Sema::LookupLocalFriendName
7706                                   : Sema::LookupOrdinaryName,
7707                     Sema::ForVisibleRedeclaration);
7708 
7709   NewFD->setInvalidDecl();
7710   if (IsLocalFriend)
7711     SemaRef.LookupName(Prev, S);
7712   else
7713     SemaRef.LookupQualifiedName(Prev, NewDC);
7714   assert(!Prev.isAmbiguous() &&
7715          "Cannot have an ambiguity in previous-declaration lookup");
7716   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7717   if (!Prev.empty()) {
7718     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7719          Func != FuncEnd; ++Func) {
7720       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7721       if (FD &&
7722           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7723         // Add 1 to the index so that 0 can mean the mismatch didn't
7724         // involve a parameter
7725         unsigned ParamNum =
7726             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7727         NearMatches.push_back(std::make_pair(FD, ParamNum));
7728       }
7729     }
7730   // If the qualified name lookup yielded nothing, try typo correction
7731   } else if ((Correction = SemaRef.CorrectTypo(
7732                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7733                   &ExtraArgs.D.getCXXScopeSpec(),
7734                   llvm::make_unique<DifferentNameValidatorCCC>(
7735                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7736                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7737     // Set up everything for the call to ActOnFunctionDeclarator
7738     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7739                               ExtraArgs.D.getIdentifierLoc());
7740     Previous.clear();
7741     Previous.setLookupName(Correction.getCorrection());
7742     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7743                                     CDeclEnd = Correction.end();
7744          CDecl != CDeclEnd; ++CDecl) {
7745       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7746       if (FD && !FD->hasBody() &&
7747           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7748         Previous.addDecl(FD);
7749       }
7750     }
7751     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7752 
7753     NamedDecl *Result;
7754     // Retry building the function declaration with the new previous
7755     // declarations, and with errors suppressed.
7756     {
7757       // Trap errors.
7758       Sema::SFINAETrap Trap(SemaRef);
7759 
7760       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7761       // pieces need to verify the typo-corrected C++ declaration and hopefully
7762       // eliminate the need for the parameter pack ExtraArgs.
7763       Result = SemaRef.ActOnFunctionDeclarator(
7764           ExtraArgs.S, ExtraArgs.D,
7765           Correction.getCorrectionDecl()->getDeclContext(),
7766           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7767           ExtraArgs.AddToScope);
7768 
7769       if (Trap.hasErrorOccurred())
7770         Result = nullptr;
7771     }
7772 
7773     if (Result) {
7774       // Determine which correction we picked.
7775       Decl *Canonical = Result->getCanonicalDecl();
7776       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7777            I != E; ++I)
7778         if ((*I)->getCanonicalDecl() == Canonical)
7779           Correction.setCorrectionDecl(*I);
7780 
7781       // Let Sema know about the correction.
7782       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7783       SemaRef.diagnoseTypo(
7784           Correction,
7785           SemaRef.PDiag(IsLocalFriend
7786                           ? diag::err_no_matching_local_friend_suggest
7787                           : diag::err_member_decl_does_not_match_suggest)
7788             << Name << NewDC << IsDefinition);
7789       return Result;
7790     }
7791 
7792     // Pretend the typo correction never occurred
7793     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7794                               ExtraArgs.D.getIdentifierLoc());
7795     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7796     Previous.clear();
7797     Previous.setLookupName(Name);
7798   }
7799 
7800   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7801       << Name << NewDC << IsDefinition << NewFD->getLocation();
7802 
7803   bool NewFDisConst = false;
7804   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7805     NewFDisConst = NewMD->isConst();
7806 
7807   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7808        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7809        NearMatch != NearMatchEnd; ++NearMatch) {
7810     FunctionDecl *FD = NearMatch->first;
7811     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7812     bool FDisConst = MD && MD->isConst();
7813     bool IsMember = MD || !IsLocalFriend;
7814 
7815     // FIXME: These notes are poorly worded for the local friend case.
7816     if (unsigned Idx = NearMatch->second) {
7817       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7818       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7819       if (Loc.isInvalid()) Loc = FD->getLocation();
7820       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7821                                  : diag::note_local_decl_close_param_match)
7822         << Idx << FDParam->getType()
7823         << NewFD->getParamDecl(Idx - 1)->getType();
7824     } else if (FDisConst != NewFDisConst) {
7825       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7826           << NewFDisConst << FD->getSourceRange().getEnd();
7827     } else
7828       SemaRef.Diag(FD->getLocation(),
7829                    IsMember ? diag::note_member_def_close_match
7830                             : diag::note_local_decl_close_match);
7831   }
7832   return nullptr;
7833 }
7834 
7835 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7836   switch (D.getDeclSpec().getStorageClassSpec()) {
7837   default: llvm_unreachable("Unknown storage class!");
7838   case DeclSpec::SCS_auto:
7839   case DeclSpec::SCS_register:
7840   case DeclSpec::SCS_mutable:
7841     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7842                  diag::err_typecheck_sclass_func);
7843     D.getMutableDeclSpec().ClearStorageClassSpecs();
7844     D.setInvalidType();
7845     break;
7846   case DeclSpec::SCS_unspecified: break;
7847   case DeclSpec::SCS_extern:
7848     if (D.getDeclSpec().isExternInLinkageSpec())
7849       return SC_None;
7850     return SC_Extern;
7851   case DeclSpec::SCS_static: {
7852     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7853       // C99 6.7.1p5:
7854       //   The declaration of an identifier for a function that has
7855       //   block scope shall have no explicit storage-class specifier
7856       //   other than extern
7857       // See also (C++ [dcl.stc]p4).
7858       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7859                    diag::err_static_block_func);
7860       break;
7861     } else
7862       return SC_Static;
7863   }
7864   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7865   }
7866 
7867   // No explicit storage class has already been returned
7868   return SC_None;
7869 }
7870 
7871 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7872                                            DeclContext *DC, QualType &R,
7873                                            TypeSourceInfo *TInfo,
7874                                            StorageClass SC,
7875                                            bool &IsVirtualOkay) {
7876   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7877   DeclarationName Name = NameInfo.getName();
7878 
7879   FunctionDecl *NewFD = nullptr;
7880   bool isInline = D.getDeclSpec().isInlineSpecified();
7881 
7882   if (!SemaRef.getLangOpts().CPlusPlus) {
7883     // Determine whether the function was written with a
7884     // prototype. This true when:
7885     //   - there is a prototype in the declarator, or
7886     //   - the type R of the function is some kind of typedef or other non-
7887     //     attributed reference to a type name (which eventually refers to a
7888     //     function type).
7889     bool HasPrototype =
7890       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7891       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7892 
7893     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7894                                  D.getLocStart(), NameInfo, R,
7895                                  TInfo, SC, isInline,
7896                                  HasPrototype, false);
7897     if (D.isInvalidType())
7898       NewFD->setInvalidDecl();
7899 
7900     return NewFD;
7901   }
7902 
7903   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7904   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7905 
7906   // Check that the return type is not an abstract class type.
7907   // For record types, this is done by the AbstractClassUsageDiagnoser once
7908   // the class has been completely parsed.
7909   if (!DC->isRecord() &&
7910       SemaRef.RequireNonAbstractType(
7911           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7912           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7913     D.setInvalidType();
7914 
7915   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7916     // This is a C++ constructor declaration.
7917     assert(DC->isRecord() &&
7918            "Constructors can only be declared in a member context");
7919 
7920     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7921     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7922                                       D.getLocStart(), NameInfo,
7923                                       R, TInfo, isExplicit, isInline,
7924                                       /*isImplicitlyDeclared=*/false,
7925                                       isConstexpr);
7926 
7927   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7928     // This is a C++ destructor declaration.
7929     if (DC->isRecord()) {
7930       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7931       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7932       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7933                                         SemaRef.Context, Record,
7934                                         D.getLocStart(),
7935                                         NameInfo, R, TInfo, isInline,
7936                                         /*isImplicitlyDeclared=*/false);
7937 
7938       // If the class is complete, then we now create the implicit exception
7939       // specification. If the class is incomplete or dependent, we can't do
7940       // it yet.
7941       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7942           Record->getDefinition() && !Record->isBeingDefined() &&
7943           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7944         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7945       }
7946 
7947       IsVirtualOkay = true;
7948       return NewDD;
7949 
7950     } else {
7951       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7952       D.setInvalidType();
7953 
7954       // Create a FunctionDecl to satisfy the function definition parsing
7955       // code path.
7956       return FunctionDecl::Create(SemaRef.Context, DC,
7957                                   D.getLocStart(),
7958                                   D.getIdentifierLoc(), Name, R, TInfo,
7959                                   SC, isInline,
7960                                   /*hasPrototype=*/true, isConstexpr);
7961     }
7962 
7963   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7964     if (!DC->isRecord()) {
7965       SemaRef.Diag(D.getIdentifierLoc(),
7966            diag::err_conv_function_not_member);
7967       return nullptr;
7968     }
7969 
7970     SemaRef.CheckConversionDeclarator(D, R, SC);
7971     IsVirtualOkay = true;
7972     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7973                                      D.getLocStart(), NameInfo,
7974                                      R, TInfo, isInline, isExplicit,
7975                                      isConstexpr, SourceLocation());
7976 
7977   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7978     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7979 
7980     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7981                                          isExplicit, NameInfo, R, TInfo,
7982                                          D.getLocEnd());
7983   } else if (DC->isRecord()) {
7984     // If the name of the function is the same as the name of the record,
7985     // then this must be an invalid constructor that has a return type.
7986     // (The parser checks for a return type and makes the declarator a
7987     // constructor if it has no return type).
7988     if (Name.getAsIdentifierInfo() &&
7989         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7990       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7991         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7992         << SourceRange(D.getIdentifierLoc());
7993       return nullptr;
7994     }
7995 
7996     // This is a C++ method declaration.
7997     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7998                                                cast<CXXRecordDecl>(DC),
7999                                                D.getLocStart(), NameInfo, R,
8000                                                TInfo, SC, isInline,
8001                                                isConstexpr, SourceLocation());
8002     IsVirtualOkay = !Ret->isStatic();
8003     return Ret;
8004   } else {
8005     bool isFriend =
8006         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8007     if (!isFriend && SemaRef.CurContext->isRecord())
8008       return nullptr;
8009 
8010     // Determine whether the function was written with a
8011     // prototype. This true when:
8012     //   - we're in C++ (where every function has a prototype),
8013     return FunctionDecl::Create(SemaRef.Context, DC,
8014                                 D.getLocStart(),
8015                                 NameInfo, R, TInfo, SC, isInline,
8016                                 true/*HasPrototype*/, isConstexpr);
8017   }
8018 }
8019 
8020 enum OpenCLParamType {
8021   ValidKernelParam,
8022   PtrPtrKernelParam,
8023   PtrKernelParam,
8024   InvalidAddrSpacePtrKernelParam,
8025   InvalidKernelParam,
8026   RecordKernelParam
8027 };
8028 
8029 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8030   if (PT->isPointerType()) {
8031     QualType PointeeType = PT->getPointeeType();
8032     if (PointeeType->isPointerType())
8033       return PtrPtrKernelParam;
8034     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8035         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8036         PointeeType.getAddressSpace() == LangAS::Default)
8037       return InvalidAddrSpacePtrKernelParam;
8038     return PtrKernelParam;
8039   }
8040 
8041   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8042   // be used as builtin types.
8043 
8044   if (PT->isImageType())
8045     return PtrKernelParam;
8046 
8047   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8048     return InvalidKernelParam;
8049 
8050   // OpenCL extension spec v1.2 s9.5:
8051   // This extension adds support for half scalar and vector types as built-in
8052   // types that can be used for arithmetic operations, conversions etc.
8053   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8054     return InvalidKernelParam;
8055 
8056   if (PT->isRecordType())
8057     return RecordKernelParam;
8058 
8059   return ValidKernelParam;
8060 }
8061 
8062 static void checkIsValidOpenCLKernelParameter(
8063   Sema &S,
8064   Declarator &D,
8065   ParmVarDecl *Param,
8066   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8067   QualType PT = Param->getType();
8068 
8069   // Cache the valid types we encounter to avoid rechecking structs that are
8070   // used again
8071   if (ValidTypes.count(PT.getTypePtr()))
8072     return;
8073 
8074   switch (getOpenCLKernelParameterType(S, PT)) {
8075   case PtrPtrKernelParam:
8076     // OpenCL v1.2 s6.9.a:
8077     // A kernel function argument cannot be declared as a
8078     // pointer to a pointer type.
8079     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8080     D.setInvalidType();
8081     return;
8082 
8083   case InvalidAddrSpacePtrKernelParam:
8084     // OpenCL v1.0 s6.5:
8085     // __kernel function arguments declared to be a pointer of a type can point
8086     // to one of the following address spaces only : __global, __local or
8087     // __constant.
8088     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8089     D.setInvalidType();
8090     return;
8091 
8092     // OpenCL v1.2 s6.9.k:
8093     // Arguments to kernel functions in a program cannot be declared with the
8094     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8095     // uintptr_t or a struct and/or union that contain fields declared to be
8096     // one of these built-in scalar types.
8097 
8098   case InvalidKernelParam:
8099     // OpenCL v1.2 s6.8 n:
8100     // A kernel function argument cannot be declared
8101     // of event_t type.
8102     // Do not diagnose half type since it is diagnosed as invalid argument
8103     // type for any function elsewhere.
8104     if (!PT->isHalfType())
8105       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8106     D.setInvalidType();
8107     return;
8108 
8109   case PtrKernelParam:
8110   case ValidKernelParam:
8111     ValidTypes.insert(PT.getTypePtr());
8112     return;
8113 
8114   case RecordKernelParam:
8115     break;
8116   }
8117 
8118   // Track nested structs we will inspect
8119   SmallVector<const Decl *, 4> VisitStack;
8120 
8121   // Track where we are in the nested structs. Items will migrate from
8122   // VisitStack to HistoryStack as we do the DFS for bad field.
8123   SmallVector<const FieldDecl *, 4> HistoryStack;
8124   HistoryStack.push_back(nullptr);
8125 
8126   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8127   VisitStack.push_back(PD);
8128 
8129   assert(VisitStack.back() && "First decl null?");
8130 
8131   do {
8132     const Decl *Next = VisitStack.pop_back_val();
8133     if (!Next) {
8134       assert(!HistoryStack.empty());
8135       // Found a marker, we have gone up a level
8136       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8137         ValidTypes.insert(Hist->getType().getTypePtr());
8138 
8139       continue;
8140     }
8141 
8142     // Adds everything except the original parameter declaration (which is not a
8143     // field itself) to the history stack.
8144     const RecordDecl *RD;
8145     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8146       HistoryStack.push_back(Field);
8147       RD = Field->getType()->castAs<RecordType>()->getDecl();
8148     } else {
8149       RD = cast<RecordDecl>(Next);
8150     }
8151 
8152     // Add a null marker so we know when we've gone back up a level
8153     VisitStack.push_back(nullptr);
8154 
8155     for (const auto *FD : RD->fields()) {
8156       QualType QT = FD->getType();
8157 
8158       if (ValidTypes.count(QT.getTypePtr()))
8159         continue;
8160 
8161       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8162       if (ParamType == ValidKernelParam)
8163         continue;
8164 
8165       if (ParamType == RecordKernelParam) {
8166         VisitStack.push_back(FD);
8167         continue;
8168       }
8169 
8170       // OpenCL v1.2 s6.9.p:
8171       // Arguments to kernel functions that are declared to be a struct or union
8172       // do not allow OpenCL objects to be passed as elements of the struct or
8173       // union.
8174       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8175           ParamType == InvalidAddrSpacePtrKernelParam) {
8176         S.Diag(Param->getLocation(),
8177                diag::err_record_with_pointers_kernel_param)
8178           << PT->isUnionType()
8179           << PT;
8180       } else {
8181         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8182       }
8183 
8184       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8185         << PD->getDeclName();
8186 
8187       // We have an error, now let's go back up through history and show where
8188       // the offending field came from
8189       for (ArrayRef<const FieldDecl *>::const_iterator
8190                I = HistoryStack.begin() + 1,
8191                E = HistoryStack.end();
8192            I != E; ++I) {
8193         const FieldDecl *OuterField = *I;
8194         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8195           << OuterField->getType();
8196       }
8197 
8198       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8199         << QT->isPointerType()
8200         << QT;
8201       D.setInvalidType();
8202       return;
8203     }
8204   } while (!VisitStack.empty());
8205 }
8206 
8207 /// Find the DeclContext in which a tag is implicitly declared if we see an
8208 /// elaborated type specifier in the specified context, and lookup finds
8209 /// nothing.
8210 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8211   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8212     DC = DC->getParent();
8213   return DC;
8214 }
8215 
8216 /// Find the Scope in which a tag is implicitly declared if we see an
8217 /// elaborated type specifier in the specified context, and lookup finds
8218 /// nothing.
8219 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8220   while (S->isClassScope() ||
8221          (LangOpts.CPlusPlus &&
8222           S->isFunctionPrototypeScope()) ||
8223          ((S->getFlags() & Scope::DeclScope) == 0) ||
8224          (S->getEntity() && S->getEntity()->isTransparentContext()))
8225     S = S->getParent();
8226   return S;
8227 }
8228 
8229 NamedDecl*
8230 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8231                               TypeSourceInfo *TInfo, LookupResult &Previous,
8232                               MultiTemplateParamsArg TemplateParamLists,
8233                               bool &AddToScope) {
8234   QualType R = TInfo->getType();
8235 
8236   assert(R.getTypePtr()->isFunctionType());
8237 
8238   // TODO: consider using NameInfo for diagnostic.
8239   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8240   DeclarationName Name = NameInfo.getName();
8241   StorageClass SC = getFunctionStorageClass(*this, D);
8242 
8243   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8244     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8245          diag::err_invalid_thread)
8246       << DeclSpec::getSpecifierName(TSCS);
8247 
8248   if (D.isFirstDeclarationOfMember())
8249     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8250                            D.getIdentifierLoc());
8251 
8252   bool isFriend = false;
8253   FunctionTemplateDecl *FunctionTemplate = nullptr;
8254   bool isMemberSpecialization = false;
8255   bool isFunctionTemplateSpecialization = false;
8256 
8257   bool isDependentClassScopeExplicitSpecialization = false;
8258   bool HasExplicitTemplateArgs = false;
8259   TemplateArgumentListInfo TemplateArgs;
8260 
8261   bool isVirtualOkay = false;
8262 
8263   DeclContext *OriginalDC = DC;
8264   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8265 
8266   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8267                                               isVirtualOkay);
8268   if (!NewFD) return nullptr;
8269 
8270   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8271     NewFD->setTopLevelDeclInObjCContainer();
8272 
8273   // Set the lexical context. If this is a function-scope declaration, or has a
8274   // C++ scope specifier, or is the object of a friend declaration, the lexical
8275   // context will be different from the semantic context.
8276   NewFD->setLexicalDeclContext(CurContext);
8277 
8278   if (IsLocalExternDecl)
8279     NewFD->setLocalExternDecl();
8280 
8281   if (getLangOpts().CPlusPlus) {
8282     bool isInline = D.getDeclSpec().isInlineSpecified();
8283     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8284     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8285     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8286     isFriend = D.getDeclSpec().isFriendSpecified();
8287     if (isFriend && !isInline && D.isFunctionDefinition()) {
8288       // C++ [class.friend]p5
8289       //   A function can be defined in a friend declaration of a
8290       //   class . . . . Such a function is implicitly inline.
8291       NewFD->setImplicitlyInline();
8292     }
8293 
8294     // If this is a method defined in an __interface, and is not a constructor
8295     // or an overloaded operator, then set the pure flag (isVirtual will already
8296     // return true).
8297     if (const CXXRecordDecl *Parent =
8298           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8299       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8300         NewFD->setPure(true);
8301 
8302       // C++ [class.union]p2
8303       //   A union can have member functions, but not virtual functions.
8304       if (isVirtual && Parent->isUnion())
8305         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8306     }
8307 
8308     SetNestedNameSpecifier(NewFD, D);
8309     isMemberSpecialization = false;
8310     isFunctionTemplateSpecialization = false;
8311     if (D.isInvalidType())
8312       NewFD->setInvalidDecl();
8313 
8314     // Match up the template parameter lists with the scope specifier, then
8315     // determine whether we have a template or a template specialization.
8316     bool Invalid = false;
8317     if (TemplateParameterList *TemplateParams =
8318             MatchTemplateParametersToScopeSpecifier(
8319                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8320                 D.getCXXScopeSpec(),
8321                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8322                     ? D.getName().TemplateId
8323                     : nullptr,
8324                 TemplateParamLists, isFriend, isMemberSpecialization,
8325                 Invalid)) {
8326       if (TemplateParams->size() > 0) {
8327         // This is a function template
8328 
8329         // Check that we can declare a template here.
8330         if (CheckTemplateDeclScope(S, TemplateParams))
8331           NewFD->setInvalidDecl();
8332 
8333         // A destructor cannot be a template.
8334         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8335           Diag(NewFD->getLocation(), diag::err_destructor_template);
8336           NewFD->setInvalidDecl();
8337         }
8338 
8339         // If we're adding a template to a dependent context, we may need to
8340         // rebuilding some of the types used within the template parameter list,
8341         // now that we know what the current instantiation is.
8342         if (DC->isDependentContext()) {
8343           ContextRAII SavedContext(*this, DC);
8344           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8345             Invalid = true;
8346         }
8347 
8348         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8349                                                         NewFD->getLocation(),
8350                                                         Name, TemplateParams,
8351                                                         NewFD);
8352         FunctionTemplate->setLexicalDeclContext(CurContext);
8353         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8354 
8355         // For source fidelity, store the other template param lists.
8356         if (TemplateParamLists.size() > 1) {
8357           NewFD->setTemplateParameterListsInfo(Context,
8358                                                TemplateParamLists.drop_back(1));
8359         }
8360       } else {
8361         // This is a function template specialization.
8362         isFunctionTemplateSpecialization = true;
8363         // For source fidelity, store all the template param lists.
8364         if (TemplateParamLists.size() > 0)
8365           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8366 
8367         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8368         if (isFriend) {
8369           // We want to remove the "template<>", found here.
8370           SourceRange RemoveRange = TemplateParams->getSourceRange();
8371 
8372           // If we remove the template<> and the name is not a
8373           // template-id, we're actually silently creating a problem:
8374           // the friend declaration will refer to an untemplated decl,
8375           // and clearly the user wants a template specialization.  So
8376           // we need to insert '<>' after the name.
8377           SourceLocation InsertLoc;
8378           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8379             InsertLoc = D.getName().getSourceRange().getEnd();
8380             InsertLoc = getLocForEndOfToken(InsertLoc);
8381           }
8382 
8383           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8384             << Name << RemoveRange
8385             << FixItHint::CreateRemoval(RemoveRange)
8386             << FixItHint::CreateInsertion(InsertLoc, "<>");
8387         }
8388       }
8389     }
8390     else {
8391       // All template param lists were matched against the scope specifier:
8392       // this is NOT (an explicit specialization of) a template.
8393       if (TemplateParamLists.size() > 0)
8394         // For source fidelity, store all the template param lists.
8395         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8396     }
8397 
8398     if (Invalid) {
8399       NewFD->setInvalidDecl();
8400       if (FunctionTemplate)
8401         FunctionTemplate->setInvalidDecl();
8402     }
8403 
8404     // C++ [dcl.fct.spec]p5:
8405     //   The virtual specifier shall only be used in declarations of
8406     //   nonstatic class member functions that appear within a
8407     //   member-specification of a class declaration; see 10.3.
8408     //
8409     if (isVirtual && !NewFD->isInvalidDecl()) {
8410       if (!isVirtualOkay) {
8411         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8412              diag::err_virtual_non_function);
8413       } else if (!CurContext->isRecord()) {
8414         // 'virtual' was specified outside of the class.
8415         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8416              diag::err_virtual_out_of_class)
8417           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8418       } else if (NewFD->getDescribedFunctionTemplate()) {
8419         // C++ [temp.mem]p3:
8420         //  A member function template shall not be virtual.
8421         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8422              diag::err_virtual_member_function_template)
8423           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8424       } else {
8425         // Okay: Add virtual to the method.
8426         NewFD->setVirtualAsWritten(true);
8427       }
8428 
8429       if (getLangOpts().CPlusPlus14 &&
8430           NewFD->getReturnType()->isUndeducedType())
8431         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8432     }
8433 
8434     if (getLangOpts().CPlusPlus14 &&
8435         (NewFD->isDependentContext() ||
8436          (isFriend && CurContext->isDependentContext())) &&
8437         NewFD->getReturnType()->isUndeducedType()) {
8438       // If the function template is referenced directly (for instance, as a
8439       // member of the current instantiation), pretend it has a dependent type.
8440       // This is not really justified by the standard, but is the only sane
8441       // thing to do.
8442       // FIXME: For a friend function, we have not marked the function as being
8443       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8444       const FunctionProtoType *FPT =
8445           NewFD->getType()->castAs<FunctionProtoType>();
8446       QualType Result =
8447           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8448       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8449                                              FPT->getExtProtoInfo()));
8450     }
8451 
8452     // C++ [dcl.fct.spec]p3:
8453     //  The inline specifier shall not appear on a block scope function
8454     //  declaration.
8455     if (isInline && !NewFD->isInvalidDecl()) {
8456       if (CurContext->isFunctionOrMethod()) {
8457         // 'inline' is not allowed on block scope function declaration.
8458         Diag(D.getDeclSpec().getInlineSpecLoc(),
8459              diag::err_inline_declaration_block_scope) << Name
8460           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8461       }
8462     }
8463 
8464     // C++ [dcl.fct.spec]p6:
8465     //  The explicit specifier shall be used only in the declaration of a
8466     //  constructor or conversion function within its class definition;
8467     //  see 12.3.1 and 12.3.2.
8468     if (isExplicit && !NewFD->isInvalidDecl() &&
8469         !isa<CXXDeductionGuideDecl>(NewFD)) {
8470       if (!CurContext->isRecord()) {
8471         // 'explicit' was specified outside of the class.
8472         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8473              diag::err_explicit_out_of_class)
8474           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8475       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8476                  !isa<CXXConversionDecl>(NewFD)) {
8477         // 'explicit' was specified on a function that wasn't a constructor
8478         // or conversion function.
8479         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8480              diag::err_explicit_non_ctor_or_conv_function)
8481           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8482       }
8483     }
8484 
8485     if (isConstexpr) {
8486       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8487       // are implicitly inline.
8488       NewFD->setImplicitlyInline();
8489 
8490       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8491       // be either constructors or to return a literal type. Therefore,
8492       // destructors cannot be declared constexpr.
8493       if (isa<CXXDestructorDecl>(NewFD))
8494         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8495     }
8496 
8497     // If __module_private__ was specified, mark the function accordingly.
8498     if (D.getDeclSpec().isModulePrivateSpecified()) {
8499       if (isFunctionTemplateSpecialization) {
8500         SourceLocation ModulePrivateLoc
8501           = D.getDeclSpec().getModulePrivateSpecLoc();
8502         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8503           << 0
8504           << FixItHint::CreateRemoval(ModulePrivateLoc);
8505       } else {
8506         NewFD->setModulePrivate();
8507         if (FunctionTemplate)
8508           FunctionTemplate->setModulePrivate();
8509       }
8510     }
8511 
8512     if (isFriend) {
8513       if (FunctionTemplate) {
8514         FunctionTemplate->setObjectOfFriendDecl();
8515         FunctionTemplate->setAccess(AS_public);
8516       }
8517       NewFD->setObjectOfFriendDecl();
8518       NewFD->setAccess(AS_public);
8519     }
8520 
8521     // If a function is defined as defaulted or deleted, mark it as such now.
8522     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8523     // definition kind to FDK_Definition.
8524     switch (D.getFunctionDefinitionKind()) {
8525       case FDK_Declaration:
8526       case FDK_Definition:
8527         break;
8528 
8529       case FDK_Defaulted:
8530         NewFD->setDefaulted();
8531         break;
8532 
8533       case FDK_Deleted:
8534         NewFD->setDeletedAsWritten();
8535         break;
8536     }
8537 
8538     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8539         D.isFunctionDefinition()) {
8540       // C++ [class.mfct]p2:
8541       //   A member function may be defined (8.4) in its class definition, in
8542       //   which case it is an inline member function (7.1.2)
8543       NewFD->setImplicitlyInline();
8544     }
8545 
8546     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8547         !CurContext->isRecord()) {
8548       // C++ [class.static]p1:
8549       //   A data or function member of a class may be declared static
8550       //   in a class definition, in which case it is a static member of
8551       //   the class.
8552 
8553       // Complain about the 'static' specifier if it's on an out-of-line
8554       // member function definition.
8555       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8556            diag::err_static_out_of_line)
8557         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8558     }
8559 
8560     // C++11 [except.spec]p15:
8561     //   A deallocation function with no exception-specification is treated
8562     //   as if it were specified with noexcept(true).
8563     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8564     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8565          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8566         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8567       NewFD->setType(Context.getFunctionType(
8568           FPT->getReturnType(), FPT->getParamTypes(),
8569           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8570   }
8571 
8572   // Filter out previous declarations that don't match the scope.
8573   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8574                        D.getCXXScopeSpec().isNotEmpty() ||
8575                        isMemberSpecialization ||
8576                        isFunctionTemplateSpecialization);
8577 
8578   // Handle GNU asm-label extension (encoded as an attribute).
8579   if (Expr *E = (Expr*) D.getAsmLabel()) {
8580     // The parser guarantees this is a string.
8581     StringLiteral *SE = cast<StringLiteral>(E);
8582     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8583                                                 SE->getString(), 0));
8584   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8585     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8586       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8587     if (I != ExtnameUndeclaredIdentifiers.end()) {
8588       if (isDeclExternC(NewFD)) {
8589         NewFD->addAttr(I->second);
8590         ExtnameUndeclaredIdentifiers.erase(I);
8591       } else
8592         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8593             << /*Variable*/0 << NewFD;
8594     }
8595   }
8596 
8597   // Copy the parameter declarations from the declarator D to the function
8598   // declaration NewFD, if they are available.  First scavenge them into Params.
8599   SmallVector<ParmVarDecl*, 16> Params;
8600   unsigned FTIIdx;
8601   if (D.isFunctionDeclarator(FTIIdx)) {
8602     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8603 
8604     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8605     // function that takes no arguments, not a function that takes a
8606     // single void argument.
8607     // We let through "const void" here because Sema::GetTypeForDeclarator
8608     // already checks for that case.
8609     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8610       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8611         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8612         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8613         Param->setDeclContext(NewFD);
8614         Params.push_back(Param);
8615 
8616         if (Param->isInvalidDecl())
8617           NewFD->setInvalidDecl();
8618       }
8619     }
8620 
8621     if (!getLangOpts().CPlusPlus) {
8622       // In C, find all the tag declarations from the prototype and move them
8623       // into the function DeclContext. Remove them from the surrounding tag
8624       // injection context of the function, which is typically but not always
8625       // the TU.
8626       DeclContext *PrototypeTagContext =
8627           getTagInjectionContext(NewFD->getLexicalDeclContext());
8628       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8629         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8630 
8631         // We don't want to reparent enumerators. Look at their parent enum
8632         // instead.
8633         if (!TD) {
8634           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8635             TD = cast<EnumDecl>(ECD->getDeclContext());
8636         }
8637         if (!TD)
8638           continue;
8639         DeclContext *TagDC = TD->getLexicalDeclContext();
8640         if (!TagDC->containsDecl(TD))
8641           continue;
8642         TagDC->removeDecl(TD);
8643         TD->setDeclContext(NewFD);
8644         NewFD->addDecl(TD);
8645 
8646         // Preserve the lexical DeclContext if it is not the surrounding tag
8647         // injection context of the FD. In this example, the semantic context of
8648         // E will be f and the lexical context will be S, while both the
8649         // semantic and lexical contexts of S will be f:
8650         //   void f(struct S { enum E { a } f; } s);
8651         if (TagDC != PrototypeTagContext)
8652           TD->setLexicalDeclContext(TagDC);
8653       }
8654     }
8655   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8656     // When we're declaring a function with a typedef, typeof, etc as in the
8657     // following example, we'll need to synthesize (unnamed)
8658     // parameters for use in the declaration.
8659     //
8660     // @code
8661     // typedef void fn(int);
8662     // fn f;
8663     // @endcode
8664 
8665     // Synthesize a parameter for each argument type.
8666     for (const auto &AI : FT->param_types()) {
8667       ParmVarDecl *Param =
8668           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8669       Param->setScopeInfo(0, Params.size());
8670       Params.push_back(Param);
8671     }
8672   } else {
8673     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8674            "Should not need args for typedef of non-prototype fn");
8675   }
8676 
8677   // Finally, we know we have the right number of parameters, install them.
8678   NewFD->setParams(Params);
8679 
8680   if (D.getDeclSpec().isNoreturnSpecified())
8681     NewFD->addAttr(
8682         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8683                                        Context, 0));
8684 
8685   // Functions returning a variably modified type violate C99 6.7.5.2p2
8686   // because all functions have linkage.
8687   if (!NewFD->isInvalidDecl() &&
8688       NewFD->getReturnType()->isVariablyModifiedType()) {
8689     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8690     NewFD->setInvalidDecl();
8691   }
8692 
8693   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8694   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8695       !NewFD->hasAttr<SectionAttr>()) {
8696     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8697                                                  PragmaClangTextSection.SectionName,
8698                                                  PragmaClangTextSection.PragmaLocation));
8699   }
8700 
8701   // Apply an implicit SectionAttr if #pragma code_seg is active.
8702   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8703       !NewFD->hasAttr<SectionAttr>()) {
8704     NewFD->addAttr(
8705         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8706                                     CodeSegStack.CurrentValue->getString(),
8707                                     CodeSegStack.CurrentPragmaLocation));
8708     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8709                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8710                          ASTContext::PSF_Read,
8711                      NewFD))
8712       NewFD->dropAttr<SectionAttr>();
8713   }
8714 
8715   // Handle attributes.
8716   ProcessDeclAttributes(S, NewFD, D);
8717 
8718   if (getLangOpts().OpenCL) {
8719     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8720     // type declaration will generate a compilation error.
8721     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8722     if (AddressSpace != LangAS::Default) {
8723       Diag(NewFD->getLocation(),
8724            diag::err_opencl_return_value_with_address_space);
8725       NewFD->setInvalidDecl();
8726     }
8727   }
8728 
8729   if (!getLangOpts().CPlusPlus) {
8730     // Perform semantic checking on the function declaration.
8731     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8732       CheckMain(NewFD, D.getDeclSpec());
8733 
8734     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8735       CheckMSVCRTEntryPoint(NewFD);
8736 
8737     if (!NewFD->isInvalidDecl())
8738       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8739                                                   isMemberSpecialization));
8740     else if (!Previous.empty())
8741       // Recover gracefully from an invalid redeclaration.
8742       D.setRedeclaration(true);
8743     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8744             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8745            "previous declaration set still overloaded");
8746 
8747     // Diagnose no-prototype function declarations with calling conventions that
8748     // don't support variadic calls. Only do this in C and do it after merging
8749     // possibly prototyped redeclarations.
8750     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8751     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8752       CallingConv CC = FT->getExtInfo().getCC();
8753       if (!supportsVariadicCall(CC)) {
8754         // Windows system headers sometimes accidentally use stdcall without
8755         // (void) parameters, so we relax this to a warning.
8756         int DiagID =
8757             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8758         Diag(NewFD->getLocation(), DiagID)
8759             << FunctionType::getNameForCallConv(CC);
8760       }
8761     }
8762   } else {
8763     // C++11 [replacement.functions]p3:
8764     //  The program's definitions shall not be specified as inline.
8765     //
8766     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8767     //
8768     // Suppress the diagnostic if the function is __attribute__((used)), since
8769     // that forces an external definition to be emitted.
8770     if (D.getDeclSpec().isInlineSpecified() &&
8771         NewFD->isReplaceableGlobalAllocationFunction() &&
8772         !NewFD->hasAttr<UsedAttr>())
8773       Diag(D.getDeclSpec().getInlineSpecLoc(),
8774            diag::ext_operator_new_delete_declared_inline)
8775         << NewFD->getDeclName();
8776 
8777     // If the declarator is a template-id, translate the parser's template
8778     // argument list into our AST format.
8779     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8780       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8781       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8782       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8783       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8784                                          TemplateId->NumArgs);
8785       translateTemplateArguments(TemplateArgsPtr,
8786                                  TemplateArgs);
8787 
8788       HasExplicitTemplateArgs = true;
8789 
8790       if (NewFD->isInvalidDecl()) {
8791         HasExplicitTemplateArgs = false;
8792       } else if (FunctionTemplate) {
8793         // Function template with explicit template arguments.
8794         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8795           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8796 
8797         HasExplicitTemplateArgs = false;
8798       } else {
8799         assert((isFunctionTemplateSpecialization ||
8800                 D.getDeclSpec().isFriendSpecified()) &&
8801                "should have a 'template<>' for this decl");
8802         // "friend void foo<>(int);" is an implicit specialization decl.
8803         isFunctionTemplateSpecialization = true;
8804       }
8805     } else if (isFriend && isFunctionTemplateSpecialization) {
8806       // This combination is only possible in a recovery case;  the user
8807       // wrote something like:
8808       //   template <> friend void foo(int);
8809       // which we're recovering from as if the user had written:
8810       //   friend void foo<>(int);
8811       // Go ahead and fake up a template id.
8812       HasExplicitTemplateArgs = true;
8813       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8814       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8815     }
8816 
8817     // We do not add HD attributes to specializations here because
8818     // they may have different constexpr-ness compared to their
8819     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8820     // may end up with different effective targets. Instead, a
8821     // specialization inherits its target attributes from its template
8822     // in the CheckFunctionTemplateSpecialization() call below.
8823     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8824       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8825 
8826     // If it's a friend (and only if it's a friend), it's possible
8827     // that either the specialized function type or the specialized
8828     // template is dependent, and therefore matching will fail.  In
8829     // this case, don't check the specialization yet.
8830     bool InstantiationDependent = false;
8831     if (isFunctionTemplateSpecialization && isFriend &&
8832         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8833          TemplateSpecializationType::anyDependentTemplateArguments(
8834             TemplateArgs,
8835             InstantiationDependent))) {
8836       assert(HasExplicitTemplateArgs &&
8837              "friend function specialization without template args");
8838       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8839                                                        Previous))
8840         NewFD->setInvalidDecl();
8841     } else if (isFunctionTemplateSpecialization) {
8842       if (CurContext->isDependentContext() && CurContext->isRecord()
8843           && !isFriend) {
8844         isDependentClassScopeExplicitSpecialization = true;
8845       } else if (!NewFD->isInvalidDecl() &&
8846                  CheckFunctionTemplateSpecialization(
8847                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8848                      Previous))
8849         NewFD->setInvalidDecl();
8850 
8851       // C++ [dcl.stc]p1:
8852       //   A storage-class-specifier shall not be specified in an explicit
8853       //   specialization (14.7.3)
8854       FunctionTemplateSpecializationInfo *Info =
8855           NewFD->getTemplateSpecializationInfo();
8856       if (Info && SC != SC_None) {
8857         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8858           Diag(NewFD->getLocation(),
8859                diag::err_explicit_specialization_inconsistent_storage_class)
8860             << SC
8861             << FixItHint::CreateRemoval(
8862                                       D.getDeclSpec().getStorageClassSpecLoc());
8863 
8864         else
8865           Diag(NewFD->getLocation(),
8866                diag::ext_explicit_specialization_storage_class)
8867             << FixItHint::CreateRemoval(
8868                                       D.getDeclSpec().getStorageClassSpecLoc());
8869       }
8870     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8871       if (CheckMemberSpecialization(NewFD, Previous))
8872           NewFD->setInvalidDecl();
8873     }
8874 
8875     // Perform semantic checking on the function declaration.
8876     if (!isDependentClassScopeExplicitSpecialization) {
8877       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8878         CheckMain(NewFD, D.getDeclSpec());
8879 
8880       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8881         CheckMSVCRTEntryPoint(NewFD);
8882 
8883       if (!NewFD->isInvalidDecl())
8884         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8885                                                     isMemberSpecialization));
8886       else if (!Previous.empty())
8887         // Recover gracefully from an invalid redeclaration.
8888         D.setRedeclaration(true);
8889     }
8890 
8891     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8892             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8893            "previous declaration set still overloaded");
8894 
8895     NamedDecl *PrincipalDecl = (FunctionTemplate
8896                                 ? cast<NamedDecl>(FunctionTemplate)
8897                                 : NewFD);
8898 
8899     if (isFriend && NewFD->getPreviousDecl()) {
8900       AccessSpecifier Access = AS_public;
8901       if (!NewFD->isInvalidDecl())
8902         Access = NewFD->getPreviousDecl()->getAccess();
8903 
8904       NewFD->setAccess(Access);
8905       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8906     }
8907 
8908     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8909         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8910       PrincipalDecl->setNonMemberOperator();
8911 
8912     // If we have a function template, check the template parameter
8913     // list. This will check and merge default template arguments.
8914     if (FunctionTemplate) {
8915       FunctionTemplateDecl *PrevTemplate =
8916                                      FunctionTemplate->getPreviousDecl();
8917       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8918                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8919                                     : nullptr,
8920                             D.getDeclSpec().isFriendSpecified()
8921                               ? (D.isFunctionDefinition()
8922                                    ? TPC_FriendFunctionTemplateDefinition
8923                                    : TPC_FriendFunctionTemplate)
8924                               : (D.getCXXScopeSpec().isSet() &&
8925                                  DC && DC->isRecord() &&
8926                                  DC->isDependentContext())
8927                                   ? TPC_ClassTemplateMember
8928                                   : TPC_FunctionTemplate);
8929     }
8930 
8931     if (NewFD->isInvalidDecl()) {
8932       // Ignore all the rest of this.
8933     } else if (!D.isRedeclaration()) {
8934       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8935                                        AddToScope };
8936       // Fake up an access specifier if it's supposed to be a class member.
8937       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8938         NewFD->setAccess(AS_public);
8939 
8940       // Qualified decls generally require a previous declaration.
8941       if (D.getCXXScopeSpec().isSet()) {
8942         // ...with the major exception of templated-scope or
8943         // dependent-scope friend declarations.
8944 
8945         // TODO: we currently also suppress this check in dependent
8946         // contexts because (1) the parameter depth will be off when
8947         // matching friend templates and (2) we might actually be
8948         // selecting a friend based on a dependent factor.  But there
8949         // are situations where these conditions don't apply and we
8950         // can actually do this check immediately.
8951         if (isFriend &&
8952             (TemplateParamLists.size() ||
8953              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8954              CurContext->isDependentContext())) {
8955           // ignore these
8956         } else {
8957           // The user tried to provide an out-of-line definition for a
8958           // function that is a member of a class or namespace, but there
8959           // was no such member function declared (C++ [class.mfct]p2,
8960           // C++ [namespace.memdef]p2). For example:
8961           //
8962           // class X {
8963           //   void f() const;
8964           // };
8965           //
8966           // void X::f() { } // ill-formed
8967           //
8968           // Complain about this problem, and attempt to suggest close
8969           // matches (e.g., those that differ only in cv-qualifiers and
8970           // whether the parameter types are references).
8971 
8972           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8973                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8974             AddToScope = ExtraArgs.AddToScope;
8975             return Result;
8976           }
8977         }
8978 
8979         // Unqualified local friend declarations are required to resolve
8980         // to something.
8981       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8982         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8983                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8984           AddToScope = ExtraArgs.AddToScope;
8985           return Result;
8986         }
8987       }
8988     } else if (!D.isFunctionDefinition() &&
8989                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8990                !isFriend && !isFunctionTemplateSpecialization &&
8991                !isMemberSpecialization) {
8992       // An out-of-line member function declaration must also be a
8993       // definition (C++ [class.mfct]p2).
8994       // Note that this is not the case for explicit specializations of
8995       // function templates or member functions of class templates, per
8996       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8997       // extension for compatibility with old SWIG code which likes to
8998       // generate them.
8999       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9000         << D.getCXXScopeSpec().getRange();
9001     }
9002   }
9003 
9004   ProcessPragmaWeak(S, NewFD);
9005   checkAttributesAfterMerging(*this, *NewFD);
9006 
9007   AddKnownFunctionAttributes(NewFD);
9008 
9009   if (NewFD->hasAttr<OverloadableAttr>() &&
9010       !NewFD->getType()->getAs<FunctionProtoType>()) {
9011     Diag(NewFD->getLocation(),
9012          diag::err_attribute_overloadable_no_prototype)
9013       << NewFD;
9014 
9015     // Turn this into a variadic function with no parameters.
9016     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9017     FunctionProtoType::ExtProtoInfo EPI(
9018         Context.getDefaultCallingConvention(true, false));
9019     EPI.Variadic = true;
9020     EPI.ExtInfo = FT->getExtInfo();
9021 
9022     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9023     NewFD->setType(R);
9024   }
9025 
9026   // If there's a #pragma GCC visibility in scope, and this isn't a class
9027   // member, set the visibility of this function.
9028   if (!DC->isRecord() && NewFD->isExternallyVisible())
9029     AddPushedVisibilityAttribute(NewFD);
9030 
9031   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9032   // marking the function.
9033   AddCFAuditedAttribute(NewFD);
9034 
9035   // If this is a function definition, check if we have to apply optnone due to
9036   // a pragma.
9037   if(D.isFunctionDefinition())
9038     AddRangeBasedOptnone(NewFD);
9039 
9040   // If this is the first declaration of an extern C variable, update
9041   // the map of such variables.
9042   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9043       isIncompleteDeclExternC(*this, NewFD))
9044     RegisterLocallyScopedExternCDecl(NewFD, S);
9045 
9046   // Set this FunctionDecl's range up to the right paren.
9047   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9048 
9049   if (D.isRedeclaration() && !Previous.empty()) {
9050     NamedDecl *Prev = Previous.getRepresentativeDecl();
9051     checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9052                                    isMemberSpecialization ||
9053                                        isFunctionTemplateSpecialization,
9054                                    D.isFunctionDefinition());
9055   }
9056 
9057   if (getLangOpts().CUDA) {
9058     IdentifierInfo *II = NewFD->getIdentifier();
9059     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9060         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9061       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9062         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9063 
9064       Context.setcudaConfigureCallDecl(NewFD);
9065     }
9066 
9067     // Variadic functions, other than a *declaration* of printf, are not allowed
9068     // in device-side CUDA code, unless someone passed
9069     // -fcuda-allow-variadic-functions.
9070     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9071         (NewFD->hasAttr<CUDADeviceAttr>() ||
9072          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9073         !(II && II->isStr("printf") && NewFD->isExternC() &&
9074           !D.isFunctionDefinition())) {
9075       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9076     }
9077   }
9078 
9079   MarkUnusedFileScopedDecl(NewFD);
9080 
9081   if (getLangOpts().CPlusPlus) {
9082     if (FunctionTemplate) {
9083       if (NewFD->isInvalidDecl())
9084         FunctionTemplate->setInvalidDecl();
9085       return FunctionTemplate;
9086     }
9087 
9088     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9089       CompleteMemberSpecialization(NewFD, Previous);
9090   }
9091 
9092   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9093     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9094     if ((getLangOpts().OpenCLVersion >= 120)
9095         && (SC == SC_Static)) {
9096       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9097       D.setInvalidType();
9098     }
9099 
9100     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9101     if (!NewFD->getReturnType()->isVoidType()) {
9102       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9103       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9104           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9105                                 : FixItHint());
9106       D.setInvalidType();
9107     }
9108 
9109     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9110     for (auto Param : NewFD->parameters())
9111       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9112   }
9113   for (const ParmVarDecl *Param : NewFD->parameters()) {
9114     QualType PT = Param->getType();
9115 
9116     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9117     // types.
9118     if (getLangOpts().OpenCLVersion >= 200) {
9119       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9120         QualType ElemTy = PipeTy->getElementType();
9121           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9122             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9123             D.setInvalidType();
9124           }
9125       }
9126     }
9127   }
9128 
9129   // Here we have an function template explicit specialization at class scope.
9130   // The actual specialization will be postponed to template instatiation
9131   // time via the ClassScopeFunctionSpecializationDecl node.
9132   if (isDependentClassScopeExplicitSpecialization) {
9133     ClassScopeFunctionSpecializationDecl *NewSpec =
9134                          ClassScopeFunctionSpecializationDecl::Create(
9135                                 Context, CurContext, NewFD->getLocation(),
9136                                 cast<CXXMethodDecl>(NewFD),
9137                                 HasExplicitTemplateArgs, TemplateArgs);
9138     CurContext->addDecl(NewSpec);
9139     AddToScope = false;
9140   }
9141 
9142   // Diagnose availability attributes. Availability cannot be used on functions
9143   // that are run during load/unload.
9144   if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9145     if (NewFD->hasAttr<ConstructorAttr>()) {
9146       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9147           << 1;
9148       NewFD->dropAttr<AvailabilityAttr>();
9149     }
9150     if (NewFD->hasAttr<DestructorAttr>()) {
9151       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9152           << 2;
9153       NewFD->dropAttr<AvailabilityAttr>();
9154     }
9155   }
9156 
9157   return NewFD;
9158 }
9159 
9160 /// \brief Checks if the new declaration declared in dependent context must be
9161 /// put in the same redeclaration chain as the specified declaration.
9162 ///
9163 /// \param D Declaration that is checked.
9164 /// \param PrevDecl Previous declaration found with proper lookup method for the
9165 ///                 same declaration name.
9166 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9167 ///          belongs to.
9168 ///
9169 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9170   // Any declarations should be put into redeclaration chains except for
9171   // friend declaration in a dependent context that names a function in
9172   // namespace scope.
9173   //
9174   // This allows to compile code like:
9175   //
9176   //       void func();
9177   //       template<typename T> class C1 { friend void func() { } };
9178   //       template<typename T> class C2 { friend void func() { } };
9179   //
9180   // This code snippet is a valid code unless both templates are instantiated.
9181   return !(D->getLexicalDeclContext()->isDependentContext() &&
9182            D->getDeclContext()->isFileContext() &&
9183            D->getFriendObjectKind() != Decl::FOK_None);
9184 }
9185 
9186 /// \brief Check the target attribute of the function for MultiVersion
9187 /// validity.
9188 ///
9189 /// Returns true if there was an error, false otherwise.
9190 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9191   const auto *TA = FD->getAttr<TargetAttr>();
9192   assert(TA && "MultiVersion Candidate requires a target attribute");
9193   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9194   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9195   enum ErrType { Feature = 0, Architecture = 1 };
9196 
9197   if (!ParseInfo.Architecture.empty() &&
9198       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9199     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9200         << Architecture << ParseInfo.Architecture;
9201     return true;
9202   }
9203 
9204   for (const auto &Feat : ParseInfo.Features) {
9205     auto BareFeat = StringRef{Feat}.substr(1);
9206     if (Feat[0] == '-') {
9207       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9208           << Feature << ("no-" + BareFeat).str();
9209       return true;
9210     }
9211 
9212     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9213         !TargetInfo.isValidFeatureName(BareFeat)) {
9214       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9215           << Feature << BareFeat;
9216       return true;
9217     }
9218   }
9219   return false;
9220 }
9221 
9222 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9223                                              const FunctionDecl *NewFD,
9224                                              bool CausesMV) {
9225   enum DoesntSupport {
9226     FuncTemplates = 0,
9227     VirtFuncs = 1,
9228     DeducedReturn = 2,
9229     Constructors = 3,
9230     Destructors = 4,
9231     DeletedFuncs = 5,
9232     DefaultedFuncs = 6
9233   };
9234   enum Different {
9235     CallingConv = 0,
9236     ReturnType = 1,
9237     ConstexprSpec = 2,
9238     InlineSpec = 3,
9239     StorageClass = 4,
9240     Linkage = 5
9241   };
9242 
9243   // For now, disallow all other attributes.  These should be opt-in, but
9244   // an analysis of all of them is a future FIXME.
9245   if (CausesMV && OldFD &&
9246       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9247     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs);
9248     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9249     return true;
9250   }
9251 
9252   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9253     return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs);
9254 
9255   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9256     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9257            << FuncTemplates;
9258 
9259   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9260     if (NewCXXFD->isVirtual())
9261       return S.Diag(NewCXXFD->getLocation(),
9262                     diag::err_multiversion_doesnt_support)
9263              << VirtFuncs;
9264 
9265     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9266       return S.Diag(NewCXXCtor->getLocation(),
9267                     diag::err_multiversion_doesnt_support)
9268              << Constructors;
9269 
9270     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9271       return S.Diag(NewCXXDtor->getLocation(),
9272                     diag::err_multiversion_doesnt_support)
9273              << Destructors;
9274   }
9275 
9276   if (NewFD->isDeleted())
9277     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9278            << DeletedFuncs;
9279 
9280   if (NewFD->isDefaulted())
9281     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9282            << DefaultedFuncs;
9283 
9284   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9285   const auto *NewType = cast<FunctionType>(NewQType);
9286   QualType NewReturnType = NewType->getReturnType();
9287 
9288   if (NewReturnType->isUndeducedType())
9289     return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9290            << DeducedReturn;
9291 
9292   // Only allow transition to MultiVersion if it hasn't been used.
9293   if (OldFD && CausesMV && OldFD->isUsed(false))
9294     return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9295 
9296   // Ensure the return type is identical.
9297   if (OldFD) {
9298     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9299     const auto *OldType = cast<FunctionType>(OldQType);
9300     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9301     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9302 
9303     if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9304       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9305              << CallingConv;
9306 
9307     QualType OldReturnType = OldType->getReturnType();
9308 
9309     if (OldReturnType != NewReturnType)
9310       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9311              << ReturnType;
9312 
9313     if (OldFD->isConstexpr() != NewFD->isConstexpr())
9314       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9315              << ConstexprSpec;
9316 
9317     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9318       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9319              << InlineSpec;
9320 
9321     if (OldFD->getStorageClass() != NewFD->getStorageClass())
9322       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9323              << StorageClass;
9324 
9325     if (OldFD->isExternC() != NewFD->isExternC())
9326       return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9327              << Linkage;
9328 
9329     if (S.CheckEquivalentExceptionSpec(
9330             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9331             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9332       return true;
9333   }
9334   return false;
9335 }
9336 
9337 /// \brief Check the validity of a mulitversion function declaration.
9338 /// Also sets the multiversion'ness' of the function itself.
9339 ///
9340 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9341 ///
9342 /// Returns true if there was an error, false otherwise.
9343 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9344                                       bool &Redeclaration, NamedDecl *&OldDecl,
9345                                       bool &MergeTypeWithPrevious,
9346                                       LookupResult &Previous) {
9347   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9348   if (NewFD->isMain()) {
9349     if (NewTA && NewTA->isDefaultVersion()) {
9350       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9351       NewFD->setInvalidDecl();
9352       return true;
9353     }
9354     return false;
9355   }
9356 
9357   // If there is no matching previous decl, only 'default' can
9358   // cause MultiVersioning.
9359   if (!OldDecl) {
9360     if (NewTA && NewTA->isDefaultVersion()) {
9361       if (!NewFD->getType()->getAs<FunctionProtoType>()) {
9362         S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9363         NewFD->setInvalidDecl();
9364         return true;
9365       }
9366       if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) {
9367         NewFD->setInvalidDecl();
9368         return true;
9369       }
9370       if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9371         S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9372         NewFD->setInvalidDecl();
9373         return true;
9374       }
9375 
9376       NewFD->setIsMultiVersion();
9377     }
9378     return false;
9379   }
9380 
9381   if (OldDecl->getDeclContext()->getRedeclContext() !=
9382       NewFD->getDeclContext()->getRedeclContext())
9383     return false;
9384 
9385   FunctionDecl *OldFD = OldDecl->getAsFunction();
9386   // Unresolved 'using' statements (the other way OldDecl can be not a function)
9387   // likely cannot cause a problem here.
9388   if (!OldFD)
9389     return false;
9390 
9391   if (!OldFD->isMultiVersion() && !NewTA)
9392     return false;
9393 
9394   if (OldFD->isMultiVersion() && !NewTA) {
9395     S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl);
9396     NewFD->setInvalidDecl();
9397     return true;
9398   }
9399 
9400   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9401   // Sort order doesn't matter, it just needs to be consistent.
9402   llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9403 
9404   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9405   if (!OldFD->isMultiVersion()) {
9406     // If the old decl is NOT MultiVersioned yet, and we don't cause that
9407     // to change, this is a simple redeclaration.
9408     if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9409       return false;
9410 
9411     // Otherwise, this decl causes MultiVersioning.
9412     if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9413       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9414       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9415       NewFD->setInvalidDecl();
9416       return true;
9417     }
9418 
9419     if (!OldFD->getType()->getAs<FunctionProtoType>()) {
9420       S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9421       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9422       NewFD->setInvalidDecl();
9423       return true;
9424     }
9425 
9426     if (CheckMultiVersionValue(S, NewFD)) {
9427       NewFD->setInvalidDecl();
9428       return true;
9429     }
9430 
9431     if (CheckMultiVersionValue(S, OldFD)) {
9432       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9433       NewFD->setInvalidDecl();
9434       return true;
9435     }
9436 
9437     TargetAttr::ParsedTargetAttr OldParsed =
9438         OldTA->parse(std::less<std::string>());
9439 
9440     if (OldParsed == NewParsed) {
9441       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9442       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9443       NewFD->setInvalidDecl();
9444       return true;
9445     }
9446 
9447     for (const auto *FD : OldFD->redecls()) {
9448       const auto *CurTA = FD->getAttr<TargetAttr>();
9449       if (!CurTA || CurTA->isInherited()) {
9450         S.Diag(FD->getLocation(), diag::err_target_required_in_redecl);
9451         S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9452         NewFD->setInvalidDecl();
9453         return true;
9454       }
9455     }
9456 
9457     if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) {
9458       NewFD->setInvalidDecl();
9459       return true;
9460     }
9461 
9462     OldFD->setIsMultiVersion();
9463     NewFD->setIsMultiVersion();
9464     Redeclaration = false;
9465     MergeTypeWithPrevious = false;
9466     OldDecl = nullptr;
9467     Previous.clear();
9468     return false;
9469   }
9470 
9471   bool UseMemberUsingDeclRules =
9472       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9473 
9474   // Next, check ALL non-overloads to see if this is a redeclaration of a
9475   // previous member of the MultiVersion set.
9476   for (NamedDecl *ND : Previous) {
9477     FunctionDecl *CurFD = ND->getAsFunction();
9478     if (!CurFD)
9479       continue;
9480     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9481       continue;
9482 
9483     const auto *CurTA = CurFD->getAttr<TargetAttr>();
9484     if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9485       NewFD->setIsMultiVersion();
9486       Redeclaration = true;
9487       OldDecl = ND;
9488       return false;
9489     }
9490 
9491     TargetAttr::ParsedTargetAttr CurParsed =
9492         CurTA->parse(std::less<std::string>());
9493 
9494     if (CurParsed == NewParsed) {
9495       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9496       S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9497       NewFD->setInvalidDecl();
9498       return true;
9499     }
9500   }
9501 
9502   // Else, this is simply a non-redecl case.
9503   if (CheckMultiVersionValue(S, NewFD)) {
9504     NewFD->setInvalidDecl();
9505     return true;
9506   }
9507 
9508   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) {
9509     NewFD->setInvalidDecl();
9510     return true;
9511   }
9512 
9513   NewFD->setIsMultiVersion();
9514   Redeclaration = false;
9515   MergeTypeWithPrevious = false;
9516   OldDecl = nullptr;
9517   Previous.clear();
9518   return false;
9519 }
9520 
9521 /// \brief Perform semantic checking of a new function declaration.
9522 ///
9523 /// Performs semantic analysis of the new function declaration
9524 /// NewFD. This routine performs all semantic checking that does not
9525 /// require the actual declarator involved in the declaration, and is
9526 /// used both for the declaration of functions as they are parsed
9527 /// (called via ActOnDeclarator) and for the declaration of functions
9528 /// that have been instantiated via C++ template instantiation (called
9529 /// via InstantiateDecl).
9530 ///
9531 /// \param IsMemberSpecialization whether this new function declaration is
9532 /// a member specialization (that replaces any definition provided by the
9533 /// previous declaration).
9534 ///
9535 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9536 ///
9537 /// \returns true if the function declaration is a redeclaration.
9538 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9539                                     LookupResult &Previous,
9540                                     bool IsMemberSpecialization) {
9541   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9542          "Variably modified return types are not handled here");
9543 
9544   // Determine whether the type of this function should be merged with
9545   // a previous visible declaration. This never happens for functions in C++,
9546   // and always happens in C if the previous declaration was visible.
9547   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9548                                !Previous.isShadowed();
9549 
9550   bool Redeclaration = false;
9551   NamedDecl *OldDecl = nullptr;
9552   bool MayNeedOverloadableChecks = false;
9553 
9554   // Merge or overload the declaration with an existing declaration of
9555   // the same name, if appropriate.
9556   if (!Previous.empty()) {
9557     // Determine whether NewFD is an overload of PrevDecl or
9558     // a declaration that requires merging. If it's an overload,
9559     // there's no more work to do here; we'll just add the new
9560     // function to the scope.
9561     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9562       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9563       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9564         Redeclaration = true;
9565         OldDecl = Candidate;
9566       }
9567     } else {
9568       MayNeedOverloadableChecks = true;
9569       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9570                             /*NewIsUsingDecl*/ false)) {
9571       case Ovl_Match:
9572         Redeclaration = true;
9573         break;
9574 
9575       case Ovl_NonFunction:
9576         Redeclaration = true;
9577         break;
9578 
9579       case Ovl_Overload:
9580         Redeclaration = false;
9581         break;
9582       }
9583     }
9584   }
9585 
9586   // Check for a previous extern "C" declaration with this name.
9587   if (!Redeclaration &&
9588       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9589     if (!Previous.empty()) {
9590       // This is an extern "C" declaration with the same name as a previous
9591       // declaration, and thus redeclares that entity...
9592       Redeclaration = true;
9593       OldDecl = Previous.getFoundDecl();
9594       MergeTypeWithPrevious = false;
9595 
9596       // ... except in the presence of __attribute__((overloadable)).
9597       if (OldDecl->hasAttr<OverloadableAttr>() ||
9598           NewFD->hasAttr<OverloadableAttr>()) {
9599         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9600           MayNeedOverloadableChecks = true;
9601           Redeclaration = false;
9602           OldDecl = nullptr;
9603         }
9604       }
9605     }
9606   }
9607 
9608   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9609                                 MergeTypeWithPrevious, Previous))
9610     return Redeclaration;
9611 
9612   // C++11 [dcl.constexpr]p8:
9613   //   A constexpr specifier for a non-static member function that is not
9614   //   a constructor declares that member function to be const.
9615   //
9616   // This needs to be delayed until we know whether this is an out-of-line
9617   // definition of a static member function.
9618   //
9619   // This rule is not present in C++1y, so we produce a backwards
9620   // compatibility warning whenever it happens in C++11.
9621   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9622   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9623       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9624       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9625     CXXMethodDecl *OldMD = nullptr;
9626     if (OldDecl)
9627       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9628     if (!OldMD || !OldMD->isStatic()) {
9629       const FunctionProtoType *FPT =
9630         MD->getType()->castAs<FunctionProtoType>();
9631       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9632       EPI.TypeQuals |= Qualifiers::Const;
9633       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9634                                           FPT->getParamTypes(), EPI));
9635 
9636       // Warn that we did this, if we're not performing template instantiation.
9637       // In that case, we'll have warned already when the template was defined.
9638       if (!inTemplateInstantiation()) {
9639         SourceLocation AddConstLoc;
9640         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9641                 .IgnoreParens().getAs<FunctionTypeLoc>())
9642           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9643 
9644         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9645           << FixItHint::CreateInsertion(AddConstLoc, " const");
9646       }
9647     }
9648   }
9649 
9650   if (Redeclaration) {
9651     // NewFD and OldDecl represent declarations that need to be
9652     // merged.
9653     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9654       NewFD->setInvalidDecl();
9655       return Redeclaration;
9656     }
9657 
9658     Previous.clear();
9659     Previous.addDecl(OldDecl);
9660 
9661     if (FunctionTemplateDecl *OldTemplateDecl =
9662             dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9663       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
9664       NewFD->setPreviousDeclaration(OldFD);
9665       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9666       FunctionTemplateDecl *NewTemplateDecl
9667         = NewFD->getDescribedFunctionTemplate();
9668       assert(NewTemplateDecl && "Template/non-template mismatch");
9669       if (NewFD->isCXXClassMember()) {
9670         NewFD->setAccess(OldTemplateDecl->getAccess());
9671         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9672       }
9673 
9674       // If this is an explicit specialization of a member that is a function
9675       // template, mark it as a member specialization.
9676       if (IsMemberSpecialization &&
9677           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9678         NewTemplateDecl->setMemberSpecialization();
9679         assert(OldTemplateDecl->isMemberSpecialization());
9680         // Explicit specializations of a member template do not inherit deleted
9681         // status from the parent member template that they are specializing.
9682         if (OldFD->isDeleted()) {
9683           // FIXME: This assert will not hold in the presence of modules.
9684           assert(OldFD->getCanonicalDecl() == OldFD);
9685           // FIXME: We need an update record for this AST mutation.
9686           OldFD->setDeletedAsWritten(false);
9687         }
9688       }
9689 
9690     } else {
9691       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9692         auto *OldFD = cast<FunctionDecl>(OldDecl);
9693         // This needs to happen first so that 'inline' propagates.
9694         NewFD->setPreviousDeclaration(OldFD);
9695         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9696         if (NewFD->isCXXClassMember())
9697           NewFD->setAccess(OldFD->getAccess());
9698       }
9699     }
9700   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9701              !NewFD->getAttr<OverloadableAttr>()) {
9702     assert((Previous.empty() ||
9703             llvm::any_of(Previous,
9704                          [](const NamedDecl *ND) {
9705                            return ND->hasAttr<OverloadableAttr>();
9706                          })) &&
9707            "Non-redecls shouldn't happen without overloadable present");
9708 
9709     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9710       const auto *FD = dyn_cast<FunctionDecl>(ND);
9711       return FD && !FD->hasAttr<OverloadableAttr>();
9712     });
9713 
9714     if (OtherUnmarkedIter != Previous.end()) {
9715       Diag(NewFD->getLocation(),
9716            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9717       Diag((*OtherUnmarkedIter)->getLocation(),
9718            diag::note_attribute_overloadable_prev_overload)
9719           << false;
9720 
9721       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9722     }
9723   }
9724 
9725   // Semantic checking for this function declaration (in isolation).
9726 
9727   if (getLangOpts().CPlusPlus) {
9728     // C++-specific checks.
9729     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9730       CheckConstructor(Constructor);
9731     } else if (CXXDestructorDecl *Destructor =
9732                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9733       CXXRecordDecl *Record = Destructor->getParent();
9734       QualType ClassType = Context.getTypeDeclType(Record);
9735 
9736       // FIXME: Shouldn't we be able to perform this check even when the class
9737       // type is dependent? Both gcc and edg can handle that.
9738       if (!ClassType->isDependentType()) {
9739         DeclarationName Name
9740           = Context.DeclarationNames.getCXXDestructorName(
9741                                         Context.getCanonicalType(ClassType));
9742         if (NewFD->getDeclName() != Name) {
9743           Diag(NewFD->getLocation(), diag::err_destructor_name);
9744           NewFD->setInvalidDecl();
9745           return Redeclaration;
9746         }
9747       }
9748     } else if (CXXConversionDecl *Conversion
9749                = dyn_cast<CXXConversionDecl>(NewFD)) {
9750       ActOnConversionDeclarator(Conversion);
9751     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9752       if (auto *TD = Guide->getDescribedFunctionTemplate())
9753         CheckDeductionGuideTemplate(TD);
9754 
9755       // A deduction guide is not on the list of entities that can be
9756       // explicitly specialized.
9757       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9758         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9759             << /*explicit specialization*/ 1;
9760     }
9761 
9762     // Find any virtual functions that this function overrides.
9763     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9764       if (!Method->isFunctionTemplateSpecialization() &&
9765           !Method->getDescribedFunctionTemplate() &&
9766           Method->isCanonicalDecl()) {
9767         if (AddOverriddenMethods(Method->getParent(), Method)) {
9768           // If the function was marked as "static", we have a problem.
9769           if (NewFD->getStorageClass() == SC_Static) {
9770             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9771           }
9772         }
9773       }
9774 
9775       if (Method->isStatic())
9776         checkThisInStaticMemberFunctionType(Method);
9777     }
9778 
9779     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9780     if (NewFD->isOverloadedOperator() &&
9781         CheckOverloadedOperatorDeclaration(NewFD)) {
9782       NewFD->setInvalidDecl();
9783       return Redeclaration;
9784     }
9785 
9786     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9787     if (NewFD->getLiteralIdentifier() &&
9788         CheckLiteralOperatorDeclaration(NewFD)) {
9789       NewFD->setInvalidDecl();
9790       return Redeclaration;
9791     }
9792 
9793     // In C++, check default arguments now that we have merged decls. Unless
9794     // the lexical context is the class, because in this case this is done
9795     // during delayed parsing anyway.
9796     if (!CurContext->isRecord())
9797       CheckCXXDefaultArguments(NewFD);
9798 
9799     // If this function declares a builtin function, check the type of this
9800     // declaration against the expected type for the builtin.
9801     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9802       ASTContext::GetBuiltinTypeError Error;
9803       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9804       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9805       // If the type of the builtin differs only in its exception
9806       // specification, that's OK.
9807       // FIXME: If the types do differ in this way, it would be better to
9808       // retain the 'noexcept' form of the type.
9809       if (!T.isNull() &&
9810           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9811                                                             NewFD->getType()))
9812         // The type of this function differs from the type of the builtin,
9813         // so forget about the builtin entirely.
9814         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9815     }
9816 
9817     // If this function is declared as being extern "C", then check to see if
9818     // the function returns a UDT (class, struct, or union type) that is not C
9819     // compatible, and if it does, warn the user.
9820     // But, issue any diagnostic on the first declaration only.
9821     if (Previous.empty() && NewFD->isExternC()) {
9822       QualType R = NewFD->getReturnType();
9823       if (R->isIncompleteType() && !R->isVoidType())
9824         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9825             << NewFD << R;
9826       else if (!R.isPODType(Context) && !R->isVoidType() &&
9827                !R->isObjCObjectPointerType())
9828         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9829     }
9830 
9831     // C++1z [dcl.fct]p6:
9832     //   [...] whether the function has a non-throwing exception-specification
9833     //   [is] part of the function type
9834     //
9835     // This results in an ABI break between C++14 and C++17 for functions whose
9836     // declared type includes an exception-specification in a parameter or
9837     // return type. (Exception specifications on the function itself are OK in
9838     // most cases, and exception specifications are not permitted in most other
9839     // contexts where they could make it into a mangling.)
9840     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
9841       auto HasNoexcept = [&](QualType T) -> bool {
9842         // Strip off declarator chunks that could be between us and a function
9843         // type. We don't need to look far, exception specifications are very
9844         // restricted prior to C++17.
9845         if (auto *RT = T->getAs<ReferenceType>())
9846           T = RT->getPointeeType();
9847         else if (T->isAnyPointerType())
9848           T = T->getPointeeType();
9849         else if (auto *MPT = T->getAs<MemberPointerType>())
9850           T = MPT->getPointeeType();
9851         if (auto *FPT = T->getAs<FunctionProtoType>())
9852           if (FPT->isNothrow(Context))
9853             return true;
9854         return false;
9855       };
9856 
9857       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9858       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9859       for (QualType T : FPT->param_types())
9860         AnyNoexcept |= HasNoexcept(T);
9861       if (AnyNoexcept)
9862         Diag(NewFD->getLocation(),
9863              diag::warn_cxx17_compat_exception_spec_in_signature)
9864             << NewFD;
9865     }
9866 
9867     if (!Redeclaration && LangOpts.CUDA)
9868       checkCUDATargetOverload(NewFD, Previous);
9869   }
9870   return Redeclaration;
9871 }
9872 
9873 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9874   // C++11 [basic.start.main]p3:
9875   //   A program that [...] declares main to be inline, static or
9876   //   constexpr is ill-formed.
9877   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9878   //   appear in a declaration of main.
9879   // static main is not an error under C99, but we should warn about it.
9880   // We accept _Noreturn main as an extension.
9881   if (FD->getStorageClass() == SC_Static)
9882     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9883          ? diag::err_static_main : diag::warn_static_main)
9884       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9885   if (FD->isInlineSpecified())
9886     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9887       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9888   if (DS.isNoreturnSpecified()) {
9889     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9890     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9891     Diag(NoreturnLoc, diag::ext_noreturn_main);
9892     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9893       << FixItHint::CreateRemoval(NoreturnRange);
9894   }
9895   if (FD->isConstexpr()) {
9896     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9897       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9898     FD->setConstexpr(false);
9899   }
9900 
9901   if (getLangOpts().OpenCL) {
9902     Diag(FD->getLocation(), diag::err_opencl_no_main)
9903         << FD->hasAttr<OpenCLKernelAttr>();
9904     FD->setInvalidDecl();
9905     return;
9906   }
9907 
9908   QualType T = FD->getType();
9909   assert(T->isFunctionType() && "function decl is not of function type");
9910   const FunctionType* FT = T->castAs<FunctionType>();
9911 
9912   // Set default calling convention for main()
9913   if (FT->getCallConv() != CC_C) {
9914     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
9915     FD->setType(QualType(FT, 0));
9916     T = Context.getCanonicalType(FD->getType());
9917   }
9918 
9919   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9920     // In C with GNU extensions we allow main() to have non-integer return
9921     // type, but we should warn about the extension, and we disable the
9922     // implicit-return-zero rule.
9923 
9924     // GCC in C mode accepts qualified 'int'.
9925     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9926       FD->setHasImplicitReturnZero(true);
9927     else {
9928       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9929       SourceRange RTRange = FD->getReturnTypeSourceRange();
9930       if (RTRange.isValid())
9931         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9932             << FixItHint::CreateReplacement(RTRange, "int");
9933     }
9934   } else {
9935     // In C and C++, main magically returns 0 if you fall off the end;
9936     // set the flag which tells us that.
9937     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9938 
9939     // All the standards say that main() should return 'int'.
9940     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9941       FD->setHasImplicitReturnZero(true);
9942     else {
9943       // Otherwise, this is just a flat-out error.
9944       SourceRange RTRange = FD->getReturnTypeSourceRange();
9945       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9946           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9947                                 : FixItHint());
9948       FD->setInvalidDecl(true);
9949     }
9950   }
9951 
9952   // Treat protoless main() as nullary.
9953   if (isa<FunctionNoProtoType>(FT)) return;
9954 
9955   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9956   unsigned nparams = FTP->getNumParams();
9957   assert(FD->getNumParams() == nparams);
9958 
9959   bool HasExtraParameters = (nparams > 3);
9960 
9961   if (FTP->isVariadic()) {
9962     Diag(FD->getLocation(), diag::ext_variadic_main);
9963     // FIXME: if we had information about the location of the ellipsis, we
9964     // could add a FixIt hint to remove it as a parameter.
9965   }
9966 
9967   // Darwin passes an undocumented fourth argument of type char**.  If
9968   // other platforms start sprouting these, the logic below will start
9969   // getting shifty.
9970   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9971     HasExtraParameters = false;
9972 
9973   if (HasExtraParameters) {
9974     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9975     FD->setInvalidDecl(true);
9976     nparams = 3;
9977   }
9978 
9979   // FIXME: a lot of the following diagnostics would be improved
9980   // if we had some location information about types.
9981 
9982   QualType CharPP =
9983     Context.getPointerType(Context.getPointerType(Context.CharTy));
9984   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9985 
9986   for (unsigned i = 0; i < nparams; ++i) {
9987     QualType AT = FTP->getParamType(i);
9988 
9989     bool mismatch = true;
9990 
9991     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9992       mismatch = false;
9993     else if (Expected[i] == CharPP) {
9994       // As an extension, the following forms are okay:
9995       //   char const **
9996       //   char const * const *
9997       //   char * const *
9998 
9999       QualifierCollector qs;
10000       const PointerType* PT;
10001       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10002           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10003           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10004                               Context.CharTy)) {
10005         qs.removeConst();
10006         mismatch = !qs.empty();
10007       }
10008     }
10009 
10010     if (mismatch) {
10011       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10012       // TODO: suggest replacing given type with expected type
10013       FD->setInvalidDecl(true);
10014     }
10015   }
10016 
10017   if (nparams == 1 && !FD->isInvalidDecl()) {
10018     Diag(FD->getLocation(), diag::warn_main_one_arg);
10019   }
10020 
10021   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10022     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10023     FD->setInvalidDecl();
10024   }
10025 }
10026 
10027 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10028   QualType T = FD->getType();
10029   assert(T->isFunctionType() && "function decl is not of function type");
10030   const FunctionType *FT = T->castAs<FunctionType>();
10031 
10032   // Set an implicit return of 'zero' if the function can return some integral,
10033   // enumeration, pointer or nullptr type.
10034   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10035       FT->getReturnType()->isAnyPointerType() ||
10036       FT->getReturnType()->isNullPtrType())
10037     // DllMain is exempt because a return value of zero means it failed.
10038     if (FD->getName() != "DllMain")
10039       FD->setHasImplicitReturnZero(true);
10040 
10041   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10042     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10043     FD->setInvalidDecl();
10044   }
10045 }
10046 
10047 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10048   // FIXME: Need strict checking.  In C89, we need to check for
10049   // any assignment, increment, decrement, function-calls, or
10050   // commas outside of a sizeof.  In C99, it's the same list,
10051   // except that the aforementioned are allowed in unevaluated
10052   // expressions.  Everything else falls under the
10053   // "may accept other forms of constant expressions" exception.
10054   // (We never end up here for C++, so the constant expression
10055   // rules there don't matter.)
10056   const Expr *Culprit;
10057   if (Init->isConstantInitializer(Context, false, &Culprit))
10058     return false;
10059   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10060     << Culprit->getSourceRange();
10061   return true;
10062 }
10063 
10064 namespace {
10065   // Visits an initialization expression to see if OrigDecl is evaluated in
10066   // its own initialization and throws a warning if it does.
10067   class SelfReferenceChecker
10068       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10069     Sema &S;
10070     Decl *OrigDecl;
10071     bool isRecordType;
10072     bool isPODType;
10073     bool isReferenceType;
10074 
10075     bool isInitList;
10076     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10077 
10078   public:
10079     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10080 
10081     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10082                                                     S(S), OrigDecl(OrigDecl) {
10083       isPODType = false;
10084       isRecordType = false;
10085       isReferenceType = false;
10086       isInitList = false;
10087       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10088         isPODType = VD->getType().isPODType(S.Context);
10089         isRecordType = VD->getType()->isRecordType();
10090         isReferenceType = VD->getType()->isReferenceType();
10091       }
10092     }
10093 
10094     // For most expressions, just call the visitor.  For initializer lists,
10095     // track the index of the field being initialized since fields are
10096     // initialized in order allowing use of previously initialized fields.
10097     void CheckExpr(Expr *E) {
10098       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10099       if (!InitList) {
10100         Visit(E);
10101         return;
10102       }
10103 
10104       // Track and increment the index here.
10105       isInitList = true;
10106       InitFieldIndex.push_back(0);
10107       for (auto Child : InitList->children()) {
10108         CheckExpr(cast<Expr>(Child));
10109         ++InitFieldIndex.back();
10110       }
10111       InitFieldIndex.pop_back();
10112     }
10113 
10114     // Returns true if MemberExpr is checked and no further checking is needed.
10115     // Returns false if additional checking is required.
10116     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10117       llvm::SmallVector<FieldDecl*, 4> Fields;
10118       Expr *Base = E;
10119       bool ReferenceField = false;
10120 
10121       // Get the field memebers used.
10122       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10123         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10124         if (!FD)
10125           return false;
10126         Fields.push_back(FD);
10127         if (FD->getType()->isReferenceType())
10128           ReferenceField = true;
10129         Base = ME->getBase()->IgnoreParenImpCasts();
10130       }
10131 
10132       // Keep checking only if the base Decl is the same.
10133       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10134       if (!DRE || DRE->getDecl() != OrigDecl)
10135         return false;
10136 
10137       // A reference field can be bound to an unininitialized field.
10138       if (CheckReference && !ReferenceField)
10139         return true;
10140 
10141       // Convert FieldDecls to their index number.
10142       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10143       for (const FieldDecl *I : llvm::reverse(Fields))
10144         UsedFieldIndex.push_back(I->getFieldIndex());
10145 
10146       // See if a warning is needed by checking the first difference in index
10147       // numbers.  If field being used has index less than the field being
10148       // initialized, then the use is safe.
10149       for (auto UsedIter = UsedFieldIndex.begin(),
10150                 UsedEnd = UsedFieldIndex.end(),
10151                 OrigIter = InitFieldIndex.begin(),
10152                 OrigEnd = InitFieldIndex.end();
10153            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10154         if (*UsedIter < *OrigIter)
10155           return true;
10156         if (*UsedIter > *OrigIter)
10157           break;
10158       }
10159 
10160       // TODO: Add a different warning which will print the field names.
10161       HandleDeclRefExpr(DRE);
10162       return true;
10163     }
10164 
10165     // For most expressions, the cast is directly above the DeclRefExpr.
10166     // For conditional operators, the cast can be outside the conditional
10167     // operator if both expressions are DeclRefExpr's.
10168     void HandleValue(Expr *E) {
10169       E = E->IgnoreParens();
10170       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10171         HandleDeclRefExpr(DRE);
10172         return;
10173       }
10174 
10175       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10176         Visit(CO->getCond());
10177         HandleValue(CO->getTrueExpr());
10178         HandleValue(CO->getFalseExpr());
10179         return;
10180       }
10181 
10182       if (BinaryConditionalOperator *BCO =
10183               dyn_cast<BinaryConditionalOperator>(E)) {
10184         Visit(BCO->getCond());
10185         HandleValue(BCO->getFalseExpr());
10186         return;
10187       }
10188 
10189       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10190         HandleValue(OVE->getSourceExpr());
10191         return;
10192       }
10193 
10194       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10195         if (BO->getOpcode() == BO_Comma) {
10196           Visit(BO->getLHS());
10197           HandleValue(BO->getRHS());
10198           return;
10199         }
10200       }
10201 
10202       if (isa<MemberExpr>(E)) {
10203         if (isInitList) {
10204           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10205                                       false /*CheckReference*/))
10206             return;
10207         }
10208 
10209         Expr *Base = E->IgnoreParenImpCasts();
10210         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10211           // Check for static member variables and don't warn on them.
10212           if (!isa<FieldDecl>(ME->getMemberDecl()))
10213             return;
10214           Base = ME->getBase()->IgnoreParenImpCasts();
10215         }
10216         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10217           HandleDeclRefExpr(DRE);
10218         return;
10219       }
10220 
10221       Visit(E);
10222     }
10223 
10224     // Reference types not handled in HandleValue are handled here since all
10225     // uses of references are bad, not just r-value uses.
10226     void VisitDeclRefExpr(DeclRefExpr *E) {
10227       if (isReferenceType)
10228         HandleDeclRefExpr(E);
10229     }
10230 
10231     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10232       if (E->getCastKind() == CK_LValueToRValue) {
10233         HandleValue(E->getSubExpr());
10234         return;
10235       }
10236 
10237       Inherited::VisitImplicitCastExpr(E);
10238     }
10239 
10240     void VisitMemberExpr(MemberExpr *E) {
10241       if (isInitList) {
10242         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10243           return;
10244       }
10245 
10246       // Don't warn on arrays since they can be treated as pointers.
10247       if (E->getType()->canDecayToPointerType()) return;
10248 
10249       // Warn when a non-static method call is followed by non-static member
10250       // field accesses, which is followed by a DeclRefExpr.
10251       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10252       bool Warn = (MD && !MD->isStatic());
10253       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10254       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10255         if (!isa<FieldDecl>(ME->getMemberDecl()))
10256           Warn = false;
10257         Base = ME->getBase()->IgnoreParenImpCasts();
10258       }
10259 
10260       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10261         if (Warn)
10262           HandleDeclRefExpr(DRE);
10263         return;
10264       }
10265 
10266       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10267       // Visit that expression.
10268       Visit(Base);
10269     }
10270 
10271     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10272       Expr *Callee = E->getCallee();
10273 
10274       if (isa<UnresolvedLookupExpr>(Callee))
10275         return Inherited::VisitCXXOperatorCallExpr(E);
10276 
10277       Visit(Callee);
10278       for (auto Arg: E->arguments())
10279         HandleValue(Arg->IgnoreParenImpCasts());
10280     }
10281 
10282     void VisitUnaryOperator(UnaryOperator *E) {
10283       // For POD record types, addresses of its own members are well-defined.
10284       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10285           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10286         if (!isPODType)
10287           HandleValue(E->getSubExpr());
10288         return;
10289       }
10290 
10291       if (E->isIncrementDecrementOp()) {
10292         HandleValue(E->getSubExpr());
10293         return;
10294       }
10295 
10296       Inherited::VisitUnaryOperator(E);
10297     }
10298 
10299     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10300 
10301     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10302       if (E->getConstructor()->isCopyConstructor()) {
10303         Expr *ArgExpr = E->getArg(0);
10304         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10305           if (ILE->getNumInits() == 1)
10306             ArgExpr = ILE->getInit(0);
10307         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10308           if (ICE->getCastKind() == CK_NoOp)
10309             ArgExpr = ICE->getSubExpr();
10310         HandleValue(ArgExpr);
10311         return;
10312       }
10313       Inherited::VisitCXXConstructExpr(E);
10314     }
10315 
10316     void VisitCallExpr(CallExpr *E) {
10317       // Treat std::move as a use.
10318       if (E->isCallToStdMove()) {
10319         HandleValue(E->getArg(0));
10320         return;
10321       }
10322 
10323       Inherited::VisitCallExpr(E);
10324     }
10325 
10326     void VisitBinaryOperator(BinaryOperator *E) {
10327       if (E->isCompoundAssignmentOp()) {
10328         HandleValue(E->getLHS());
10329         Visit(E->getRHS());
10330         return;
10331       }
10332 
10333       Inherited::VisitBinaryOperator(E);
10334     }
10335 
10336     // A custom visitor for BinaryConditionalOperator is needed because the
10337     // regular visitor would check the condition and true expression separately
10338     // but both point to the same place giving duplicate diagnostics.
10339     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10340       Visit(E->getCond());
10341       Visit(E->getFalseExpr());
10342     }
10343 
10344     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10345       Decl* ReferenceDecl = DRE->getDecl();
10346       if (OrigDecl != ReferenceDecl) return;
10347       unsigned diag;
10348       if (isReferenceType) {
10349         diag = diag::warn_uninit_self_reference_in_reference_init;
10350       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10351         diag = diag::warn_static_self_reference_in_init;
10352       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10353                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10354                  DRE->getDecl()->getType()->isRecordType()) {
10355         diag = diag::warn_uninit_self_reference_in_init;
10356       } else {
10357         // Local variables will be handled by the CFG analysis.
10358         return;
10359       }
10360 
10361       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10362                             S.PDiag(diag)
10363                               << DRE->getDecl()
10364                               << OrigDecl->getLocation()
10365                               << DRE->getSourceRange());
10366     }
10367   };
10368 
10369   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10370   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10371                                  bool DirectInit) {
10372     // Parameters arguments are occassionially constructed with itself,
10373     // for instance, in recursive functions.  Skip them.
10374     if (isa<ParmVarDecl>(OrigDecl))
10375       return;
10376 
10377     E = E->IgnoreParens();
10378 
10379     // Skip checking T a = a where T is not a record or reference type.
10380     // Doing so is a way to silence uninitialized warnings.
10381     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10382       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10383         if (ICE->getCastKind() == CK_LValueToRValue)
10384           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10385             if (DRE->getDecl() == OrigDecl)
10386               return;
10387 
10388     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10389   }
10390 } // end anonymous namespace
10391 
10392 namespace {
10393   // Simple wrapper to add the name of a variable or (if no variable is
10394   // available) a DeclarationName into a diagnostic.
10395   struct VarDeclOrName {
10396     VarDecl *VDecl;
10397     DeclarationName Name;
10398 
10399     friend const Sema::SemaDiagnosticBuilder &
10400     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10401       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10402     }
10403   };
10404 } // end anonymous namespace
10405 
10406 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10407                                             DeclarationName Name, QualType Type,
10408                                             TypeSourceInfo *TSI,
10409                                             SourceRange Range, bool DirectInit,
10410                                             Expr *Init) {
10411   bool IsInitCapture = !VDecl;
10412   assert((!VDecl || !VDecl->isInitCapture()) &&
10413          "init captures are expected to be deduced prior to initialization");
10414 
10415   VarDeclOrName VN{VDecl, Name};
10416 
10417   DeducedType *Deduced = Type->getContainedDeducedType();
10418   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10419 
10420   // C++11 [dcl.spec.auto]p3
10421   if (!Init) {
10422     assert(VDecl && "no init for init capture deduction?");
10423 
10424     // Except for class argument deduction, and then for an initializing
10425     // declaration only, i.e. no static at class scope or extern.
10426     if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10427         VDecl->hasExternalStorage() ||
10428         VDecl->isStaticDataMember()) {
10429       Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10430         << VDecl->getDeclName() << Type;
10431       return QualType();
10432     }
10433   }
10434 
10435   ArrayRef<Expr*> DeduceInits;
10436   if (Init)
10437     DeduceInits = Init;
10438 
10439   if (DirectInit) {
10440     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10441       DeduceInits = PL->exprs();
10442   }
10443 
10444   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10445     assert(VDecl && "non-auto type for init capture deduction?");
10446     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10447     InitializationKind Kind = InitializationKind::CreateForInit(
10448         VDecl->getLocation(), DirectInit, Init);
10449     // FIXME: Initialization should not be taking a mutable list of inits.
10450     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10451     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10452                                                        InitsCopy);
10453   }
10454 
10455   if (DirectInit) {
10456     if (auto *IL = dyn_cast<InitListExpr>(Init))
10457       DeduceInits = IL->inits();
10458   }
10459 
10460   // Deduction only works if we have exactly one source expression.
10461   if (DeduceInits.empty()) {
10462     // It isn't possible to write this directly, but it is possible to
10463     // end up in this situation with "auto x(some_pack...);"
10464     Diag(Init->getLocStart(), IsInitCapture
10465                                   ? diag::err_init_capture_no_expression
10466                                   : diag::err_auto_var_init_no_expression)
10467         << VN << Type << Range;
10468     return QualType();
10469   }
10470 
10471   if (DeduceInits.size() > 1) {
10472     Diag(DeduceInits[1]->getLocStart(),
10473          IsInitCapture ? diag::err_init_capture_multiple_expressions
10474                        : diag::err_auto_var_init_multiple_expressions)
10475         << VN << Type << Range;
10476     return QualType();
10477   }
10478 
10479   Expr *DeduceInit = DeduceInits[0];
10480   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10481     Diag(Init->getLocStart(), IsInitCapture
10482                                   ? diag::err_init_capture_paren_braces
10483                                   : diag::err_auto_var_init_paren_braces)
10484         << isa<InitListExpr>(Init) << VN << Type << Range;
10485     return QualType();
10486   }
10487 
10488   // Expressions default to 'id' when we're in a debugger.
10489   bool DefaultedAnyToId = false;
10490   if (getLangOpts().DebuggerCastResultToId &&
10491       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10492     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10493     if (Result.isInvalid()) {
10494       return QualType();
10495     }
10496     Init = Result.get();
10497     DefaultedAnyToId = true;
10498   }
10499 
10500   // C++ [dcl.decomp]p1:
10501   //   If the assignment-expression [...] has array type A and no ref-qualifier
10502   //   is present, e has type cv A
10503   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10504       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10505       DeduceInit->getType()->isConstantArrayType())
10506     return Context.getQualifiedType(DeduceInit->getType(),
10507                                     Type.getQualifiers());
10508 
10509   QualType DeducedType;
10510   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10511     if (!IsInitCapture)
10512       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10513     else if (isa<InitListExpr>(Init))
10514       Diag(Range.getBegin(),
10515            diag::err_init_capture_deduction_failure_from_init_list)
10516           << VN
10517           << (DeduceInit->getType().isNull() ? TSI->getType()
10518                                              : DeduceInit->getType())
10519           << DeduceInit->getSourceRange();
10520     else
10521       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10522           << VN << TSI->getType()
10523           << (DeduceInit->getType().isNull() ? TSI->getType()
10524                                              : DeduceInit->getType())
10525           << DeduceInit->getSourceRange();
10526   }
10527 
10528   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10529   // 'id' instead of a specific object type prevents most of our usual
10530   // checks.
10531   // We only want to warn outside of template instantiations, though:
10532   // inside a template, the 'id' could have come from a parameter.
10533   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10534       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10535     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10536     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10537   }
10538 
10539   return DeducedType;
10540 }
10541 
10542 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10543                                          Expr *Init) {
10544   QualType DeducedType = deduceVarTypeFromInitializer(
10545       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10546       VDecl->getSourceRange(), DirectInit, Init);
10547   if (DeducedType.isNull()) {
10548     VDecl->setInvalidDecl();
10549     return true;
10550   }
10551 
10552   VDecl->setType(DeducedType);
10553   assert(VDecl->isLinkageValid());
10554 
10555   // In ARC, infer lifetime.
10556   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10557     VDecl->setInvalidDecl();
10558 
10559   // If this is a redeclaration, check that the type we just deduced matches
10560   // the previously declared type.
10561   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10562     // We never need to merge the type, because we cannot form an incomplete
10563     // array of auto, nor deduce such a type.
10564     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10565   }
10566 
10567   // Check the deduced type is valid for a variable declaration.
10568   CheckVariableDeclarationType(VDecl);
10569   return VDecl->isInvalidDecl();
10570 }
10571 
10572 /// AddInitializerToDecl - Adds the initializer Init to the
10573 /// declaration dcl. If DirectInit is true, this is C++ direct
10574 /// initialization rather than copy initialization.
10575 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10576   // If there is no declaration, there was an error parsing it.  Just ignore
10577   // the initializer.
10578   if (!RealDecl || RealDecl->isInvalidDecl()) {
10579     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10580     return;
10581   }
10582 
10583   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10584     // Pure-specifiers are handled in ActOnPureSpecifier.
10585     Diag(Method->getLocation(), diag::err_member_function_initialization)
10586       << Method->getDeclName() << Init->getSourceRange();
10587     Method->setInvalidDecl();
10588     return;
10589   }
10590 
10591   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10592   if (!VDecl) {
10593     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10594     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10595     RealDecl->setInvalidDecl();
10596     return;
10597   }
10598 
10599   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10600   if (VDecl->getType()->isUndeducedType()) {
10601     // Attempt typo correction early so that the type of the init expression can
10602     // be deduced based on the chosen correction if the original init contains a
10603     // TypoExpr.
10604     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10605     if (!Res.isUsable()) {
10606       RealDecl->setInvalidDecl();
10607       return;
10608     }
10609     Init = Res.get();
10610 
10611     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10612       return;
10613   }
10614 
10615   // dllimport cannot be used on variable definitions.
10616   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10617     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10618     VDecl->setInvalidDecl();
10619     return;
10620   }
10621 
10622   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10623     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10624     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10625     VDecl->setInvalidDecl();
10626     return;
10627   }
10628 
10629   if (!VDecl->getType()->isDependentType()) {
10630     // A definition must end up with a complete type, which means it must be
10631     // complete with the restriction that an array type might be completed by
10632     // the initializer; note that later code assumes this restriction.
10633     QualType BaseDeclType = VDecl->getType();
10634     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10635       BaseDeclType = Array->getElementType();
10636     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10637                             diag::err_typecheck_decl_incomplete_type)) {
10638       RealDecl->setInvalidDecl();
10639       return;
10640     }
10641 
10642     // The variable can not have an abstract class type.
10643     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10644                                diag::err_abstract_type_in_decl,
10645                                AbstractVariableType))
10646       VDecl->setInvalidDecl();
10647   }
10648 
10649   // If adding the initializer will turn this declaration into a definition,
10650   // and we already have a definition for this variable, diagnose or otherwise
10651   // handle the situation.
10652   VarDecl *Def;
10653   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10654       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10655       !VDecl->isThisDeclarationADemotedDefinition() &&
10656       checkVarDeclRedefinition(Def, VDecl))
10657     return;
10658 
10659   if (getLangOpts().CPlusPlus) {
10660     // C++ [class.static.data]p4
10661     //   If a static data member is of const integral or const
10662     //   enumeration type, its declaration in the class definition can
10663     //   specify a constant-initializer which shall be an integral
10664     //   constant expression (5.19). In that case, the member can appear
10665     //   in integral constant expressions. The member shall still be
10666     //   defined in a namespace scope if it is used in the program and the
10667     //   namespace scope definition shall not contain an initializer.
10668     //
10669     // We already performed a redefinition check above, but for static
10670     // data members we also need to check whether there was an in-class
10671     // declaration with an initializer.
10672     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10673       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10674           << VDecl->getDeclName();
10675       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10676            diag::note_previous_initializer)
10677           << 0;
10678       return;
10679     }
10680 
10681     if (VDecl->hasLocalStorage())
10682       setFunctionHasBranchProtectedScope();
10683 
10684     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10685       VDecl->setInvalidDecl();
10686       return;
10687     }
10688   }
10689 
10690   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10691   // a kernel function cannot be initialized."
10692   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10693     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10694     VDecl->setInvalidDecl();
10695     return;
10696   }
10697 
10698   // Get the decls type and save a reference for later, since
10699   // CheckInitializerTypes may change it.
10700   QualType DclT = VDecl->getType(), SavT = DclT;
10701 
10702   // Expressions default to 'id' when we're in a debugger
10703   // and we are assigning it to a variable of Objective-C pointer type.
10704   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10705       Init->getType() == Context.UnknownAnyTy) {
10706     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10707     if (Result.isInvalid()) {
10708       VDecl->setInvalidDecl();
10709       return;
10710     }
10711     Init = Result.get();
10712   }
10713 
10714   // Perform the initialization.
10715   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10716   if (!VDecl->isInvalidDecl()) {
10717     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10718     InitializationKind Kind = InitializationKind::CreateForInit(
10719         VDecl->getLocation(), DirectInit, Init);
10720 
10721     MultiExprArg Args = Init;
10722     if (CXXDirectInit)
10723       Args = MultiExprArg(CXXDirectInit->getExprs(),
10724                           CXXDirectInit->getNumExprs());
10725 
10726     // Try to correct any TypoExprs in the initialization arguments.
10727     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10728       ExprResult Res = CorrectDelayedTyposInExpr(
10729           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10730             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10731             return Init.Failed() ? ExprError() : E;
10732           });
10733       if (Res.isInvalid()) {
10734         VDecl->setInvalidDecl();
10735       } else if (Res.get() != Args[Idx]) {
10736         Args[Idx] = Res.get();
10737       }
10738     }
10739     if (VDecl->isInvalidDecl())
10740       return;
10741 
10742     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10743                                    /*TopLevelOfInitList=*/false,
10744                                    /*TreatUnavailableAsInvalid=*/false);
10745     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10746     if (Result.isInvalid()) {
10747       VDecl->setInvalidDecl();
10748       return;
10749     }
10750 
10751     Init = Result.getAs<Expr>();
10752   }
10753 
10754   // Check for self-references within variable initializers.
10755   // Variables declared within a function/method body (except for references)
10756   // are handled by a dataflow analysis.
10757   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10758       VDecl->getType()->isReferenceType()) {
10759     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10760   }
10761 
10762   // If the type changed, it means we had an incomplete type that was
10763   // completed by the initializer. For example:
10764   //   int ary[] = { 1, 3, 5 };
10765   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10766   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10767     VDecl->setType(DclT);
10768 
10769   if (!VDecl->isInvalidDecl()) {
10770     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10771 
10772     if (VDecl->hasAttr<BlocksAttr>())
10773       checkRetainCycles(VDecl, Init);
10774 
10775     // It is safe to assign a weak reference into a strong variable.
10776     // Although this code can still have problems:
10777     //   id x = self.weakProp;
10778     //   id y = self.weakProp;
10779     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10780     // paths through the function. This should be revisited if
10781     // -Wrepeated-use-of-weak is made flow-sensitive.
10782     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10783          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10784         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10785                          Init->getLocStart()))
10786       getCurFunction()->markSafeWeakUse(Init);
10787   }
10788 
10789   // The initialization is usually a full-expression.
10790   //
10791   // FIXME: If this is a braced initialization of an aggregate, it is not
10792   // an expression, and each individual field initializer is a separate
10793   // full-expression. For instance, in:
10794   //
10795   //   struct Temp { ~Temp(); };
10796   //   struct S { S(Temp); };
10797   //   struct T { S a, b; } t = { Temp(), Temp() }
10798   //
10799   // we should destroy the first Temp before constructing the second.
10800   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10801                                           false,
10802                                           VDecl->isConstexpr());
10803   if (Result.isInvalid()) {
10804     VDecl->setInvalidDecl();
10805     return;
10806   }
10807   Init = Result.get();
10808 
10809   // Attach the initializer to the decl.
10810   VDecl->setInit(Init);
10811 
10812   if (VDecl->isLocalVarDecl()) {
10813     // Don't check the initializer if the declaration is malformed.
10814     if (VDecl->isInvalidDecl()) {
10815       // do nothing
10816 
10817     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10818     // This is true even in OpenCL C++.
10819     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10820       CheckForConstantInitializer(Init, DclT);
10821 
10822     // Otherwise, C++ does not restrict the initializer.
10823     } else if (getLangOpts().CPlusPlus) {
10824       // do nothing
10825 
10826     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10827     // static storage duration shall be constant expressions or string literals.
10828     } else if (VDecl->getStorageClass() == SC_Static) {
10829       CheckForConstantInitializer(Init, DclT);
10830 
10831     // C89 is stricter than C99 for aggregate initializers.
10832     // C89 6.5.7p3: All the expressions [...] in an initializer list
10833     // for an object that has aggregate or union type shall be
10834     // constant expressions.
10835     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10836                isa<InitListExpr>(Init)) {
10837       const Expr *Culprit;
10838       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10839         Diag(Culprit->getExprLoc(),
10840              diag::ext_aggregate_init_not_constant)
10841           << Culprit->getSourceRange();
10842       }
10843     }
10844   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10845              VDecl->getLexicalDeclContext()->isRecord()) {
10846     // This is an in-class initialization for a static data member, e.g.,
10847     //
10848     // struct S {
10849     //   static const int value = 17;
10850     // };
10851 
10852     // C++ [class.mem]p4:
10853     //   A member-declarator can contain a constant-initializer only
10854     //   if it declares a static member (9.4) of const integral or
10855     //   const enumeration type, see 9.4.2.
10856     //
10857     // C++11 [class.static.data]p3:
10858     //   If a non-volatile non-inline const static data member is of integral
10859     //   or enumeration type, its declaration in the class definition can
10860     //   specify a brace-or-equal-initializer in which every initializer-clause
10861     //   that is an assignment-expression is a constant expression. A static
10862     //   data member of literal type can be declared in the class definition
10863     //   with the constexpr specifier; if so, its declaration shall specify a
10864     //   brace-or-equal-initializer in which every initializer-clause that is
10865     //   an assignment-expression is a constant expression.
10866 
10867     // Do nothing on dependent types.
10868     if (DclT->isDependentType()) {
10869 
10870     // Allow any 'static constexpr' members, whether or not they are of literal
10871     // type. We separately check that every constexpr variable is of literal
10872     // type.
10873     } else if (VDecl->isConstexpr()) {
10874 
10875     // Require constness.
10876     } else if (!DclT.isConstQualified()) {
10877       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10878         << Init->getSourceRange();
10879       VDecl->setInvalidDecl();
10880 
10881     // We allow integer constant expressions in all cases.
10882     } else if (DclT->isIntegralOrEnumerationType()) {
10883       // Check whether the expression is a constant expression.
10884       SourceLocation Loc;
10885       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10886         // In C++11, a non-constexpr const static data member with an
10887         // in-class initializer cannot be volatile.
10888         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10889       else if (Init->isValueDependent())
10890         ; // Nothing to check.
10891       else if (Init->isIntegerConstantExpr(Context, &Loc))
10892         ; // Ok, it's an ICE!
10893       else if (Init->isEvaluatable(Context)) {
10894         // If we can constant fold the initializer through heroics, accept it,
10895         // but report this as a use of an extension for -pedantic.
10896         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10897           << Init->getSourceRange();
10898       } else {
10899         // Otherwise, this is some crazy unknown case.  Report the issue at the
10900         // location provided by the isIntegerConstantExpr failed check.
10901         Diag(Loc, diag::err_in_class_initializer_non_constant)
10902           << Init->getSourceRange();
10903         VDecl->setInvalidDecl();
10904       }
10905 
10906     // We allow foldable floating-point constants as an extension.
10907     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10908       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10909       // it anyway and provide a fixit to add the 'constexpr'.
10910       if (getLangOpts().CPlusPlus11) {
10911         Diag(VDecl->getLocation(),
10912              diag::ext_in_class_initializer_float_type_cxx11)
10913             << DclT << Init->getSourceRange();
10914         Diag(VDecl->getLocStart(),
10915              diag::note_in_class_initializer_float_type_cxx11)
10916             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10917       } else {
10918         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10919           << DclT << Init->getSourceRange();
10920 
10921         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10922           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10923             << Init->getSourceRange();
10924           VDecl->setInvalidDecl();
10925         }
10926       }
10927 
10928     // Suggest adding 'constexpr' in C++11 for literal types.
10929     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10930       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10931         << DclT << Init->getSourceRange()
10932         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10933       VDecl->setConstexpr(true);
10934 
10935     } else {
10936       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10937         << DclT << Init->getSourceRange();
10938       VDecl->setInvalidDecl();
10939     }
10940   } else if (VDecl->isFileVarDecl()) {
10941     // In C, extern is typically used to avoid tentative definitions when
10942     // declaring variables in headers, but adding an intializer makes it a
10943     // definition. This is somewhat confusing, so GCC and Clang both warn on it.
10944     // In C++, extern is often used to give implictly static const variables
10945     // external linkage, so don't warn in that case. If selectany is present,
10946     // this might be header code intended for C and C++ inclusion, so apply the
10947     // C++ rules.
10948     if (VDecl->getStorageClass() == SC_Extern &&
10949         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10950          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10951         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10952         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10953       Diag(VDecl->getLocation(), diag::warn_extern_init);
10954 
10955     // C99 6.7.8p4. All file scoped initializers need to be constant.
10956     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10957       CheckForConstantInitializer(Init, DclT);
10958   }
10959 
10960   // We will represent direct-initialization similarly to copy-initialization:
10961   //    int x(1);  -as-> int x = 1;
10962   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10963   //
10964   // Clients that want to distinguish between the two forms, can check for
10965   // direct initializer using VarDecl::getInitStyle().
10966   // A major benefit is that clients that don't particularly care about which
10967   // exactly form was it (like the CodeGen) can handle both cases without
10968   // special case code.
10969 
10970   // C++ 8.5p11:
10971   // The form of initialization (using parentheses or '=') is generally
10972   // insignificant, but does matter when the entity being initialized has a
10973   // class type.
10974   if (CXXDirectInit) {
10975     assert(DirectInit && "Call-style initializer must be direct init.");
10976     VDecl->setInitStyle(VarDecl::CallInit);
10977   } else if (DirectInit) {
10978     // This must be list-initialization. No other way is direct-initialization.
10979     VDecl->setInitStyle(VarDecl::ListInit);
10980   }
10981 
10982   CheckCompleteVariableDeclaration(VDecl);
10983 }
10984 
10985 /// ActOnInitializerError - Given that there was an error parsing an
10986 /// initializer for the given declaration, try to return to some form
10987 /// of sanity.
10988 void Sema::ActOnInitializerError(Decl *D) {
10989   // Our main concern here is re-establishing invariants like "a
10990   // variable's type is either dependent or complete".
10991   if (!D || D->isInvalidDecl()) return;
10992 
10993   VarDecl *VD = dyn_cast<VarDecl>(D);
10994   if (!VD) return;
10995 
10996   // Bindings are not usable if we can't make sense of the initializer.
10997   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10998     for (auto *BD : DD->bindings())
10999       BD->setInvalidDecl();
11000 
11001   // Auto types are meaningless if we can't make sense of the initializer.
11002   if (ParsingInitForAutoVars.count(D)) {
11003     D->setInvalidDecl();
11004     return;
11005   }
11006 
11007   QualType Ty = VD->getType();
11008   if (Ty->isDependentType()) return;
11009 
11010   // Require a complete type.
11011   if (RequireCompleteType(VD->getLocation(),
11012                           Context.getBaseElementType(Ty),
11013                           diag::err_typecheck_decl_incomplete_type)) {
11014     VD->setInvalidDecl();
11015     return;
11016   }
11017 
11018   // Require a non-abstract type.
11019   if (RequireNonAbstractType(VD->getLocation(), Ty,
11020                              diag::err_abstract_type_in_decl,
11021                              AbstractVariableType)) {
11022     VD->setInvalidDecl();
11023     return;
11024   }
11025 
11026   // Don't bother complaining about constructors or destructors,
11027   // though.
11028 }
11029 
11030 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11031   // If there is no declaration, there was an error parsing it. Just ignore it.
11032   if (!RealDecl)
11033     return;
11034 
11035   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11036     QualType Type = Var->getType();
11037 
11038     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11039     if (isa<DecompositionDecl>(RealDecl)) {
11040       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11041       Var->setInvalidDecl();
11042       return;
11043     }
11044 
11045     if (Type->isUndeducedType() &&
11046         DeduceVariableDeclarationType(Var, false, nullptr))
11047       return;
11048 
11049     // C++11 [class.static.data]p3: A static data member can be declared with
11050     // the constexpr specifier; if so, its declaration shall specify
11051     // a brace-or-equal-initializer.
11052     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11053     // the definition of a variable [...] or the declaration of a static data
11054     // member.
11055     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11056         !Var->isThisDeclarationADemotedDefinition()) {
11057       if (Var->isStaticDataMember()) {
11058         // C++1z removes the relevant rule; the in-class declaration is always
11059         // a definition there.
11060         if (!getLangOpts().CPlusPlus17) {
11061           Diag(Var->getLocation(),
11062                diag::err_constexpr_static_mem_var_requires_init)
11063             << Var->getDeclName();
11064           Var->setInvalidDecl();
11065           return;
11066         }
11067       } else {
11068         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11069         Var->setInvalidDecl();
11070         return;
11071       }
11072     }
11073 
11074     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11075     // be initialized.
11076     if (!Var->isInvalidDecl() &&
11077         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11078         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11079       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11080       Var->setInvalidDecl();
11081       return;
11082     }
11083 
11084     switch (Var->isThisDeclarationADefinition()) {
11085     case VarDecl::Definition:
11086       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11087         break;
11088 
11089       // We have an out-of-line definition of a static data member
11090       // that has an in-class initializer, so we type-check this like
11091       // a declaration.
11092       //
11093       LLVM_FALLTHROUGH;
11094 
11095     case VarDecl::DeclarationOnly:
11096       // It's only a declaration.
11097 
11098       // Block scope. C99 6.7p7: If an identifier for an object is
11099       // declared with no linkage (C99 6.2.2p6), the type for the
11100       // object shall be complete.
11101       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11102           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11103           RequireCompleteType(Var->getLocation(), Type,
11104                               diag::err_typecheck_decl_incomplete_type))
11105         Var->setInvalidDecl();
11106 
11107       // Make sure that the type is not abstract.
11108       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11109           RequireNonAbstractType(Var->getLocation(), Type,
11110                                  diag::err_abstract_type_in_decl,
11111                                  AbstractVariableType))
11112         Var->setInvalidDecl();
11113       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11114           Var->getStorageClass() == SC_PrivateExtern) {
11115         Diag(Var->getLocation(), diag::warn_private_extern);
11116         Diag(Var->getLocation(), diag::note_private_extern);
11117       }
11118 
11119       return;
11120 
11121     case VarDecl::TentativeDefinition:
11122       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11123       // object that has file scope without an initializer, and without a
11124       // storage-class specifier or with the storage-class specifier "static",
11125       // constitutes a tentative definition. Note: A tentative definition with
11126       // external linkage is valid (C99 6.2.2p5).
11127       if (!Var->isInvalidDecl()) {
11128         if (const IncompleteArrayType *ArrayT
11129                                     = Context.getAsIncompleteArrayType(Type)) {
11130           if (RequireCompleteType(Var->getLocation(),
11131                                   ArrayT->getElementType(),
11132                                   diag::err_illegal_decl_array_incomplete_type))
11133             Var->setInvalidDecl();
11134         } else if (Var->getStorageClass() == SC_Static) {
11135           // C99 6.9.2p3: If the declaration of an identifier for an object is
11136           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11137           // declared type shall not be an incomplete type.
11138           // NOTE: code such as the following
11139           //     static struct s;
11140           //     struct s { int a; };
11141           // is accepted by gcc. Hence here we issue a warning instead of
11142           // an error and we do not invalidate the static declaration.
11143           // NOTE: to avoid multiple warnings, only check the first declaration.
11144           if (Var->isFirstDecl())
11145             RequireCompleteType(Var->getLocation(), Type,
11146                                 diag::ext_typecheck_decl_incomplete_type);
11147         }
11148       }
11149 
11150       // Record the tentative definition; we're done.
11151       if (!Var->isInvalidDecl())
11152         TentativeDefinitions.push_back(Var);
11153       return;
11154     }
11155 
11156     // Provide a specific diagnostic for uninitialized variable
11157     // definitions with incomplete array type.
11158     if (Type->isIncompleteArrayType()) {
11159       Diag(Var->getLocation(),
11160            diag::err_typecheck_incomplete_array_needs_initializer);
11161       Var->setInvalidDecl();
11162       return;
11163     }
11164 
11165     // Provide a specific diagnostic for uninitialized variable
11166     // definitions with reference type.
11167     if (Type->isReferenceType()) {
11168       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11169         << Var->getDeclName()
11170         << SourceRange(Var->getLocation(), Var->getLocation());
11171       Var->setInvalidDecl();
11172       return;
11173     }
11174 
11175     // Do not attempt to type-check the default initializer for a
11176     // variable with dependent type.
11177     if (Type->isDependentType())
11178       return;
11179 
11180     if (Var->isInvalidDecl())
11181       return;
11182 
11183     if (!Var->hasAttr<AliasAttr>()) {
11184       if (RequireCompleteType(Var->getLocation(),
11185                               Context.getBaseElementType(Type),
11186                               diag::err_typecheck_decl_incomplete_type)) {
11187         Var->setInvalidDecl();
11188         return;
11189       }
11190     } else {
11191       return;
11192     }
11193 
11194     // The variable can not have an abstract class type.
11195     if (RequireNonAbstractType(Var->getLocation(), Type,
11196                                diag::err_abstract_type_in_decl,
11197                                AbstractVariableType)) {
11198       Var->setInvalidDecl();
11199       return;
11200     }
11201 
11202     // Check for jumps past the implicit initializer.  C++0x
11203     // clarifies that this applies to a "variable with automatic
11204     // storage duration", not a "local variable".
11205     // C++11 [stmt.dcl]p3
11206     //   A program that jumps from a point where a variable with automatic
11207     //   storage duration is not in scope to a point where it is in scope is
11208     //   ill-formed unless the variable has scalar type, class type with a
11209     //   trivial default constructor and a trivial destructor, a cv-qualified
11210     //   version of one of these types, or an array of one of the preceding
11211     //   types and is declared without an initializer.
11212     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11213       if (const RecordType *Record
11214             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11215         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11216         // Mark the function (if we're in one) for further checking even if the
11217         // looser rules of C++11 do not require such checks, so that we can
11218         // diagnose incompatibilities with C++98.
11219         if (!CXXRecord->isPOD())
11220           setFunctionHasBranchProtectedScope();
11221       }
11222     }
11223 
11224     // C++03 [dcl.init]p9:
11225     //   If no initializer is specified for an object, and the
11226     //   object is of (possibly cv-qualified) non-POD class type (or
11227     //   array thereof), the object shall be default-initialized; if
11228     //   the object is of const-qualified type, the underlying class
11229     //   type shall have a user-declared default
11230     //   constructor. Otherwise, if no initializer is specified for
11231     //   a non- static object, the object and its subobjects, if
11232     //   any, have an indeterminate initial value); if the object
11233     //   or any of its subobjects are of const-qualified type, the
11234     //   program is ill-formed.
11235     // C++0x [dcl.init]p11:
11236     //   If no initializer is specified for an object, the object is
11237     //   default-initialized; [...].
11238     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11239     InitializationKind Kind
11240       = InitializationKind::CreateDefault(Var->getLocation());
11241 
11242     InitializationSequence InitSeq(*this, Entity, Kind, None);
11243     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11244     if (Init.isInvalid())
11245       Var->setInvalidDecl();
11246     else if (Init.get()) {
11247       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11248       // This is important for template substitution.
11249       Var->setInitStyle(VarDecl::CallInit);
11250     }
11251 
11252     CheckCompleteVariableDeclaration(Var);
11253   }
11254 }
11255 
11256 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11257   // If there is no declaration, there was an error parsing it. Ignore it.
11258   if (!D)
11259     return;
11260 
11261   VarDecl *VD = dyn_cast<VarDecl>(D);
11262   if (!VD) {
11263     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11264     D->setInvalidDecl();
11265     return;
11266   }
11267 
11268   VD->setCXXForRangeDecl(true);
11269 
11270   // for-range-declaration cannot be given a storage class specifier.
11271   int Error = -1;
11272   switch (VD->getStorageClass()) {
11273   case SC_None:
11274     break;
11275   case SC_Extern:
11276     Error = 0;
11277     break;
11278   case SC_Static:
11279     Error = 1;
11280     break;
11281   case SC_PrivateExtern:
11282     Error = 2;
11283     break;
11284   case SC_Auto:
11285     Error = 3;
11286     break;
11287   case SC_Register:
11288     Error = 4;
11289     break;
11290   }
11291   if (Error != -1) {
11292     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11293       << VD->getDeclName() << Error;
11294     D->setInvalidDecl();
11295   }
11296 }
11297 
11298 StmtResult
11299 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11300                                  IdentifierInfo *Ident,
11301                                  ParsedAttributes &Attrs,
11302                                  SourceLocation AttrEnd) {
11303   // C++1y [stmt.iter]p1:
11304   //   A range-based for statement of the form
11305   //      for ( for-range-identifier : for-range-initializer ) statement
11306   //   is equivalent to
11307   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11308   DeclSpec DS(Attrs.getPool().getFactory());
11309 
11310   const char *PrevSpec;
11311   unsigned DiagID;
11312   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11313                      getPrintingPolicy());
11314 
11315   Declarator D(DS, DeclaratorContext::ForContext);
11316   D.SetIdentifier(Ident, IdentLoc);
11317   D.takeAttributes(Attrs, AttrEnd);
11318 
11319   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11320   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11321                 EmptyAttrs, IdentLoc);
11322   Decl *Var = ActOnDeclarator(S, D);
11323   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11324   FinalizeDeclaration(Var);
11325   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11326                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11327 }
11328 
11329 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11330   if (var->isInvalidDecl()) return;
11331 
11332   if (getLangOpts().OpenCL) {
11333     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11334     // initialiser
11335     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11336         !var->hasInit()) {
11337       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11338           << 1 /*Init*/;
11339       var->setInvalidDecl();
11340       return;
11341     }
11342   }
11343 
11344   // In Objective-C, don't allow jumps past the implicit initialization of a
11345   // local retaining variable.
11346   if (getLangOpts().ObjC1 &&
11347       var->hasLocalStorage()) {
11348     switch (var->getType().getObjCLifetime()) {
11349     case Qualifiers::OCL_None:
11350     case Qualifiers::OCL_ExplicitNone:
11351     case Qualifiers::OCL_Autoreleasing:
11352       break;
11353 
11354     case Qualifiers::OCL_Weak:
11355     case Qualifiers::OCL_Strong:
11356       setFunctionHasBranchProtectedScope();
11357       break;
11358     }
11359   }
11360 
11361   if (var->hasLocalStorage() &&
11362       var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11363     setFunctionHasBranchProtectedScope();
11364 
11365   // Warn about externally-visible variables being defined without a
11366   // prior declaration.  We only want to do this for global
11367   // declarations, but we also specifically need to avoid doing it for
11368   // class members because the linkage of an anonymous class can
11369   // change if it's later given a typedef name.
11370   if (var->isThisDeclarationADefinition() &&
11371       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11372       var->isExternallyVisible() && var->hasLinkage() &&
11373       !var->isInline() && !var->getDescribedVarTemplate() &&
11374       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11375       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11376                                   var->getLocation())) {
11377     // Find a previous declaration that's not a definition.
11378     VarDecl *prev = var->getPreviousDecl();
11379     while (prev && prev->isThisDeclarationADefinition())
11380       prev = prev->getPreviousDecl();
11381 
11382     if (!prev)
11383       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11384   }
11385 
11386   // Cache the result of checking for constant initialization.
11387   Optional<bool> CacheHasConstInit;
11388   const Expr *CacheCulprit;
11389   auto checkConstInit = [&]() mutable {
11390     if (!CacheHasConstInit)
11391       CacheHasConstInit = var->getInit()->isConstantInitializer(
11392             Context, var->getType()->isReferenceType(), &CacheCulprit);
11393     return *CacheHasConstInit;
11394   };
11395 
11396   if (var->getTLSKind() == VarDecl::TLS_Static) {
11397     if (var->getType().isDestructedType()) {
11398       // GNU C++98 edits for __thread, [basic.start.term]p3:
11399       //   The type of an object with thread storage duration shall not
11400       //   have a non-trivial destructor.
11401       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11402       if (getLangOpts().CPlusPlus11)
11403         Diag(var->getLocation(), diag::note_use_thread_local);
11404     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11405       if (!checkConstInit()) {
11406         // GNU C++98 edits for __thread, [basic.start.init]p4:
11407         //   An object of thread storage duration shall not require dynamic
11408         //   initialization.
11409         // FIXME: Need strict checking here.
11410         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11411           << CacheCulprit->getSourceRange();
11412         if (getLangOpts().CPlusPlus11)
11413           Diag(var->getLocation(), diag::note_use_thread_local);
11414       }
11415     }
11416   }
11417 
11418   // Apply section attributes and pragmas to global variables.
11419   bool GlobalStorage = var->hasGlobalStorage();
11420   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11421       !inTemplateInstantiation()) {
11422     PragmaStack<StringLiteral *> *Stack = nullptr;
11423     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11424     if (var->getType().isConstQualified())
11425       Stack = &ConstSegStack;
11426     else if (!var->getInit()) {
11427       Stack = &BSSSegStack;
11428       SectionFlags |= ASTContext::PSF_Write;
11429     } else {
11430       Stack = &DataSegStack;
11431       SectionFlags |= ASTContext::PSF_Write;
11432     }
11433     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11434       var->addAttr(SectionAttr::CreateImplicit(
11435           Context, SectionAttr::Declspec_allocate,
11436           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11437     }
11438     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11439       if (UnifySection(SA->getName(), SectionFlags, var))
11440         var->dropAttr<SectionAttr>();
11441 
11442     // Apply the init_seg attribute if this has an initializer.  If the
11443     // initializer turns out to not be dynamic, we'll end up ignoring this
11444     // attribute.
11445     if (CurInitSeg && var->getInit())
11446       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11447                                                CurInitSegLoc));
11448   }
11449 
11450   // All the following checks are C++ only.
11451   if (!getLangOpts().CPlusPlus) {
11452       // If this variable must be emitted, add it as an initializer for the
11453       // current module.
11454      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11455        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11456      return;
11457   }
11458 
11459   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11460     CheckCompleteDecompositionDeclaration(DD);
11461 
11462   QualType type = var->getType();
11463   if (type->isDependentType()) return;
11464 
11465   // __block variables might require us to capture a copy-initializer.
11466   if (var->hasAttr<BlocksAttr>()) {
11467     // It's currently invalid to ever have a __block variable with an
11468     // array type; should we diagnose that here?
11469 
11470     // Regardless, we don't want to ignore array nesting when
11471     // constructing this copy.
11472     if (type->isStructureOrClassType()) {
11473       EnterExpressionEvaluationContext scope(
11474           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11475       SourceLocation poi = var->getLocation();
11476       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11477       ExprResult result
11478         = PerformMoveOrCopyInitialization(
11479             InitializedEntity::InitializeBlock(poi, type, false),
11480             var, var->getType(), varRef, /*AllowNRVO=*/true);
11481       if (!result.isInvalid()) {
11482         result = MaybeCreateExprWithCleanups(result);
11483         Expr *init = result.getAs<Expr>();
11484         Context.setBlockVarCopyInits(var, init);
11485       }
11486     }
11487   }
11488 
11489   Expr *Init = var->getInit();
11490   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11491   QualType baseType = Context.getBaseElementType(type);
11492 
11493   if (Init && !Init->isValueDependent()) {
11494     if (var->isConstexpr()) {
11495       SmallVector<PartialDiagnosticAt, 8> Notes;
11496       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11497         SourceLocation DiagLoc = var->getLocation();
11498         // If the note doesn't add any useful information other than a source
11499         // location, fold it into the primary diagnostic.
11500         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11501               diag::note_invalid_subexpr_in_const_expr) {
11502           DiagLoc = Notes[0].first;
11503           Notes.clear();
11504         }
11505         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11506           << var << Init->getSourceRange();
11507         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11508           Diag(Notes[I].first, Notes[I].second);
11509       }
11510     } else if (var->isUsableInConstantExpressions(Context)) {
11511       // Check whether the initializer of a const variable of integral or
11512       // enumeration type is an ICE now, since we can't tell whether it was
11513       // initialized by a constant expression if we check later.
11514       var->checkInitIsICE();
11515     }
11516 
11517     // Don't emit further diagnostics about constexpr globals since they
11518     // were just diagnosed.
11519     if (!var->isConstexpr() && GlobalStorage &&
11520             var->hasAttr<RequireConstantInitAttr>()) {
11521       // FIXME: Need strict checking in C++03 here.
11522       bool DiagErr = getLangOpts().CPlusPlus11
11523           ? !var->checkInitIsICE() : !checkConstInit();
11524       if (DiagErr) {
11525         auto attr = var->getAttr<RequireConstantInitAttr>();
11526         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11527           << Init->getSourceRange();
11528         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11529           << attr->getRange();
11530         if (getLangOpts().CPlusPlus11) {
11531           APValue Value;
11532           SmallVector<PartialDiagnosticAt, 8> Notes;
11533           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11534           for (auto &it : Notes)
11535             Diag(it.first, it.second);
11536         } else {
11537           Diag(CacheCulprit->getExprLoc(),
11538                diag::note_invalid_subexpr_in_const_expr)
11539               << CacheCulprit->getSourceRange();
11540         }
11541       }
11542     }
11543     else if (!var->isConstexpr() && IsGlobal &&
11544              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11545                                     var->getLocation())) {
11546       // Warn about globals which don't have a constant initializer.  Don't
11547       // warn about globals with a non-trivial destructor because we already
11548       // warned about them.
11549       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11550       if (!(RD && !RD->hasTrivialDestructor())) {
11551         if (!checkConstInit())
11552           Diag(var->getLocation(), diag::warn_global_constructor)
11553             << Init->getSourceRange();
11554       }
11555     }
11556   }
11557 
11558   // Require the destructor.
11559   if (const RecordType *recordType = baseType->getAs<RecordType>())
11560     FinalizeVarWithDestructor(var, recordType);
11561 
11562   // If this variable must be emitted, add it as an initializer for the current
11563   // module.
11564   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11565     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11566 }
11567 
11568 /// \brief Determines if a variable's alignment is dependent.
11569 static bool hasDependentAlignment(VarDecl *VD) {
11570   if (VD->getType()->isDependentType())
11571     return true;
11572   for (auto *I : VD->specific_attrs<AlignedAttr>())
11573     if (I->isAlignmentDependent())
11574       return true;
11575   return false;
11576 }
11577 
11578 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11579 /// any semantic actions necessary after any initializer has been attached.
11580 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11581   // Note that we are no longer parsing the initializer for this declaration.
11582   ParsingInitForAutoVars.erase(ThisDecl);
11583 
11584   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11585   if (!VD)
11586     return;
11587 
11588   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11589   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11590       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11591     if (PragmaClangBSSSection.Valid)
11592       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11593                                                             PragmaClangBSSSection.SectionName,
11594                                                             PragmaClangBSSSection.PragmaLocation));
11595     if (PragmaClangDataSection.Valid)
11596       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11597                                                              PragmaClangDataSection.SectionName,
11598                                                              PragmaClangDataSection.PragmaLocation));
11599     if (PragmaClangRodataSection.Valid)
11600       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11601                                                                PragmaClangRodataSection.SectionName,
11602                                                                PragmaClangRodataSection.PragmaLocation));
11603   }
11604 
11605   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11606     for (auto *BD : DD->bindings()) {
11607       FinalizeDeclaration(BD);
11608     }
11609   }
11610 
11611   checkAttributesAfterMerging(*this, *VD);
11612 
11613   // Perform TLS alignment check here after attributes attached to the variable
11614   // which may affect the alignment have been processed. Only perform the check
11615   // if the target has a maximum TLS alignment (zero means no constraints).
11616   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11617     // Protect the check so that it's not performed on dependent types and
11618     // dependent alignments (we can't determine the alignment in that case).
11619     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11620         !VD->isInvalidDecl()) {
11621       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11622       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11623         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11624           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11625           << (unsigned)MaxAlignChars.getQuantity();
11626       }
11627     }
11628   }
11629 
11630   if (VD->isStaticLocal()) {
11631     if (FunctionDecl *FD =
11632             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11633       // Static locals inherit dll attributes from their function.
11634       if (Attr *A = getDLLAttr(FD)) {
11635         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11636         NewAttr->setInherited(true);
11637         VD->addAttr(NewAttr);
11638       }
11639       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11640       // function, only __shared__ variables may be declared with
11641       // static storage class.
11642       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11643           CUDADiagIfDeviceCode(VD->getLocation(),
11644                                diag::err_device_static_local_var)
11645               << CurrentCUDATarget())
11646         VD->setInvalidDecl();
11647     }
11648   }
11649 
11650   // Perform check for initializers of device-side global variables.
11651   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11652   // 7.5). We must also apply the same checks to all __shared__
11653   // variables whether they are local or not. CUDA also allows
11654   // constant initializers for __constant__ and __device__ variables.
11655   if (getLangOpts().CUDA) {
11656     const Expr *Init = VD->getInit();
11657     if (Init && VD->hasGlobalStorage()) {
11658       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11659           VD->hasAttr<CUDASharedAttr>()) {
11660         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11661         bool AllowedInit = false;
11662         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11663           AllowedInit =
11664               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11665         // We'll allow constant initializers even if it's a non-empty
11666         // constructor according to CUDA rules. This deviates from NVCC,
11667         // but allows us to handle things like constexpr constructors.
11668         if (!AllowedInit &&
11669             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11670           AllowedInit = VD->getInit()->isConstantInitializer(
11671               Context, VD->getType()->isReferenceType());
11672 
11673         // Also make sure that destructor, if there is one, is empty.
11674         if (AllowedInit)
11675           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11676             AllowedInit =
11677                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11678 
11679         if (!AllowedInit) {
11680           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11681                                       ? diag::err_shared_var_init
11682                                       : diag::err_dynamic_var_init)
11683               << Init->getSourceRange();
11684           VD->setInvalidDecl();
11685         }
11686       } else {
11687         // This is a host-side global variable.  Check that the initializer is
11688         // callable from the host side.
11689         const FunctionDecl *InitFn = nullptr;
11690         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11691           InitFn = CE->getConstructor();
11692         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11693           InitFn = CE->getDirectCallee();
11694         }
11695         if (InitFn) {
11696           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11697           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11698             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11699                 << InitFnTarget << InitFn;
11700             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11701             VD->setInvalidDecl();
11702           }
11703         }
11704       }
11705     }
11706   }
11707 
11708   // Grab the dllimport or dllexport attribute off of the VarDecl.
11709   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11710 
11711   // Imported static data members cannot be defined out-of-line.
11712   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11713     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11714         VD->isThisDeclarationADefinition()) {
11715       // We allow definitions of dllimport class template static data members
11716       // with a warning.
11717       CXXRecordDecl *Context =
11718         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11719       bool IsClassTemplateMember =
11720           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11721           Context->getDescribedClassTemplate();
11722 
11723       Diag(VD->getLocation(),
11724            IsClassTemplateMember
11725                ? diag::warn_attribute_dllimport_static_field_definition
11726                : diag::err_attribute_dllimport_static_field_definition);
11727       Diag(IA->getLocation(), diag::note_attribute);
11728       if (!IsClassTemplateMember)
11729         VD->setInvalidDecl();
11730     }
11731   }
11732 
11733   // dllimport/dllexport variables cannot be thread local, their TLS index
11734   // isn't exported with the variable.
11735   if (DLLAttr && VD->getTLSKind()) {
11736     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11737     if (F && getDLLAttr(F)) {
11738       assert(VD->isStaticLocal());
11739       // But if this is a static local in a dlimport/dllexport function, the
11740       // function will never be inlined, which means the var would never be
11741       // imported, so having it marked import/export is safe.
11742     } else {
11743       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11744                                                                     << DLLAttr;
11745       VD->setInvalidDecl();
11746     }
11747   }
11748 
11749   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11750     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11751       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11752       VD->dropAttr<UsedAttr>();
11753     }
11754   }
11755 
11756   const DeclContext *DC = VD->getDeclContext();
11757   // If there's a #pragma GCC visibility in scope, and this isn't a class
11758   // member, set the visibility of this variable.
11759   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11760     AddPushedVisibilityAttribute(VD);
11761 
11762   // FIXME: Warn on unused var template partial specializations.
11763   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11764     MarkUnusedFileScopedDecl(VD);
11765 
11766   // Now we have parsed the initializer and can update the table of magic
11767   // tag values.
11768   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11769       !VD->getType()->isIntegralOrEnumerationType())
11770     return;
11771 
11772   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11773     const Expr *MagicValueExpr = VD->getInit();
11774     if (!MagicValueExpr) {
11775       continue;
11776     }
11777     llvm::APSInt MagicValueInt;
11778     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11779       Diag(I->getRange().getBegin(),
11780            diag::err_type_tag_for_datatype_not_ice)
11781         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11782       continue;
11783     }
11784     if (MagicValueInt.getActiveBits() > 64) {
11785       Diag(I->getRange().getBegin(),
11786            diag::err_type_tag_for_datatype_too_large)
11787         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11788       continue;
11789     }
11790     uint64_t MagicValue = MagicValueInt.getZExtValue();
11791     RegisterTypeTagForDatatype(I->getArgumentKind(),
11792                                MagicValue,
11793                                I->getMatchingCType(),
11794                                I->getLayoutCompatible(),
11795                                I->getMustBeNull());
11796   }
11797 }
11798 
11799 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11800   auto *VD = dyn_cast<VarDecl>(DD);
11801   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11802 }
11803 
11804 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11805                                                    ArrayRef<Decl *> Group) {
11806   SmallVector<Decl*, 8> Decls;
11807 
11808   if (DS.isTypeSpecOwned())
11809     Decls.push_back(DS.getRepAsDecl());
11810 
11811   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11812   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11813   bool DiagnosedMultipleDecomps = false;
11814   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11815   bool DiagnosedNonDeducedAuto = false;
11816 
11817   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11818     if (Decl *D = Group[i]) {
11819       // For declarators, there are some additional syntactic-ish checks we need
11820       // to perform.
11821       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11822         if (!FirstDeclaratorInGroup)
11823           FirstDeclaratorInGroup = DD;
11824         if (!FirstDecompDeclaratorInGroup)
11825           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11826         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11827             !hasDeducedAuto(DD))
11828           FirstNonDeducedAutoInGroup = DD;
11829 
11830         if (FirstDeclaratorInGroup != DD) {
11831           // A decomposition declaration cannot be combined with any other
11832           // declaration in the same group.
11833           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11834             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11835                  diag::err_decomp_decl_not_alone)
11836                 << FirstDeclaratorInGroup->getSourceRange()
11837                 << DD->getSourceRange();
11838             DiagnosedMultipleDecomps = true;
11839           }
11840 
11841           // A declarator that uses 'auto' in any way other than to declare a
11842           // variable with a deduced type cannot be combined with any other
11843           // declarator in the same group.
11844           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11845             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11846                  diag::err_auto_non_deduced_not_alone)
11847                 << FirstNonDeducedAutoInGroup->getType()
11848                        ->hasAutoForTrailingReturnType()
11849                 << FirstDeclaratorInGroup->getSourceRange()
11850                 << DD->getSourceRange();
11851             DiagnosedNonDeducedAuto = true;
11852           }
11853         }
11854       }
11855 
11856       Decls.push_back(D);
11857     }
11858   }
11859 
11860   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11861     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11862       handleTagNumbering(Tag, S);
11863       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11864           getLangOpts().CPlusPlus)
11865         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11866     }
11867   }
11868 
11869   return BuildDeclaratorGroup(Decls);
11870 }
11871 
11872 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11873 /// group, performing any necessary semantic checking.
11874 Sema::DeclGroupPtrTy
11875 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11876   // C++14 [dcl.spec.auto]p7: (DR1347)
11877   //   If the type that replaces the placeholder type is not the same in each
11878   //   deduction, the program is ill-formed.
11879   if (Group.size() > 1) {
11880     QualType Deduced;
11881     VarDecl *DeducedDecl = nullptr;
11882     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11883       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11884       if (!D || D->isInvalidDecl())
11885         break;
11886       DeducedType *DT = D->getType()->getContainedDeducedType();
11887       if (!DT || DT->getDeducedType().isNull())
11888         continue;
11889       if (Deduced.isNull()) {
11890         Deduced = DT->getDeducedType();
11891         DeducedDecl = D;
11892       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11893         auto *AT = dyn_cast<AutoType>(DT);
11894         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11895              diag::err_auto_different_deductions)
11896           << (AT ? (unsigned)AT->getKeyword() : 3)
11897           << Deduced << DeducedDecl->getDeclName()
11898           << DT->getDeducedType() << D->getDeclName()
11899           << DeducedDecl->getInit()->getSourceRange()
11900           << D->getInit()->getSourceRange();
11901         D->setInvalidDecl();
11902         break;
11903       }
11904     }
11905   }
11906 
11907   ActOnDocumentableDecls(Group);
11908 
11909   return DeclGroupPtrTy::make(
11910       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11911 }
11912 
11913 void Sema::ActOnDocumentableDecl(Decl *D) {
11914   ActOnDocumentableDecls(D);
11915 }
11916 
11917 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11918   // Don't parse the comment if Doxygen diagnostics are ignored.
11919   if (Group.empty() || !Group[0])
11920     return;
11921 
11922   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11923                       Group[0]->getLocation()) &&
11924       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11925                       Group[0]->getLocation()))
11926     return;
11927 
11928   if (Group.size() >= 2) {
11929     // This is a decl group.  Normally it will contain only declarations
11930     // produced from declarator list.  But in case we have any definitions or
11931     // additional declaration references:
11932     //   'typedef struct S {} S;'
11933     //   'typedef struct S *S;'
11934     //   'struct S *pS;'
11935     // FinalizeDeclaratorGroup adds these as separate declarations.
11936     Decl *MaybeTagDecl = Group[0];
11937     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11938       Group = Group.slice(1);
11939     }
11940   }
11941 
11942   // See if there are any new comments that are not attached to a decl.
11943   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11944   if (!Comments.empty() &&
11945       !Comments.back()->isAttached()) {
11946     // There is at least one comment that not attached to a decl.
11947     // Maybe it should be attached to one of these decls?
11948     //
11949     // Note that this way we pick up not only comments that precede the
11950     // declaration, but also comments that *follow* the declaration -- thanks to
11951     // the lookahead in the lexer: we've consumed the semicolon and looked
11952     // ahead through comments.
11953     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11954       Context.getCommentForDecl(Group[i], &PP);
11955   }
11956 }
11957 
11958 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11959 /// to introduce parameters into function prototype scope.
11960 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11961   const DeclSpec &DS = D.getDeclSpec();
11962 
11963   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11964 
11965   // C++03 [dcl.stc]p2 also permits 'auto'.
11966   StorageClass SC = SC_None;
11967   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11968     SC = SC_Register;
11969     // In C++11, the 'register' storage class specifier is deprecated.
11970     // In C++17, it is not allowed, but we tolerate it as an extension.
11971     if (getLangOpts().CPlusPlus11) {
11972       Diag(DS.getStorageClassSpecLoc(),
11973            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
11974                                      : diag::warn_deprecated_register)
11975         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11976     }
11977   } else if (getLangOpts().CPlusPlus &&
11978              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11979     SC = SC_Auto;
11980   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11981     Diag(DS.getStorageClassSpecLoc(),
11982          diag::err_invalid_storage_class_in_func_decl);
11983     D.getMutableDeclSpec().ClearStorageClassSpecs();
11984   }
11985 
11986   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11987     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11988       << DeclSpec::getSpecifierName(TSCS);
11989   if (DS.isInlineSpecified())
11990     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11991         << getLangOpts().CPlusPlus17;
11992   if (DS.isConstexprSpecified())
11993     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11994       << 0;
11995 
11996   DiagnoseFunctionSpecifiers(DS);
11997 
11998   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11999   QualType parmDeclType = TInfo->getType();
12000 
12001   if (getLangOpts().CPlusPlus) {
12002     // Check that there are no default arguments inside the type of this
12003     // parameter.
12004     CheckExtraCXXDefaultArguments(D);
12005 
12006     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12007     if (D.getCXXScopeSpec().isSet()) {
12008       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12009         << D.getCXXScopeSpec().getRange();
12010       D.getCXXScopeSpec().clear();
12011     }
12012   }
12013 
12014   // Ensure we have a valid name
12015   IdentifierInfo *II = nullptr;
12016   if (D.hasName()) {
12017     II = D.getIdentifier();
12018     if (!II) {
12019       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12020         << GetNameForDeclarator(D).getName();
12021       D.setInvalidType(true);
12022     }
12023   }
12024 
12025   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12026   if (II) {
12027     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12028                    ForVisibleRedeclaration);
12029     LookupName(R, S);
12030     if (R.isSingleResult()) {
12031       NamedDecl *PrevDecl = R.getFoundDecl();
12032       if (PrevDecl->isTemplateParameter()) {
12033         // Maybe we will complain about the shadowed template parameter.
12034         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12035         // Just pretend that we didn't see the previous declaration.
12036         PrevDecl = nullptr;
12037       } else if (S->isDeclScope(PrevDecl)) {
12038         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12039         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12040 
12041         // Recover by removing the name
12042         II = nullptr;
12043         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12044         D.setInvalidType(true);
12045       }
12046     }
12047   }
12048 
12049   // Temporarily put parameter variables in the translation unit, not
12050   // the enclosing context.  This prevents them from accidentally
12051   // looking like class members in C++.
12052   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12053                                     D.getLocStart(),
12054                                     D.getIdentifierLoc(), II,
12055                                     parmDeclType, TInfo,
12056                                     SC);
12057 
12058   if (D.isInvalidType())
12059     New->setInvalidDecl();
12060 
12061   assert(S->isFunctionPrototypeScope());
12062   assert(S->getFunctionPrototypeDepth() >= 1);
12063   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12064                     S->getNextFunctionPrototypeIndex());
12065 
12066   // Add the parameter declaration into this scope.
12067   S->AddDecl(New);
12068   if (II)
12069     IdResolver.AddDecl(New);
12070 
12071   ProcessDeclAttributes(S, New, D);
12072 
12073   if (D.getDeclSpec().isModulePrivateSpecified())
12074     Diag(New->getLocation(), diag::err_module_private_local)
12075       << 1 << New->getDeclName()
12076       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12077       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12078 
12079   if (New->hasAttr<BlocksAttr>()) {
12080     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12081   }
12082   return New;
12083 }
12084 
12085 /// \brief Synthesizes a variable for a parameter arising from a
12086 /// typedef.
12087 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12088                                               SourceLocation Loc,
12089                                               QualType T) {
12090   /* FIXME: setting StartLoc == Loc.
12091      Would it be worth to modify callers so as to provide proper source
12092      location for the unnamed parameters, embedding the parameter's type? */
12093   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12094                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12095                                            SC_None, nullptr);
12096   Param->setImplicit();
12097   return Param;
12098 }
12099 
12100 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12101   // Don't diagnose unused-parameter errors in template instantiations; we
12102   // will already have done so in the template itself.
12103   if (inTemplateInstantiation())
12104     return;
12105 
12106   for (const ParmVarDecl *Parameter : Parameters) {
12107     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12108         !Parameter->hasAttr<UnusedAttr>()) {
12109       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12110         << Parameter->getDeclName();
12111     }
12112   }
12113 }
12114 
12115 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12116     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12117   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12118     return;
12119 
12120   // Warn if the return value is pass-by-value and larger than the specified
12121   // threshold.
12122   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12123     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12124     if (Size > LangOpts.NumLargeByValueCopy)
12125       Diag(D->getLocation(), diag::warn_return_value_size)
12126           << D->getDeclName() << Size;
12127   }
12128 
12129   // Warn if any parameter is pass-by-value and larger than the specified
12130   // threshold.
12131   for (const ParmVarDecl *Parameter : Parameters) {
12132     QualType T = Parameter->getType();
12133     if (T->isDependentType() || !T.isPODType(Context))
12134       continue;
12135     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12136     if (Size > LangOpts.NumLargeByValueCopy)
12137       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12138           << Parameter->getDeclName() << Size;
12139   }
12140 }
12141 
12142 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12143                                   SourceLocation NameLoc, IdentifierInfo *Name,
12144                                   QualType T, TypeSourceInfo *TSInfo,
12145                                   StorageClass SC) {
12146   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12147   if (getLangOpts().ObjCAutoRefCount &&
12148       T.getObjCLifetime() == Qualifiers::OCL_None &&
12149       T->isObjCLifetimeType()) {
12150 
12151     Qualifiers::ObjCLifetime lifetime;
12152 
12153     // Special cases for arrays:
12154     //   - if it's const, use __unsafe_unretained
12155     //   - otherwise, it's an error
12156     if (T->isArrayType()) {
12157       if (!T.isConstQualified()) {
12158         DelayedDiagnostics.add(
12159             sema::DelayedDiagnostic::makeForbiddenType(
12160             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12161       }
12162       lifetime = Qualifiers::OCL_ExplicitNone;
12163     } else {
12164       lifetime = T->getObjCARCImplicitLifetime();
12165     }
12166     T = Context.getLifetimeQualifiedType(T, lifetime);
12167   }
12168 
12169   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12170                                          Context.getAdjustedParameterType(T),
12171                                          TSInfo, SC, nullptr);
12172 
12173   // Parameters can not be abstract class types.
12174   // For record types, this is done by the AbstractClassUsageDiagnoser once
12175   // the class has been completely parsed.
12176   if (!CurContext->isRecord() &&
12177       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12178                              AbstractParamType))
12179     New->setInvalidDecl();
12180 
12181   // Parameter declarators cannot be interface types. All ObjC objects are
12182   // passed by reference.
12183   if (T->isObjCObjectType()) {
12184     SourceLocation TypeEndLoc =
12185         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12186     Diag(NameLoc,
12187          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12188       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12189     T = Context.getObjCObjectPointerType(T);
12190     New->setType(T);
12191   }
12192 
12193   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12194   // duration shall not be qualified by an address-space qualifier."
12195   // Since all parameters have automatic store duration, they can not have
12196   // an address space.
12197   if (T.getAddressSpace() != LangAS::Default &&
12198       // OpenCL allows function arguments declared to be an array of a type
12199       // to be qualified with an address space.
12200       !(getLangOpts().OpenCL &&
12201         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12202     Diag(NameLoc, diag::err_arg_with_address_space);
12203     New->setInvalidDecl();
12204   }
12205 
12206   return New;
12207 }
12208 
12209 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12210                                            SourceLocation LocAfterDecls) {
12211   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12212 
12213   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12214   // for a K&R function.
12215   if (!FTI.hasPrototype) {
12216     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12217       --i;
12218       if (FTI.Params[i].Param == nullptr) {
12219         SmallString<256> Code;
12220         llvm::raw_svector_ostream(Code)
12221             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12222         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12223             << FTI.Params[i].Ident
12224             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12225 
12226         // Implicitly declare the argument as type 'int' for lack of a better
12227         // type.
12228         AttributeFactory attrs;
12229         DeclSpec DS(attrs);
12230         const char* PrevSpec; // unused
12231         unsigned DiagID; // unused
12232         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12233                            DiagID, Context.getPrintingPolicy());
12234         // Use the identifier location for the type source range.
12235         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12236         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12237         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12238         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12239         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12240       }
12241     }
12242   }
12243 }
12244 
12245 Decl *
12246 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12247                               MultiTemplateParamsArg TemplateParameterLists,
12248                               SkipBodyInfo *SkipBody) {
12249   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12250   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12251   Scope *ParentScope = FnBodyScope->getParent();
12252 
12253   D.setFunctionDefinitionKind(FDK_Definition);
12254   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12255   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12256 }
12257 
12258 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12259   Consumer.HandleInlineFunctionDefinition(D);
12260 }
12261 
12262 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12263                              const FunctionDecl*& PossibleZeroParamPrototype) {
12264   // Don't warn about invalid declarations.
12265   if (FD->isInvalidDecl())
12266     return false;
12267 
12268   // Or declarations that aren't global.
12269   if (!FD->isGlobal())
12270     return false;
12271 
12272   // Don't warn about C++ member functions.
12273   if (isa<CXXMethodDecl>(FD))
12274     return false;
12275 
12276   // Don't warn about 'main'.
12277   if (FD->isMain())
12278     return false;
12279 
12280   // Don't warn about inline functions.
12281   if (FD->isInlined())
12282     return false;
12283 
12284   // Don't warn about function templates.
12285   if (FD->getDescribedFunctionTemplate())
12286     return false;
12287 
12288   // Don't warn about function template specializations.
12289   if (FD->isFunctionTemplateSpecialization())
12290     return false;
12291 
12292   // Don't warn for OpenCL kernels.
12293   if (FD->hasAttr<OpenCLKernelAttr>())
12294     return false;
12295 
12296   // Don't warn on explicitly deleted functions.
12297   if (FD->isDeleted())
12298     return false;
12299 
12300   bool MissingPrototype = true;
12301   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12302        Prev; Prev = Prev->getPreviousDecl()) {
12303     // Ignore any declarations that occur in function or method
12304     // scope, because they aren't visible from the header.
12305     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12306       continue;
12307 
12308     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12309     if (FD->getNumParams() == 0)
12310       PossibleZeroParamPrototype = Prev;
12311     break;
12312   }
12313 
12314   return MissingPrototype;
12315 }
12316 
12317 void
12318 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12319                                    const FunctionDecl *EffectiveDefinition,
12320                                    SkipBodyInfo *SkipBody) {
12321   const FunctionDecl *Definition = EffectiveDefinition;
12322   if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12323     // If this is a friend function defined in a class template, it does not
12324     // have a body until it is used, nevertheless it is a definition, see
12325     // [temp.inst]p2:
12326     //
12327     // ... for the purpose of determining whether an instantiated redeclaration
12328     // is valid according to [basic.def.odr] and [class.mem], a declaration that
12329     // corresponds to a definition in the template is considered to be a
12330     // definition.
12331     //
12332     // The following code must produce redefinition error:
12333     //
12334     //     template<typename T> struct C20 { friend void func_20() {} };
12335     //     C20<int> c20i;
12336     //     void func_20() {}
12337     //
12338     for (auto I : FD->redecls()) {
12339       if (I != FD && !I->isInvalidDecl() &&
12340           I->getFriendObjectKind() != Decl::FOK_None) {
12341         if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12342           if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12343             // A merged copy of the same function, instantiated as a member of
12344             // the same class, is OK.
12345             if (declaresSameEntity(OrigFD, Original) &&
12346                 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12347                                    cast<Decl>(FD->getLexicalDeclContext())))
12348               continue;
12349           }
12350 
12351           if (Original->isThisDeclarationADefinition()) {
12352             Definition = I;
12353             break;
12354           }
12355         }
12356       }
12357     }
12358   }
12359   if (!Definition)
12360     return;
12361 
12362   if (canRedefineFunction(Definition, getLangOpts()))
12363     return;
12364 
12365   // Don't emit an error when this is redefinition of a typo-corrected
12366   // definition.
12367   if (TypoCorrectedFunctionDefinitions.count(Definition))
12368     return;
12369 
12370   // If we don't have a visible definition of the function, and it's inline or
12371   // a template, skip the new definition.
12372   if (SkipBody && !hasVisibleDefinition(Definition) &&
12373       (Definition->getFormalLinkage() == InternalLinkage ||
12374        Definition->isInlined() ||
12375        Definition->getDescribedFunctionTemplate() ||
12376        Definition->getNumTemplateParameterLists())) {
12377     SkipBody->ShouldSkip = true;
12378     if (auto *TD = Definition->getDescribedFunctionTemplate())
12379       makeMergedDefinitionVisible(TD);
12380     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12381     return;
12382   }
12383 
12384   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12385       Definition->getStorageClass() == SC_Extern)
12386     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12387         << FD->getDeclName() << getLangOpts().CPlusPlus;
12388   else
12389     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12390 
12391   Diag(Definition->getLocation(), diag::note_previous_definition);
12392   FD->setInvalidDecl();
12393 }
12394 
12395 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12396                                    Sema &S) {
12397   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12398 
12399   LambdaScopeInfo *LSI = S.PushLambdaScope();
12400   LSI->CallOperator = CallOperator;
12401   LSI->Lambda = LambdaClass;
12402   LSI->ReturnType = CallOperator->getReturnType();
12403   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12404 
12405   if (LCD == LCD_None)
12406     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12407   else if (LCD == LCD_ByCopy)
12408     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12409   else if (LCD == LCD_ByRef)
12410     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12411   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12412 
12413   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12414   LSI->Mutable = !CallOperator->isConst();
12415 
12416   // Add the captures to the LSI so they can be noted as already
12417   // captured within tryCaptureVar.
12418   auto I = LambdaClass->field_begin();
12419   for (const auto &C : LambdaClass->captures()) {
12420     if (C.capturesVariable()) {
12421       VarDecl *VD = C.getCapturedVar();
12422       if (VD->isInitCapture())
12423         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12424       QualType CaptureType = VD->getType();
12425       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12426       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12427           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12428           /*EllipsisLoc*/C.isPackExpansion()
12429                          ? C.getEllipsisLoc() : SourceLocation(),
12430           CaptureType, /*Expr*/ nullptr);
12431 
12432     } else if (C.capturesThis()) {
12433       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12434                               /*Expr*/ nullptr,
12435                               C.getCaptureKind() == LCK_StarThis);
12436     } else {
12437       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12438     }
12439     ++I;
12440   }
12441 }
12442 
12443 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12444                                     SkipBodyInfo *SkipBody) {
12445   if (!D) {
12446     // Parsing the function declaration failed in some way. Push on a fake scope
12447     // anyway so we can try to parse the function body.
12448     PushFunctionScope();
12449     return D;
12450   }
12451 
12452   FunctionDecl *FD = nullptr;
12453 
12454   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12455     FD = FunTmpl->getTemplatedDecl();
12456   else
12457     FD = cast<FunctionDecl>(D);
12458 
12459   // Check for defining attributes before the check for redefinition.
12460   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12461     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12462     FD->dropAttr<AliasAttr>();
12463     FD->setInvalidDecl();
12464   }
12465   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12466     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12467     FD->dropAttr<IFuncAttr>();
12468     FD->setInvalidDecl();
12469   }
12470 
12471   // See if this is a redefinition. If 'will have body' is already set, then
12472   // these checks were already performed when it was set.
12473   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12474     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12475 
12476     // If we're skipping the body, we're done. Don't enter the scope.
12477     if (SkipBody && SkipBody->ShouldSkip)
12478       return D;
12479   }
12480 
12481   // Mark this function as "will have a body eventually".  This lets users to
12482   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12483   // this function.
12484   FD->setWillHaveBody();
12485 
12486   // If we are instantiating a generic lambda call operator, push
12487   // a LambdaScopeInfo onto the function stack.  But use the information
12488   // that's already been calculated (ActOnLambdaExpr) to prime the current
12489   // LambdaScopeInfo.
12490   // When the template operator is being specialized, the LambdaScopeInfo,
12491   // has to be properly restored so that tryCaptureVariable doesn't try
12492   // and capture any new variables. In addition when calculating potential
12493   // captures during transformation of nested lambdas, it is necessary to
12494   // have the LSI properly restored.
12495   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12496     assert(inTemplateInstantiation() &&
12497            "There should be an active template instantiation on the stack "
12498            "when instantiating a generic lambda!");
12499     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12500   } else {
12501     // Enter a new function scope
12502     PushFunctionScope();
12503   }
12504 
12505   // Builtin functions cannot be defined.
12506   if (unsigned BuiltinID = FD->getBuiltinID()) {
12507     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12508         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12509       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12510       FD->setInvalidDecl();
12511     }
12512   }
12513 
12514   // The return type of a function definition must be complete
12515   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12516   QualType ResultType = FD->getReturnType();
12517   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12518       !FD->isInvalidDecl() &&
12519       RequireCompleteType(FD->getLocation(), ResultType,
12520                           diag::err_func_def_incomplete_result))
12521     FD->setInvalidDecl();
12522 
12523   if (FnBodyScope)
12524     PushDeclContext(FnBodyScope, FD);
12525 
12526   // Check the validity of our function parameters
12527   CheckParmsForFunctionDef(FD->parameters(),
12528                            /*CheckParameterNames=*/true);
12529 
12530   // Add non-parameter declarations already in the function to the current
12531   // scope.
12532   if (FnBodyScope) {
12533     for (Decl *NPD : FD->decls()) {
12534       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12535       if (!NonParmDecl)
12536         continue;
12537       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12538              "parameters should not be in newly created FD yet");
12539 
12540       // If the decl has a name, make it accessible in the current scope.
12541       if (NonParmDecl->getDeclName())
12542         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12543 
12544       // Similarly, dive into enums and fish their constants out, making them
12545       // accessible in this scope.
12546       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12547         for (auto *EI : ED->enumerators())
12548           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12549       }
12550     }
12551   }
12552 
12553   // Introduce our parameters into the function scope
12554   for (auto Param : FD->parameters()) {
12555     Param->setOwningFunction(FD);
12556 
12557     // If this has an identifier, add it to the scope stack.
12558     if (Param->getIdentifier() && FnBodyScope) {
12559       CheckShadow(FnBodyScope, Param);
12560 
12561       PushOnScopeChains(Param, FnBodyScope);
12562     }
12563   }
12564 
12565   // Ensure that the function's exception specification is instantiated.
12566   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12567     ResolveExceptionSpec(D->getLocation(), FPT);
12568 
12569   // dllimport cannot be applied to non-inline function definitions.
12570   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12571       !FD->isTemplateInstantiation()) {
12572     assert(!FD->hasAttr<DLLExportAttr>());
12573     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12574     FD->setInvalidDecl();
12575     return D;
12576   }
12577   // We want to attach documentation to original Decl (which might be
12578   // a function template).
12579   ActOnDocumentableDecl(D);
12580   if (getCurLexicalContext()->isObjCContainer() &&
12581       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12582       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12583     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12584 
12585   return D;
12586 }
12587 
12588 /// \brief Given the set of return statements within a function body,
12589 /// compute the variables that are subject to the named return value
12590 /// optimization.
12591 ///
12592 /// Each of the variables that is subject to the named return value
12593 /// optimization will be marked as NRVO variables in the AST, and any
12594 /// return statement that has a marked NRVO variable as its NRVO candidate can
12595 /// use the named return value optimization.
12596 ///
12597 /// This function applies a very simplistic algorithm for NRVO: if every return
12598 /// statement in the scope of a variable has the same NRVO candidate, that
12599 /// candidate is an NRVO variable.
12600 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12601   ReturnStmt **Returns = Scope->Returns.data();
12602 
12603   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12604     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12605       if (!NRVOCandidate->isNRVOVariable())
12606         Returns[I]->setNRVOCandidate(nullptr);
12607     }
12608   }
12609 }
12610 
12611 bool Sema::canDelayFunctionBody(const Declarator &D) {
12612   // We can't delay parsing the body of a constexpr function template (yet).
12613   if (D.getDeclSpec().isConstexprSpecified())
12614     return false;
12615 
12616   // We can't delay parsing the body of a function template with a deduced
12617   // return type (yet).
12618   if (D.getDeclSpec().hasAutoTypeSpec()) {
12619     // If the placeholder introduces a non-deduced trailing return type,
12620     // we can still delay parsing it.
12621     if (D.getNumTypeObjects()) {
12622       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12623       if (Outer.Kind == DeclaratorChunk::Function &&
12624           Outer.Fun.hasTrailingReturnType()) {
12625         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12626         return Ty.isNull() || !Ty->isUndeducedType();
12627       }
12628     }
12629     return false;
12630   }
12631 
12632   return true;
12633 }
12634 
12635 bool Sema::canSkipFunctionBody(Decl *D) {
12636   // We cannot skip the body of a function (or function template) which is
12637   // constexpr, since we may need to evaluate its body in order to parse the
12638   // rest of the file.
12639   // We cannot skip the body of a function with an undeduced return type,
12640   // because any callers of that function need to know the type.
12641   if (const FunctionDecl *FD = D->getAsFunction())
12642     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12643       return false;
12644   return Consumer.shouldSkipFunctionBody(D);
12645 }
12646 
12647 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12648   if (!Decl)
12649     return nullptr;
12650   if (FunctionDecl *FD = Decl->getAsFunction())
12651     FD->setHasSkippedBody();
12652   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12653     MD->setHasSkippedBody();
12654   return Decl;
12655 }
12656 
12657 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12658   return ActOnFinishFunctionBody(D, BodyArg, false);
12659 }
12660 
12661 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12662                                     bool IsInstantiation) {
12663   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12664 
12665   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12666   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12667 
12668   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12669     CheckCompletedCoroutineBody(FD, Body);
12670 
12671   if (FD) {
12672     FD->setBody(Body);
12673     FD->setWillHaveBody(false);
12674 
12675     if (getLangOpts().CPlusPlus14) {
12676       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12677           FD->getReturnType()->isUndeducedType()) {
12678         // If the function has a deduced result type but contains no 'return'
12679         // statements, the result type as written must be exactly 'auto', and
12680         // the deduced result type is 'void'.
12681         if (!FD->getReturnType()->getAs<AutoType>()) {
12682           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12683               << FD->getReturnType();
12684           FD->setInvalidDecl();
12685         } else {
12686           // Substitute 'void' for the 'auto' in the type.
12687           TypeLoc ResultType = getReturnTypeLoc(FD);
12688           Context.adjustDeducedFunctionResultType(
12689               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12690         }
12691       }
12692     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12693       // In C++11, we don't use 'auto' deduction rules for lambda call
12694       // operators because we don't support return type deduction.
12695       auto *LSI = getCurLambda();
12696       if (LSI->HasImplicitReturnType) {
12697         deduceClosureReturnType(*LSI);
12698 
12699         // C++11 [expr.prim.lambda]p4:
12700         //   [...] if there are no return statements in the compound-statement
12701         //   [the deduced type is] the type void
12702         QualType RetType =
12703             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12704 
12705         // Update the return type to the deduced type.
12706         const FunctionProtoType *Proto =
12707             FD->getType()->getAs<FunctionProtoType>();
12708         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12709                                             Proto->getExtProtoInfo()));
12710       }
12711     }
12712 
12713     // If the function implicitly returns zero (like 'main') or is naked,
12714     // don't complain about missing return statements.
12715     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12716       WP.disableCheckFallThrough();
12717 
12718     // MSVC permits the use of pure specifier (=0) on function definition,
12719     // defined at class scope, warn about this non-standard construct.
12720     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12721       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12722 
12723     if (!FD->isInvalidDecl()) {
12724       // Don't diagnose unused parameters of defaulted or deleted functions.
12725       if (!FD->isDeleted() && !FD->isDefaulted())
12726         DiagnoseUnusedParameters(FD->parameters());
12727       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12728                                              FD->getReturnType(), FD);
12729 
12730       // If this is a structor, we need a vtable.
12731       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12732         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12733       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12734         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12735 
12736       // Try to apply the named return value optimization. We have to check
12737       // if we can do this here because lambdas keep return statements around
12738       // to deduce an implicit return type.
12739       if (FD->getReturnType()->isRecordType() &&
12740           (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
12741         computeNRVO(Body, getCurFunction());
12742     }
12743 
12744     // GNU warning -Wmissing-prototypes:
12745     //   Warn if a global function is defined without a previous
12746     //   prototype declaration. This warning is issued even if the
12747     //   definition itself provides a prototype. The aim is to detect
12748     //   global functions that fail to be declared in header files.
12749     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12750     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12751       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12752 
12753       if (PossibleZeroParamPrototype) {
12754         // We found a declaration that is not a prototype,
12755         // but that could be a zero-parameter prototype
12756         if (TypeSourceInfo *TI =
12757                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12758           TypeLoc TL = TI->getTypeLoc();
12759           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12760             Diag(PossibleZeroParamPrototype->getLocation(),
12761                  diag::note_declaration_not_a_prototype)
12762                 << PossibleZeroParamPrototype
12763                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12764         }
12765       }
12766 
12767       // GNU warning -Wstrict-prototypes
12768       //   Warn if K&R function is defined without a previous declaration.
12769       //   This warning is issued only if the definition itself does not provide
12770       //   a prototype. Only K&R definitions do not provide a prototype.
12771       //   An empty list in a function declarator that is part of a definition
12772       //   of that function specifies that the function has no parameters
12773       //   (C99 6.7.5.3p14)
12774       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12775           !LangOpts.CPlusPlus) {
12776         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12777         TypeLoc TL = TI->getTypeLoc();
12778         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12779         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12780       }
12781     }
12782 
12783     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12784       const CXXMethodDecl *KeyFunction;
12785       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12786           MD->isVirtual() &&
12787           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12788           MD == KeyFunction->getCanonicalDecl()) {
12789         // Update the key-function state if necessary for this ABI.
12790         if (FD->isInlined() &&
12791             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12792           Context.setNonKeyFunction(MD);
12793 
12794           // If the newly-chosen key function is already defined, then we
12795           // need to mark the vtable as used retroactively.
12796           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12797           const FunctionDecl *Definition;
12798           if (KeyFunction && KeyFunction->isDefined(Definition))
12799             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12800         } else {
12801           // We just defined they key function; mark the vtable as used.
12802           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12803         }
12804       }
12805     }
12806 
12807     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12808            "Function parsing confused");
12809   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12810     assert(MD == getCurMethodDecl() && "Method parsing confused");
12811     MD->setBody(Body);
12812     if (!MD->isInvalidDecl()) {
12813       DiagnoseUnusedParameters(MD->parameters());
12814       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12815                                              MD->getReturnType(), MD);
12816 
12817       if (Body)
12818         computeNRVO(Body, getCurFunction());
12819     }
12820     if (getCurFunction()->ObjCShouldCallSuper) {
12821       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12822         << MD->getSelector().getAsString();
12823       getCurFunction()->ObjCShouldCallSuper = false;
12824     }
12825     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12826       const ObjCMethodDecl *InitMethod = nullptr;
12827       bool isDesignated =
12828           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12829       assert(isDesignated && InitMethod);
12830       (void)isDesignated;
12831 
12832       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12833         auto IFace = MD->getClassInterface();
12834         if (!IFace)
12835           return false;
12836         auto SuperD = IFace->getSuperClass();
12837         if (!SuperD)
12838           return false;
12839         return SuperD->getIdentifier() ==
12840             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12841       };
12842       // Don't issue this warning for unavailable inits or direct subclasses
12843       // of NSObject.
12844       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12845         Diag(MD->getLocation(),
12846              diag::warn_objc_designated_init_missing_super_call);
12847         Diag(InitMethod->getLocation(),
12848              diag::note_objc_designated_init_marked_here);
12849       }
12850       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12851     }
12852     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12853       // Don't issue this warning for unavaialable inits.
12854       if (!MD->isUnavailable())
12855         Diag(MD->getLocation(),
12856              diag::warn_objc_secondary_init_missing_init_call);
12857       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12858     }
12859   } else {
12860     // Parsing the function declaration failed in some way. Pop the fake scope
12861     // we pushed on.
12862     PopFunctionScopeInfo(ActivePolicy, dcl);
12863     return nullptr;
12864   }
12865 
12866   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12867     DiagnoseUnguardedAvailabilityViolations(dcl);
12868 
12869   assert(!getCurFunction()->ObjCShouldCallSuper &&
12870          "This should only be set for ObjC methods, which should have been "
12871          "handled in the block above.");
12872 
12873   // Verify and clean out per-function state.
12874   if (Body && (!FD || !FD->isDefaulted())) {
12875     // C++ constructors that have function-try-blocks can't have return
12876     // statements in the handlers of that block. (C++ [except.handle]p14)
12877     // Verify this.
12878     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12879       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12880 
12881     // Verify that gotos and switch cases don't jump into scopes illegally.
12882     if (getCurFunction()->NeedsScopeChecking() &&
12883         !PP.isCodeCompletionEnabled())
12884       DiagnoseInvalidJumps(Body);
12885 
12886     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12887       if (!Destructor->getParent()->isDependentType())
12888         CheckDestructor(Destructor);
12889 
12890       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12891                                              Destructor->getParent());
12892     }
12893 
12894     // If any errors have occurred, clear out any temporaries that may have
12895     // been leftover. This ensures that these temporaries won't be picked up for
12896     // deletion in some later function.
12897     if (getDiagnostics().hasErrorOccurred() ||
12898         getDiagnostics().getSuppressAllDiagnostics()) {
12899       DiscardCleanupsInEvaluationContext();
12900     }
12901     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12902         !isa<FunctionTemplateDecl>(dcl)) {
12903       // Since the body is valid, issue any analysis-based warnings that are
12904       // enabled.
12905       ActivePolicy = &WP;
12906     }
12907 
12908     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12909         (!CheckConstexprFunctionDecl(FD) ||
12910          !CheckConstexprFunctionBody(FD, Body)))
12911       FD->setInvalidDecl();
12912 
12913     if (FD && FD->hasAttr<NakedAttr>()) {
12914       for (const Stmt *S : Body->children()) {
12915         // Allow local register variables without initializer as they don't
12916         // require prologue.
12917         bool RegisterVariables = false;
12918         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12919           for (const auto *Decl : DS->decls()) {
12920             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12921               RegisterVariables =
12922                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12923               if (!RegisterVariables)
12924                 break;
12925             }
12926           }
12927         }
12928         if (RegisterVariables)
12929           continue;
12930         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12931           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12932           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12933           FD->setInvalidDecl();
12934           break;
12935         }
12936       }
12937     }
12938 
12939     assert(ExprCleanupObjects.size() ==
12940                ExprEvalContexts.back().NumCleanupObjects &&
12941            "Leftover temporaries in function");
12942     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12943     assert(MaybeODRUseExprs.empty() &&
12944            "Leftover expressions for odr-use checking");
12945   }
12946 
12947   if (!IsInstantiation)
12948     PopDeclContext();
12949 
12950   PopFunctionScopeInfo(ActivePolicy, dcl);
12951   // If any errors have occurred, clear out any temporaries that may have
12952   // been leftover. This ensures that these temporaries won't be picked up for
12953   // deletion in some later function.
12954   if (getDiagnostics().hasErrorOccurred()) {
12955     DiscardCleanupsInEvaluationContext();
12956   }
12957 
12958   return dcl;
12959 }
12960 
12961 /// When we finish delayed parsing of an attribute, we must attach it to the
12962 /// relevant Decl.
12963 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12964                                        ParsedAttributes &Attrs) {
12965   // Always attach attributes to the underlying decl.
12966   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12967     D = TD->getTemplatedDecl();
12968   ProcessDeclAttributeList(S, D, Attrs.getList());
12969 
12970   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12971     if (Method->isStatic())
12972       checkThisInStaticMemberFunctionAttributes(Method);
12973 }
12974 
12975 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12976 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12977 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12978                                           IdentifierInfo &II, Scope *S) {
12979   // Find the scope in which the identifier is injected and the corresponding
12980   // DeclContext.
12981   // FIXME: C89 does not say what happens if there is no enclosing block scope.
12982   // In that case, we inject the declaration into the translation unit scope
12983   // instead.
12984   Scope *BlockScope = S;
12985   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12986     BlockScope = BlockScope->getParent();
12987 
12988   Scope *ContextScope = BlockScope;
12989   while (!ContextScope->getEntity())
12990     ContextScope = ContextScope->getParent();
12991   ContextRAII SavedContext(*this, ContextScope->getEntity());
12992 
12993   // Before we produce a declaration for an implicitly defined
12994   // function, see whether there was a locally-scoped declaration of
12995   // this name as a function or variable. If so, use that
12996   // (non-visible) declaration, and complain about it.
12997   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12998   if (ExternCPrev) {
12999     // We still need to inject the function into the enclosing block scope so
13000     // that later (non-call) uses can see it.
13001     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
13002 
13003     // C89 footnote 38:
13004     //   If in fact it is not defined as having type "function returning int",
13005     //   the behavior is undefined.
13006     if (!isa<FunctionDecl>(ExternCPrev) ||
13007         !Context.typesAreCompatible(
13008             cast<FunctionDecl>(ExternCPrev)->getType(),
13009             Context.getFunctionNoProtoType(Context.IntTy))) {
13010       Diag(Loc, diag::ext_use_out_of_scope_declaration)
13011           << ExternCPrev << !getLangOpts().C99;
13012       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13013       return ExternCPrev;
13014     }
13015   }
13016 
13017   // Extension in C99.  Legal in C90, but warn about it.
13018   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13019   unsigned diag_id;
13020   if (II.getName().startswith("__builtin_"))
13021     diag_id = diag::warn_builtin_unknown;
13022   else if (getLangOpts().C99 || getLangOpts().OpenCL)
13023     diag_id = diag::ext_implicit_function_decl;
13024   else
13025     diag_id = diag::warn_implicit_function_decl;
13026   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
13027 
13028   // If we found a prior declaration of this function, don't bother building
13029   // another one. We've already pushed that one into scope, so there's nothing
13030   // more to do.
13031   if (ExternCPrev)
13032     return ExternCPrev;
13033 
13034   // Because typo correction is expensive, only do it if the implicit
13035   // function declaration is going to be treated as an error.
13036   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13037     TypoCorrection Corrected;
13038     if (S &&
13039         (Corrected = CorrectTypo(
13040              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13041              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13042       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13043                    /*ErrorRecovery*/false);
13044   }
13045 
13046   // Set a Declarator for the implicit definition: int foo();
13047   const char *Dummy;
13048   AttributeFactory attrFactory;
13049   DeclSpec DS(attrFactory);
13050   unsigned DiagID;
13051   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13052                                   Context.getPrintingPolicy());
13053   (void)Error; // Silence warning.
13054   assert(!Error && "Error setting up implicit decl!");
13055   SourceLocation NoLoc;
13056   Declarator D(DS, DeclaratorContext::BlockContext);
13057   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13058                                              /*IsAmbiguous=*/false,
13059                                              /*LParenLoc=*/NoLoc,
13060                                              /*Params=*/nullptr,
13061                                              /*NumParams=*/0,
13062                                              /*EllipsisLoc=*/NoLoc,
13063                                              /*RParenLoc=*/NoLoc,
13064                                              /*TypeQuals=*/0,
13065                                              /*RefQualifierIsLvalueRef=*/true,
13066                                              /*RefQualifierLoc=*/NoLoc,
13067                                              /*ConstQualifierLoc=*/NoLoc,
13068                                              /*VolatileQualifierLoc=*/NoLoc,
13069                                              /*RestrictQualifierLoc=*/NoLoc,
13070                                              /*MutableLoc=*/NoLoc,
13071                                              EST_None,
13072                                              /*ESpecRange=*/SourceRange(),
13073                                              /*Exceptions=*/nullptr,
13074                                              /*ExceptionRanges=*/nullptr,
13075                                              /*NumExceptions=*/0,
13076                                              /*NoexceptExpr=*/nullptr,
13077                                              /*ExceptionSpecTokens=*/nullptr,
13078                                              /*DeclsInPrototype=*/None,
13079                                              Loc, Loc, D),
13080                 DS.getAttributes(),
13081                 SourceLocation());
13082   D.SetIdentifier(&II, Loc);
13083 
13084   // Insert this function into the enclosing block scope.
13085   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13086   FD->setImplicit();
13087 
13088   AddKnownFunctionAttributes(FD);
13089 
13090   return FD;
13091 }
13092 
13093 /// \brief Adds any function attributes that we know a priori based on
13094 /// the declaration of this function.
13095 ///
13096 /// These attributes can apply both to implicitly-declared builtins
13097 /// (like __builtin___printf_chk) or to library-declared functions
13098 /// like NSLog or printf.
13099 ///
13100 /// We need to check for duplicate attributes both here and where user-written
13101 /// attributes are applied to declarations.
13102 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13103   if (FD->isInvalidDecl())
13104     return;
13105 
13106   // If this is a built-in function, map its builtin attributes to
13107   // actual attributes.
13108   if (unsigned BuiltinID = FD->getBuiltinID()) {
13109     // Handle printf-formatting attributes.
13110     unsigned FormatIdx;
13111     bool HasVAListArg;
13112     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13113       if (!FD->hasAttr<FormatAttr>()) {
13114         const char *fmt = "printf";
13115         unsigned int NumParams = FD->getNumParams();
13116         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13117             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13118           fmt = "NSString";
13119         FD->addAttr(FormatAttr::CreateImplicit(Context,
13120                                                &Context.Idents.get(fmt),
13121                                                FormatIdx+1,
13122                                                HasVAListArg ? 0 : FormatIdx+2,
13123                                                FD->getLocation()));
13124       }
13125     }
13126     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13127                                              HasVAListArg)) {
13128      if (!FD->hasAttr<FormatAttr>())
13129        FD->addAttr(FormatAttr::CreateImplicit(Context,
13130                                               &Context.Idents.get("scanf"),
13131                                               FormatIdx+1,
13132                                               HasVAListArg ? 0 : FormatIdx+2,
13133                                               FD->getLocation()));
13134     }
13135 
13136     // Mark const if we don't care about errno and that is the only thing
13137     // preventing the function from being const. This allows IRgen to use LLVM
13138     // intrinsics for such functions.
13139     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13140         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13141       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13142 
13143     // We make "fma" on some platforms const because we know it does not set
13144     // errno in those environments even though it could set errno based on the
13145     // C standard.
13146     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13147     if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13148         !FD->hasAttr<ConstAttr>()) {
13149       switch (BuiltinID) {
13150       case Builtin::BI__builtin_fma:
13151       case Builtin::BI__builtin_fmaf:
13152       case Builtin::BI__builtin_fmal:
13153       case Builtin::BIfma:
13154       case Builtin::BIfmaf:
13155       case Builtin::BIfmal:
13156         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13157         break;
13158       default:
13159         break;
13160       }
13161     }
13162 
13163     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13164         !FD->hasAttr<ReturnsTwiceAttr>())
13165       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13166                                          FD->getLocation()));
13167     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13168       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13169     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13170       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13171     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13172       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13173     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13174         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13175       // Add the appropriate attribute, depending on the CUDA compilation mode
13176       // and which target the builtin belongs to. For example, during host
13177       // compilation, aux builtins are __device__, while the rest are __host__.
13178       if (getLangOpts().CUDAIsDevice !=
13179           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13180         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13181       else
13182         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13183     }
13184   }
13185 
13186   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13187   // throw, add an implicit nothrow attribute to any extern "C" function we come
13188   // across.
13189   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13190       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13191     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13192     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13193       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13194   }
13195 
13196   IdentifierInfo *Name = FD->getIdentifier();
13197   if (!Name)
13198     return;
13199   if ((!getLangOpts().CPlusPlus &&
13200        FD->getDeclContext()->isTranslationUnit()) ||
13201       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13202        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13203        LinkageSpecDecl::lang_c)) {
13204     // Okay: this could be a libc/libm/Objective-C function we know
13205     // about.
13206   } else
13207     return;
13208 
13209   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13210     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13211     // target-specific builtins, perhaps?
13212     if (!FD->hasAttr<FormatAttr>())
13213       FD->addAttr(FormatAttr::CreateImplicit(Context,
13214                                              &Context.Idents.get("printf"), 2,
13215                                              Name->isStr("vasprintf") ? 0 : 3,
13216                                              FD->getLocation()));
13217   }
13218 
13219   if (Name->isStr("__CFStringMakeConstantString")) {
13220     // We already have a __builtin___CFStringMakeConstantString,
13221     // but builds that use -fno-constant-cfstrings don't go through that.
13222     if (!FD->hasAttr<FormatArgAttr>())
13223       FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13224                                                 FD->getLocation()));
13225   }
13226 }
13227 
13228 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13229                                     TypeSourceInfo *TInfo) {
13230   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13231   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13232 
13233   if (!TInfo) {
13234     assert(D.isInvalidType() && "no declarator info for valid type");
13235     TInfo = Context.getTrivialTypeSourceInfo(T);
13236   }
13237 
13238   // Scope manipulation handled by caller.
13239   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13240                                            D.getLocStart(),
13241                                            D.getIdentifierLoc(),
13242                                            D.getIdentifier(),
13243                                            TInfo);
13244 
13245   // Bail out immediately if we have an invalid declaration.
13246   if (D.isInvalidType()) {
13247     NewTD->setInvalidDecl();
13248     return NewTD;
13249   }
13250 
13251   if (D.getDeclSpec().isModulePrivateSpecified()) {
13252     if (CurContext->isFunctionOrMethod())
13253       Diag(NewTD->getLocation(), diag::err_module_private_local)
13254         << 2 << NewTD->getDeclName()
13255         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13256         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13257     else
13258       NewTD->setModulePrivate();
13259   }
13260 
13261   // C++ [dcl.typedef]p8:
13262   //   If the typedef declaration defines an unnamed class (or
13263   //   enum), the first typedef-name declared by the declaration
13264   //   to be that class type (or enum type) is used to denote the
13265   //   class type (or enum type) for linkage purposes only.
13266   // We need to check whether the type was declared in the declaration.
13267   switch (D.getDeclSpec().getTypeSpecType()) {
13268   case TST_enum:
13269   case TST_struct:
13270   case TST_interface:
13271   case TST_union:
13272   case TST_class: {
13273     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13274     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13275     break;
13276   }
13277 
13278   default:
13279     break;
13280   }
13281 
13282   return NewTD;
13283 }
13284 
13285 /// \brief Check that this is a valid underlying type for an enum declaration.
13286 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13287   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13288   QualType T = TI->getType();
13289 
13290   if (T->isDependentType())
13291     return false;
13292 
13293   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13294     if (BT->isInteger())
13295       return false;
13296 
13297   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13298   return true;
13299 }
13300 
13301 /// Check whether this is a valid redeclaration of a previous enumeration.
13302 /// \return true if the redeclaration was invalid.
13303 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13304                                   QualType EnumUnderlyingTy, bool IsFixed,
13305                                   const EnumDecl *Prev) {
13306   if (IsScoped != Prev->isScoped()) {
13307     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13308       << Prev->isScoped();
13309     Diag(Prev->getLocation(), diag::note_previous_declaration);
13310     return true;
13311   }
13312 
13313   if (IsFixed && Prev->isFixed()) {
13314     if (!EnumUnderlyingTy->isDependentType() &&
13315         !Prev->getIntegerType()->isDependentType() &&
13316         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13317                                         Prev->getIntegerType())) {
13318       // TODO: Highlight the underlying type of the redeclaration.
13319       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13320         << EnumUnderlyingTy << Prev->getIntegerType();
13321       Diag(Prev->getLocation(), diag::note_previous_declaration)
13322           << Prev->getIntegerTypeRange();
13323       return true;
13324     }
13325   } else if (IsFixed != Prev->isFixed()) {
13326     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13327       << Prev->isFixed();
13328     Diag(Prev->getLocation(), diag::note_previous_declaration);
13329     return true;
13330   }
13331 
13332   return false;
13333 }
13334 
13335 /// \brief Get diagnostic %select index for tag kind for
13336 /// redeclaration diagnostic message.
13337 /// WARNING: Indexes apply to particular diagnostics only!
13338 ///
13339 /// \returns diagnostic %select index.
13340 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13341   switch (Tag) {
13342   case TTK_Struct: return 0;
13343   case TTK_Interface: return 1;
13344   case TTK_Class:  return 2;
13345   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13346   }
13347 }
13348 
13349 /// \brief Determine if tag kind is a class-key compatible with
13350 /// class for redeclaration (class, struct, or __interface).
13351 ///
13352 /// \returns true iff the tag kind is compatible.
13353 static bool isClassCompatTagKind(TagTypeKind Tag)
13354 {
13355   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13356 }
13357 
13358 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13359                                              TagTypeKind TTK) {
13360   if (isa<TypedefDecl>(PrevDecl))
13361     return NTK_Typedef;
13362   else if (isa<TypeAliasDecl>(PrevDecl))
13363     return NTK_TypeAlias;
13364   else if (isa<ClassTemplateDecl>(PrevDecl))
13365     return NTK_Template;
13366   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13367     return NTK_TypeAliasTemplate;
13368   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13369     return NTK_TemplateTemplateArgument;
13370   switch (TTK) {
13371   case TTK_Struct:
13372   case TTK_Interface:
13373   case TTK_Class:
13374     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13375   case TTK_Union:
13376     return NTK_NonUnion;
13377   case TTK_Enum:
13378     return NTK_NonEnum;
13379   }
13380   llvm_unreachable("invalid TTK");
13381 }
13382 
13383 /// \brief Determine whether a tag with a given kind is acceptable
13384 /// as a redeclaration of the given tag declaration.
13385 ///
13386 /// \returns true if the new tag kind is acceptable, false otherwise.
13387 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13388                                         TagTypeKind NewTag, bool isDefinition,
13389                                         SourceLocation NewTagLoc,
13390                                         const IdentifierInfo *Name) {
13391   // C++ [dcl.type.elab]p3:
13392   //   The class-key or enum keyword present in the
13393   //   elaborated-type-specifier shall agree in kind with the
13394   //   declaration to which the name in the elaborated-type-specifier
13395   //   refers. This rule also applies to the form of
13396   //   elaborated-type-specifier that declares a class-name or
13397   //   friend class since it can be construed as referring to the
13398   //   definition of the class. Thus, in any
13399   //   elaborated-type-specifier, the enum keyword shall be used to
13400   //   refer to an enumeration (7.2), the union class-key shall be
13401   //   used to refer to a union (clause 9), and either the class or
13402   //   struct class-key shall be used to refer to a class (clause 9)
13403   //   declared using the class or struct class-key.
13404   TagTypeKind OldTag = Previous->getTagKind();
13405   if (!isDefinition || !isClassCompatTagKind(NewTag))
13406     if (OldTag == NewTag)
13407       return true;
13408 
13409   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13410     // Warn about the struct/class tag mismatch.
13411     bool isTemplate = false;
13412     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13413       isTemplate = Record->getDescribedClassTemplate();
13414 
13415     if (inTemplateInstantiation()) {
13416       // In a template instantiation, do not offer fix-its for tag mismatches
13417       // since they usually mess up the template instead of fixing the problem.
13418       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13419         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13420         << getRedeclDiagFromTagKind(OldTag);
13421       return true;
13422     }
13423 
13424     if (isDefinition) {
13425       // On definitions, check previous tags and issue a fix-it for each
13426       // one that doesn't match the current tag.
13427       if (Previous->getDefinition()) {
13428         // Don't suggest fix-its for redefinitions.
13429         return true;
13430       }
13431 
13432       bool previousMismatch = false;
13433       for (auto I : Previous->redecls()) {
13434         if (I->getTagKind() != NewTag) {
13435           if (!previousMismatch) {
13436             previousMismatch = true;
13437             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13438               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13439               << getRedeclDiagFromTagKind(I->getTagKind());
13440           }
13441           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13442             << getRedeclDiagFromTagKind(NewTag)
13443             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13444                  TypeWithKeyword::getTagTypeKindName(NewTag));
13445         }
13446       }
13447       return true;
13448     }
13449 
13450     // Check for a previous definition.  If current tag and definition
13451     // are same type, do nothing.  If no definition, but disagree with
13452     // with previous tag type, give a warning, but no fix-it.
13453     const TagDecl *Redecl = Previous->getDefinition() ?
13454                             Previous->getDefinition() : Previous;
13455     if (Redecl->getTagKind() == NewTag) {
13456       return true;
13457     }
13458 
13459     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13460       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13461       << getRedeclDiagFromTagKind(OldTag);
13462     Diag(Redecl->getLocation(), diag::note_previous_use);
13463 
13464     // If there is a previous definition, suggest a fix-it.
13465     if (Previous->getDefinition()) {
13466         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13467           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13468           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13469                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13470     }
13471 
13472     return true;
13473   }
13474   return false;
13475 }
13476 
13477 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13478 /// from an outer enclosing namespace or file scope inside a friend declaration.
13479 /// This should provide the commented out code in the following snippet:
13480 ///   namespace N {
13481 ///     struct X;
13482 ///     namespace M {
13483 ///       struct Y { friend struct /*N::*/ X; };
13484 ///     }
13485 ///   }
13486 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13487                                          SourceLocation NameLoc) {
13488   // While the decl is in a namespace, do repeated lookup of that name and see
13489   // if we get the same namespace back.  If we do not, continue until
13490   // translation unit scope, at which point we have a fully qualified NNS.
13491   SmallVector<IdentifierInfo *, 4> Namespaces;
13492   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13493   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13494     // This tag should be declared in a namespace, which can only be enclosed by
13495     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13496     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13497     if (!Namespace || Namespace->isAnonymousNamespace())
13498       return FixItHint();
13499     IdentifierInfo *II = Namespace->getIdentifier();
13500     Namespaces.push_back(II);
13501     NamedDecl *Lookup = SemaRef.LookupSingleName(
13502         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13503     if (Lookup == Namespace)
13504       break;
13505   }
13506 
13507   // Once we have all the namespaces, reverse them to go outermost first, and
13508   // build an NNS.
13509   SmallString<64> Insertion;
13510   llvm::raw_svector_ostream OS(Insertion);
13511   if (DC->isTranslationUnit())
13512     OS << "::";
13513   std::reverse(Namespaces.begin(), Namespaces.end());
13514   for (auto *II : Namespaces)
13515     OS << II->getName() << "::";
13516   return FixItHint::CreateInsertion(NameLoc, Insertion);
13517 }
13518 
13519 /// \brief Determine whether a tag originally declared in context \p OldDC can
13520 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13521 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13522 /// using-declaration).
13523 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13524                                          DeclContext *NewDC) {
13525   OldDC = OldDC->getRedeclContext();
13526   NewDC = NewDC->getRedeclContext();
13527 
13528   if (OldDC->Equals(NewDC))
13529     return true;
13530 
13531   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13532   // encloses the other).
13533   if (S.getLangOpts().MSVCCompat &&
13534       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13535     return true;
13536 
13537   return false;
13538 }
13539 
13540 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13541 /// former case, Name will be non-null.  In the later case, Name will be null.
13542 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13543 /// reference/declaration/definition of a tag.
13544 ///
13545 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13546 /// trailing-type-specifier) other than one in an alias-declaration.
13547 ///
13548 /// \param SkipBody If non-null, will be set to indicate if the caller should
13549 /// skip the definition of this tag and treat it as if it were a declaration.
13550 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13551                      SourceLocation KWLoc, CXXScopeSpec &SS,
13552                      IdentifierInfo *Name, SourceLocation NameLoc,
13553                      AttributeList *Attr, AccessSpecifier AS,
13554                      SourceLocation ModulePrivateLoc,
13555                      MultiTemplateParamsArg TemplateParameterLists,
13556                      bool &OwnedDecl, bool &IsDependent,
13557                      SourceLocation ScopedEnumKWLoc,
13558                      bool ScopedEnumUsesClassTag,
13559                      TypeResult UnderlyingType,
13560                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13561                      SkipBodyInfo *SkipBody) {
13562   // If this is not a definition, it must have a name.
13563   IdentifierInfo *OrigName = Name;
13564   assert((Name != nullptr || TUK == TUK_Definition) &&
13565          "Nameless record must be a definition!");
13566   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13567 
13568   OwnedDecl = false;
13569   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13570   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13571 
13572   // FIXME: Check member specializations more carefully.
13573   bool isMemberSpecialization = false;
13574   bool Invalid = false;
13575 
13576   // We only need to do this matching if we have template parameters
13577   // or a scope specifier, which also conveniently avoids this work
13578   // for non-C++ cases.
13579   if (TemplateParameterLists.size() > 0 ||
13580       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13581     if (TemplateParameterList *TemplateParams =
13582             MatchTemplateParametersToScopeSpecifier(
13583                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13584                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13585       if (Kind == TTK_Enum) {
13586         Diag(KWLoc, diag::err_enum_template);
13587         return nullptr;
13588       }
13589 
13590       if (TemplateParams->size() > 0) {
13591         // This is a declaration or definition of a class template (which may
13592         // be a member of another template).
13593 
13594         if (Invalid)
13595           return nullptr;
13596 
13597         OwnedDecl = false;
13598         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13599                                                SS, Name, NameLoc, Attr,
13600                                                TemplateParams, AS,
13601                                                ModulePrivateLoc,
13602                                                /*FriendLoc*/SourceLocation(),
13603                                                TemplateParameterLists.size()-1,
13604                                                TemplateParameterLists.data(),
13605                                                SkipBody);
13606         return Result.get();
13607       } else {
13608         // The "template<>" header is extraneous.
13609         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13610           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13611         isMemberSpecialization = true;
13612       }
13613     }
13614   }
13615 
13616   // Figure out the underlying type if this a enum declaration. We need to do
13617   // this early, because it's needed to detect if this is an incompatible
13618   // redeclaration.
13619   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13620   bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13621 
13622   if (Kind == TTK_Enum) {
13623     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13624       // No underlying type explicitly specified, or we failed to parse the
13625       // type, default to int.
13626       EnumUnderlying = Context.IntTy.getTypePtr();
13627     } else if (UnderlyingType.get()) {
13628       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13629       // integral type; any cv-qualification is ignored.
13630       TypeSourceInfo *TI = nullptr;
13631       GetTypeFromParser(UnderlyingType.get(), &TI);
13632       EnumUnderlying = TI;
13633 
13634       if (CheckEnumUnderlyingType(TI))
13635         // Recover by falling back to int.
13636         EnumUnderlying = Context.IntTy.getTypePtr();
13637 
13638       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13639                                           UPPC_FixedUnderlyingType))
13640         EnumUnderlying = Context.IntTy.getTypePtr();
13641 
13642     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13643       // For MSVC ABI compatibility, unfixed enums must use an underlying type
13644       // of 'int'. However, if this is an unfixed forward declaration, don't set
13645       // the underlying type unless the user enables -fms-compatibility. This
13646       // makes unfixed forward declared enums incomplete and is more conforming.
13647       if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13648         EnumUnderlying = Context.IntTy.getTypePtr();
13649     }
13650   }
13651 
13652   DeclContext *SearchDC = CurContext;
13653   DeclContext *DC = CurContext;
13654   bool isStdBadAlloc = false;
13655   bool isStdAlignValT = false;
13656 
13657   RedeclarationKind Redecl = forRedeclarationInCurContext();
13658   if (TUK == TUK_Friend || TUK == TUK_Reference)
13659     Redecl = NotForRedeclaration;
13660 
13661   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13662   /// implemented asks for structural equivalence checking, the returned decl
13663   /// here is passed back to the parser, allowing the tag body to be parsed.
13664   auto createTagFromNewDecl = [&]() -> TagDecl * {
13665     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13666     // If there is an identifier, use the location of the identifier as the
13667     // location of the decl, otherwise use the location of the struct/union
13668     // keyword.
13669     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13670     TagDecl *New = nullptr;
13671 
13672     if (Kind == TTK_Enum) {
13673       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13674                              ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
13675       // If this is an undefined enum, bail.
13676       if (TUK != TUK_Definition && !Invalid)
13677         return nullptr;
13678       if (EnumUnderlying) {
13679         EnumDecl *ED = cast<EnumDecl>(New);
13680         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13681           ED->setIntegerTypeSourceInfo(TI);
13682         else
13683           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13684         ED->setPromotionType(ED->getIntegerType());
13685       }
13686     } else { // struct/union
13687       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13688                                nullptr);
13689     }
13690 
13691     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13692       // Add alignment attributes if necessary; these attributes are checked
13693       // when the ASTContext lays out the structure.
13694       //
13695       // It is important for implementing the correct semantics that this
13696       // happen here (in ActOnTag). The #pragma pack stack is
13697       // maintained as a result of parser callbacks which can occur at
13698       // many points during the parsing of a struct declaration (because
13699       // the #pragma tokens are effectively skipped over during the
13700       // parsing of the struct).
13701       if (TUK == TUK_Definition) {
13702         AddAlignmentAttributesForRecord(RD);
13703         AddMsStructLayoutForRecord(RD);
13704       }
13705     }
13706     New->setLexicalDeclContext(CurContext);
13707     return New;
13708   };
13709 
13710   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13711   if (Name && SS.isNotEmpty()) {
13712     // We have a nested-name tag ('struct foo::bar').
13713 
13714     // Check for invalid 'foo::'.
13715     if (SS.isInvalid()) {
13716       Name = nullptr;
13717       goto CreateNewDecl;
13718     }
13719 
13720     // If this is a friend or a reference to a class in a dependent
13721     // context, don't try to make a decl for it.
13722     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13723       DC = computeDeclContext(SS, false);
13724       if (!DC) {
13725         IsDependent = true;
13726         return nullptr;
13727       }
13728     } else {
13729       DC = computeDeclContext(SS, true);
13730       if (!DC) {
13731         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13732           << SS.getRange();
13733         return nullptr;
13734       }
13735     }
13736 
13737     if (RequireCompleteDeclContext(SS, DC))
13738       return nullptr;
13739 
13740     SearchDC = DC;
13741     // Look-up name inside 'foo::'.
13742     LookupQualifiedName(Previous, DC);
13743 
13744     if (Previous.isAmbiguous())
13745       return nullptr;
13746 
13747     if (Previous.empty()) {
13748       // Name lookup did not find anything. However, if the
13749       // nested-name-specifier refers to the current instantiation,
13750       // and that current instantiation has any dependent base
13751       // classes, we might find something at instantiation time: treat
13752       // this as a dependent elaborated-type-specifier.
13753       // But this only makes any sense for reference-like lookups.
13754       if (Previous.wasNotFoundInCurrentInstantiation() &&
13755           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13756         IsDependent = true;
13757         return nullptr;
13758       }
13759 
13760       // A tag 'foo::bar' must already exist.
13761       Diag(NameLoc, diag::err_not_tag_in_scope)
13762         << Kind << Name << DC << SS.getRange();
13763       Name = nullptr;
13764       Invalid = true;
13765       goto CreateNewDecl;
13766     }
13767   } else if (Name) {
13768     // C++14 [class.mem]p14:
13769     //   If T is the name of a class, then each of the following shall have a
13770     //   name different from T:
13771     //    -- every member of class T that is itself a type
13772     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13773         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13774       return nullptr;
13775 
13776     // If this is a named struct, check to see if there was a previous forward
13777     // declaration or definition.
13778     // FIXME: We're looking into outer scopes here, even when we
13779     // shouldn't be. Doing so can result in ambiguities that we
13780     // shouldn't be diagnosing.
13781     LookupName(Previous, S);
13782 
13783     // When declaring or defining a tag, ignore ambiguities introduced
13784     // by types using'ed into this scope.
13785     if (Previous.isAmbiguous() &&
13786         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13787       LookupResult::Filter F = Previous.makeFilter();
13788       while (F.hasNext()) {
13789         NamedDecl *ND = F.next();
13790         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13791                 SearchDC->getRedeclContext()))
13792           F.erase();
13793       }
13794       F.done();
13795     }
13796 
13797     // C++11 [namespace.memdef]p3:
13798     //   If the name in a friend declaration is neither qualified nor
13799     //   a template-id and the declaration is a function or an
13800     //   elaborated-type-specifier, the lookup to determine whether
13801     //   the entity has been previously declared shall not consider
13802     //   any scopes outside the innermost enclosing namespace.
13803     //
13804     // MSVC doesn't implement the above rule for types, so a friend tag
13805     // declaration may be a redeclaration of a type declared in an enclosing
13806     // scope.  They do implement this rule for friend functions.
13807     //
13808     // Does it matter that this should be by scope instead of by
13809     // semantic context?
13810     if (!Previous.empty() && TUK == TUK_Friend) {
13811       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13812       LookupResult::Filter F = Previous.makeFilter();
13813       bool FriendSawTagOutsideEnclosingNamespace = false;
13814       while (F.hasNext()) {
13815         NamedDecl *ND = F.next();
13816         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13817         if (DC->isFileContext() &&
13818             !EnclosingNS->Encloses(ND->getDeclContext())) {
13819           if (getLangOpts().MSVCCompat)
13820             FriendSawTagOutsideEnclosingNamespace = true;
13821           else
13822             F.erase();
13823         }
13824       }
13825       F.done();
13826 
13827       // Diagnose this MSVC extension in the easy case where lookup would have
13828       // unambiguously found something outside the enclosing namespace.
13829       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13830         NamedDecl *ND = Previous.getFoundDecl();
13831         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13832             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13833       }
13834     }
13835 
13836     // Note:  there used to be some attempt at recovery here.
13837     if (Previous.isAmbiguous())
13838       return nullptr;
13839 
13840     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13841       // FIXME: This makes sure that we ignore the contexts associated
13842       // with C structs, unions, and enums when looking for a matching
13843       // tag declaration or definition. See the similar lookup tweak
13844       // in Sema::LookupName; is there a better way to deal with this?
13845       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13846         SearchDC = SearchDC->getParent();
13847     }
13848   }
13849 
13850   if (Previous.isSingleResult() &&
13851       Previous.getFoundDecl()->isTemplateParameter()) {
13852     // Maybe we will complain about the shadowed template parameter.
13853     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13854     // Just pretend that we didn't see the previous declaration.
13855     Previous.clear();
13856   }
13857 
13858   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13859       DC->Equals(getStdNamespace())) {
13860     if (Name->isStr("bad_alloc")) {
13861       // This is a declaration of or a reference to "std::bad_alloc".
13862       isStdBadAlloc = true;
13863 
13864       // If std::bad_alloc has been implicitly declared (but made invisible to
13865       // name lookup), fill in this implicit declaration as the previous
13866       // declaration, so that the declarations get chained appropriately.
13867       if (Previous.empty() && StdBadAlloc)
13868         Previous.addDecl(getStdBadAlloc());
13869     } else if (Name->isStr("align_val_t")) {
13870       isStdAlignValT = true;
13871       if (Previous.empty() && StdAlignValT)
13872         Previous.addDecl(getStdAlignValT());
13873     }
13874   }
13875 
13876   // If we didn't find a previous declaration, and this is a reference
13877   // (or friend reference), move to the correct scope.  In C++, we
13878   // also need to do a redeclaration lookup there, just in case
13879   // there's a shadow friend decl.
13880   if (Name && Previous.empty() &&
13881       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13882     if (Invalid) goto CreateNewDecl;
13883     assert(SS.isEmpty());
13884 
13885     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13886       // C++ [basic.scope.pdecl]p5:
13887       //   -- for an elaborated-type-specifier of the form
13888       //
13889       //          class-key identifier
13890       //
13891       //      if the elaborated-type-specifier is used in the
13892       //      decl-specifier-seq or parameter-declaration-clause of a
13893       //      function defined in namespace scope, the identifier is
13894       //      declared as a class-name in the namespace that contains
13895       //      the declaration; otherwise, except as a friend
13896       //      declaration, the identifier is declared in the smallest
13897       //      non-class, non-function-prototype scope that contains the
13898       //      declaration.
13899       //
13900       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13901       // C structs and unions.
13902       //
13903       // It is an error in C++ to declare (rather than define) an enum
13904       // type, including via an elaborated type specifier.  We'll
13905       // diagnose that later; for now, declare the enum in the same
13906       // scope as we would have picked for any other tag type.
13907       //
13908       // GNU C also supports this behavior as part of its incomplete
13909       // enum types extension, while GNU C++ does not.
13910       //
13911       // Find the context where we'll be declaring the tag.
13912       // FIXME: We would like to maintain the current DeclContext as the
13913       // lexical context,
13914       SearchDC = getTagInjectionContext(SearchDC);
13915 
13916       // Find the scope where we'll be declaring the tag.
13917       S = getTagInjectionScope(S, getLangOpts());
13918     } else {
13919       assert(TUK == TUK_Friend);
13920       // C++ [namespace.memdef]p3:
13921       //   If a friend declaration in a non-local class first declares a
13922       //   class or function, the friend class or function is a member of
13923       //   the innermost enclosing namespace.
13924       SearchDC = SearchDC->getEnclosingNamespaceContext();
13925     }
13926 
13927     // In C++, we need to do a redeclaration lookup to properly
13928     // diagnose some problems.
13929     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13930     // hidden declaration so that we don't get ambiguity errors when using a
13931     // type declared by an elaborated-type-specifier.  In C that is not correct
13932     // and we should instead merge compatible types found by lookup.
13933     if (getLangOpts().CPlusPlus) {
13934       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13935       LookupQualifiedName(Previous, SearchDC);
13936     } else {
13937       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13938       LookupName(Previous, S);
13939     }
13940   }
13941 
13942   // If we have a known previous declaration to use, then use it.
13943   if (Previous.empty() && SkipBody && SkipBody->Previous)
13944     Previous.addDecl(SkipBody->Previous);
13945 
13946   if (!Previous.empty()) {
13947     NamedDecl *PrevDecl = Previous.getFoundDecl();
13948     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13949 
13950     // It's okay to have a tag decl in the same scope as a typedef
13951     // which hides a tag decl in the same scope.  Finding this
13952     // insanity with a redeclaration lookup can only actually happen
13953     // in C++.
13954     //
13955     // This is also okay for elaborated-type-specifiers, which is
13956     // technically forbidden by the current standard but which is
13957     // okay according to the likely resolution of an open issue;
13958     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13959     if (getLangOpts().CPlusPlus) {
13960       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13961         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13962           TagDecl *Tag = TT->getDecl();
13963           if (Tag->getDeclName() == Name &&
13964               Tag->getDeclContext()->getRedeclContext()
13965                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13966             PrevDecl = Tag;
13967             Previous.clear();
13968             Previous.addDecl(Tag);
13969             Previous.resolveKind();
13970           }
13971         }
13972       }
13973     }
13974 
13975     // If this is a redeclaration of a using shadow declaration, it must
13976     // declare a tag in the same context. In MSVC mode, we allow a
13977     // redefinition if either context is within the other.
13978     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13979       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13980       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13981           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13982           !(OldTag && isAcceptableTagRedeclContext(
13983                           *this, OldTag->getDeclContext(), SearchDC))) {
13984         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13985         Diag(Shadow->getTargetDecl()->getLocation(),
13986              diag::note_using_decl_target);
13987         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13988             << 0;
13989         // Recover by ignoring the old declaration.
13990         Previous.clear();
13991         goto CreateNewDecl;
13992       }
13993     }
13994 
13995     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13996       // If this is a use of a previous tag, or if the tag is already declared
13997       // in the same scope (so that the definition/declaration completes or
13998       // rementions the tag), reuse the decl.
13999       if (TUK == TUK_Reference || TUK == TUK_Friend ||
14000           isDeclInScope(DirectPrevDecl, SearchDC, S,
14001                         SS.isNotEmpty() || isMemberSpecialization)) {
14002         // Make sure that this wasn't declared as an enum and now used as a
14003         // struct or something similar.
14004         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
14005                                           TUK == TUK_Definition, KWLoc,
14006                                           Name)) {
14007           bool SafeToContinue
14008             = (PrevTagDecl->getTagKind() != TTK_Enum &&
14009                Kind != TTK_Enum);
14010           if (SafeToContinue)
14011             Diag(KWLoc, diag::err_use_with_wrong_tag)
14012               << Name
14013               << FixItHint::CreateReplacement(SourceRange(KWLoc),
14014                                               PrevTagDecl->getKindName());
14015           else
14016             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14017           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14018 
14019           if (SafeToContinue)
14020             Kind = PrevTagDecl->getTagKind();
14021           else {
14022             // Recover by making this an anonymous redefinition.
14023             Name = nullptr;
14024             Previous.clear();
14025             Invalid = true;
14026           }
14027         }
14028 
14029         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14030           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14031 
14032           // If this is an elaborated-type-specifier for a scoped enumeration,
14033           // the 'class' keyword is not necessary and not permitted.
14034           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14035             if (ScopedEnum)
14036               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14037                 << PrevEnum->isScoped()
14038                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14039             return PrevTagDecl;
14040           }
14041 
14042           QualType EnumUnderlyingTy;
14043           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14044             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14045           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14046             EnumUnderlyingTy = QualType(T, 0);
14047 
14048           // All conflicts with previous declarations are recovered by
14049           // returning the previous declaration, unless this is a definition,
14050           // in which case we want the caller to bail out.
14051           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14052                                      ScopedEnum, EnumUnderlyingTy,
14053                                      IsFixed, PrevEnum))
14054             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14055         }
14056 
14057         // C++11 [class.mem]p1:
14058         //   A member shall not be declared twice in the member-specification,
14059         //   except that a nested class or member class template can be declared
14060         //   and then later defined.
14061         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14062             S->isDeclScope(PrevDecl)) {
14063           Diag(NameLoc, diag::ext_member_redeclared);
14064           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14065         }
14066 
14067         if (!Invalid) {
14068           // If this is a use, just return the declaration we found, unless
14069           // we have attributes.
14070           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14071             if (Attr) {
14072               // FIXME: Diagnose these attributes. For now, we create a new
14073               // declaration to hold them.
14074             } else if (TUK == TUK_Reference &&
14075                        (PrevTagDecl->getFriendObjectKind() ==
14076                             Decl::FOK_Undeclared ||
14077                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14078                        SS.isEmpty()) {
14079               // This declaration is a reference to an existing entity, but
14080               // has different visibility from that entity: it either makes
14081               // a friend visible or it makes a type visible in a new module.
14082               // In either case, create a new declaration. We only do this if
14083               // the declaration would have meant the same thing if no prior
14084               // declaration were found, that is, if it was found in the same
14085               // scope where we would have injected a declaration.
14086               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14087                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14088                 return PrevTagDecl;
14089               // This is in the injected scope, create a new declaration in
14090               // that scope.
14091               S = getTagInjectionScope(S, getLangOpts());
14092             } else {
14093               return PrevTagDecl;
14094             }
14095           }
14096 
14097           // Diagnose attempts to redefine a tag.
14098           if (TUK == TUK_Definition) {
14099             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14100               // If we're defining a specialization and the previous definition
14101               // is from an implicit instantiation, don't emit an error
14102               // here; we'll catch this in the general case below.
14103               bool IsExplicitSpecializationAfterInstantiation = false;
14104               if (isMemberSpecialization) {
14105                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14106                   IsExplicitSpecializationAfterInstantiation =
14107                     RD->getTemplateSpecializationKind() !=
14108                     TSK_ExplicitSpecialization;
14109                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14110                   IsExplicitSpecializationAfterInstantiation =
14111                     ED->getTemplateSpecializationKind() !=
14112                     TSK_ExplicitSpecialization;
14113               }
14114 
14115               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14116               // not keep more that one definition around (merge them). However,
14117               // ensure the decl passes the structural compatibility check in
14118               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14119               NamedDecl *Hidden = nullptr;
14120               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14121                 // There is a definition of this tag, but it is not visible. We
14122                 // explicitly make use of C++'s one definition rule here, and
14123                 // assume that this definition is identical to the hidden one
14124                 // we already have. Make the existing definition visible and
14125                 // use it in place of this one.
14126                 if (!getLangOpts().CPlusPlus) {
14127                   // Postpone making the old definition visible until after we
14128                   // complete parsing the new one and do the structural
14129                   // comparison.
14130                   SkipBody->CheckSameAsPrevious = true;
14131                   SkipBody->New = createTagFromNewDecl();
14132                   SkipBody->Previous = Hidden;
14133                 } else {
14134                   SkipBody->ShouldSkip = true;
14135                   makeMergedDefinitionVisible(Hidden);
14136                 }
14137                 return Def;
14138               } else if (!IsExplicitSpecializationAfterInstantiation) {
14139                 // A redeclaration in function prototype scope in C isn't
14140                 // visible elsewhere, so merely issue a warning.
14141                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14142                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14143                 else
14144                   Diag(NameLoc, diag::err_redefinition) << Name;
14145                 notePreviousDefinition(Def,
14146                                        NameLoc.isValid() ? NameLoc : KWLoc);
14147                 // If this is a redefinition, recover by making this
14148                 // struct be anonymous, which will make any later
14149                 // references get the previous definition.
14150                 Name = nullptr;
14151                 Previous.clear();
14152                 Invalid = true;
14153               }
14154             } else {
14155               // If the type is currently being defined, complain
14156               // about a nested redefinition.
14157               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14158               if (TD->isBeingDefined()) {
14159                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14160                 Diag(PrevTagDecl->getLocation(),
14161                      diag::note_previous_definition);
14162                 Name = nullptr;
14163                 Previous.clear();
14164                 Invalid = true;
14165               }
14166             }
14167 
14168             // Okay, this is definition of a previously declared or referenced
14169             // tag. We're going to create a new Decl for it.
14170           }
14171 
14172           // Okay, we're going to make a redeclaration.  If this is some kind
14173           // of reference, make sure we build the redeclaration in the same DC
14174           // as the original, and ignore the current access specifier.
14175           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14176             SearchDC = PrevTagDecl->getDeclContext();
14177             AS = AS_none;
14178           }
14179         }
14180         // If we get here we have (another) forward declaration or we
14181         // have a definition.  Just create a new decl.
14182 
14183       } else {
14184         // If we get here, this is a definition of a new tag type in a nested
14185         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14186         // new decl/type.  We set PrevDecl to NULL so that the entities
14187         // have distinct types.
14188         Previous.clear();
14189       }
14190       // If we get here, we're going to create a new Decl. If PrevDecl
14191       // is non-NULL, it's a definition of the tag declared by
14192       // PrevDecl. If it's NULL, we have a new definition.
14193 
14194     // Otherwise, PrevDecl is not a tag, but was found with tag
14195     // lookup.  This is only actually possible in C++, where a few
14196     // things like templates still live in the tag namespace.
14197     } else {
14198       // Use a better diagnostic if an elaborated-type-specifier
14199       // found the wrong kind of type on the first
14200       // (non-redeclaration) lookup.
14201       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14202           !Previous.isForRedeclaration()) {
14203         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14204         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14205                                                        << Kind;
14206         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14207         Invalid = true;
14208 
14209       // Otherwise, only diagnose if the declaration is in scope.
14210       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14211                                 SS.isNotEmpty() || isMemberSpecialization)) {
14212         // do nothing
14213 
14214       // Diagnose implicit declarations introduced by elaborated types.
14215       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14216         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14217         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14218         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14219         Invalid = true;
14220 
14221       // Otherwise it's a declaration.  Call out a particularly common
14222       // case here.
14223       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14224         unsigned Kind = 0;
14225         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14226         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14227           << Name << Kind << TND->getUnderlyingType();
14228         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14229         Invalid = true;
14230 
14231       // Otherwise, diagnose.
14232       } else {
14233         // The tag name clashes with something else in the target scope,
14234         // issue an error and recover by making this tag be anonymous.
14235         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14236         notePreviousDefinition(PrevDecl, NameLoc);
14237         Name = nullptr;
14238         Invalid = true;
14239       }
14240 
14241       // The existing declaration isn't relevant to us; we're in a
14242       // new scope, so clear out the previous declaration.
14243       Previous.clear();
14244     }
14245   }
14246 
14247 CreateNewDecl:
14248 
14249   TagDecl *PrevDecl = nullptr;
14250   if (Previous.isSingleResult())
14251     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14252 
14253   // If there is an identifier, use the location of the identifier as the
14254   // location of the decl, otherwise use the location of the struct/union
14255   // keyword.
14256   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14257 
14258   // Otherwise, create a new declaration. If there is a previous
14259   // declaration of the same entity, the two will be linked via
14260   // PrevDecl.
14261   TagDecl *New;
14262 
14263   bool IsForwardReference = false;
14264   if (Kind == TTK_Enum) {
14265     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14266     // enum X { A, B, C } D;    D should chain to X.
14267     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14268                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14269                            ScopedEnumUsesClassTag, IsFixed);
14270 
14271     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14272       StdAlignValT = cast<EnumDecl>(New);
14273 
14274     // If this is an undefined enum, warn.
14275     if (TUK != TUK_Definition && !Invalid) {
14276       TagDecl *Def;
14277       if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14278           cast<EnumDecl>(New)->isFixed()) {
14279         // C++0x: 7.2p2: opaque-enum-declaration.
14280         // Conflicts are diagnosed above. Do nothing.
14281       }
14282       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14283         Diag(Loc, diag::ext_forward_ref_enum_def)
14284           << New;
14285         Diag(Def->getLocation(), diag::note_previous_definition);
14286       } else {
14287         unsigned DiagID = diag::ext_forward_ref_enum;
14288         if (getLangOpts().MSVCCompat)
14289           DiagID = diag::ext_ms_forward_ref_enum;
14290         else if (getLangOpts().CPlusPlus)
14291           DiagID = diag::err_forward_ref_enum;
14292         Diag(Loc, DiagID);
14293 
14294         // If this is a forward-declared reference to an enumeration, make a
14295         // note of it; we won't actually be introducing the declaration into
14296         // the declaration context.
14297         if (TUK == TUK_Reference)
14298           IsForwardReference = true;
14299       }
14300     }
14301 
14302     if (EnumUnderlying) {
14303       EnumDecl *ED = cast<EnumDecl>(New);
14304       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14305         ED->setIntegerTypeSourceInfo(TI);
14306       else
14307         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14308       ED->setPromotionType(ED->getIntegerType());
14309       assert(ED->isComplete() && "enum with type should be complete");
14310     }
14311   } else {
14312     // struct/union/class
14313 
14314     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14315     // struct X { int A; } D;    D should chain to X.
14316     if (getLangOpts().CPlusPlus) {
14317       // FIXME: Look for a way to use RecordDecl for simple structs.
14318       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14319                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14320 
14321       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14322         StdBadAlloc = cast<CXXRecordDecl>(New);
14323     } else
14324       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14325                                cast_or_null<RecordDecl>(PrevDecl));
14326   }
14327 
14328   // C++11 [dcl.type]p3:
14329   //   A type-specifier-seq shall not define a class or enumeration [...].
14330   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14331       TUK == TUK_Definition) {
14332     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14333       << Context.getTagDeclType(New);
14334     Invalid = true;
14335   }
14336 
14337   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14338       DC->getDeclKind() == Decl::Enum) {
14339     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14340       << Context.getTagDeclType(New);
14341     Invalid = true;
14342   }
14343 
14344   // Maybe add qualifier info.
14345   if (SS.isNotEmpty()) {
14346     if (SS.isSet()) {
14347       // If this is either a declaration or a definition, check the
14348       // nested-name-specifier against the current context.
14349       if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14350           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14351                                        isMemberSpecialization))
14352         Invalid = true;
14353 
14354       New->setQualifierInfo(SS.getWithLocInContext(Context));
14355       if (TemplateParameterLists.size() > 0) {
14356         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14357       }
14358     }
14359     else
14360       Invalid = true;
14361   }
14362 
14363   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14364     // Add alignment attributes if necessary; these attributes are checked when
14365     // the ASTContext lays out the structure.
14366     //
14367     // It is important for implementing the correct semantics that this
14368     // happen here (in ActOnTag). The #pragma pack stack is
14369     // maintained as a result of parser callbacks which can occur at
14370     // many points during the parsing of a struct declaration (because
14371     // the #pragma tokens are effectively skipped over during the
14372     // parsing of the struct).
14373     if (TUK == TUK_Definition) {
14374       AddAlignmentAttributesForRecord(RD);
14375       AddMsStructLayoutForRecord(RD);
14376     }
14377   }
14378 
14379   if (ModulePrivateLoc.isValid()) {
14380     if (isMemberSpecialization)
14381       Diag(New->getLocation(), diag::err_module_private_specialization)
14382         << 2
14383         << FixItHint::CreateRemoval(ModulePrivateLoc);
14384     // __module_private__ does not apply to local classes. However, we only
14385     // diagnose this as an error when the declaration specifiers are
14386     // freestanding. Here, we just ignore the __module_private__.
14387     else if (!SearchDC->isFunctionOrMethod())
14388       New->setModulePrivate();
14389   }
14390 
14391   // If this is a specialization of a member class (of a class template),
14392   // check the specialization.
14393   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14394     Invalid = true;
14395 
14396   // If we're declaring or defining a tag in function prototype scope in C,
14397   // note that this type can only be used within the function and add it to
14398   // the list of decls to inject into the function definition scope.
14399   if ((Name || Kind == TTK_Enum) &&
14400       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14401     if (getLangOpts().CPlusPlus) {
14402       // C++ [dcl.fct]p6:
14403       //   Types shall not be defined in return or parameter types.
14404       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14405         Diag(Loc, diag::err_type_defined_in_param_type)
14406             << Name;
14407         Invalid = true;
14408       }
14409     } else if (!PrevDecl) {
14410       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14411     }
14412   }
14413 
14414   if (Invalid)
14415     New->setInvalidDecl();
14416 
14417   // Set the lexical context. If the tag has a C++ scope specifier, the
14418   // lexical context will be different from the semantic context.
14419   New->setLexicalDeclContext(CurContext);
14420 
14421   // Mark this as a friend decl if applicable.
14422   // In Microsoft mode, a friend declaration also acts as a forward
14423   // declaration so we always pass true to setObjectOfFriendDecl to make
14424   // the tag name visible.
14425   if (TUK == TUK_Friend)
14426     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14427 
14428   // Set the access specifier.
14429   if (!Invalid && SearchDC->isRecord())
14430     SetMemberAccessSpecifier(New, PrevDecl, AS);
14431 
14432   if (PrevDecl)
14433     CheckRedeclarationModuleOwnership(New, PrevDecl);
14434 
14435   if (TUK == TUK_Definition)
14436     New->startDefinition();
14437 
14438   if (Attr)
14439     ProcessDeclAttributeList(S, New, Attr);
14440   AddPragmaAttributes(S, New);
14441 
14442   // If this has an identifier, add it to the scope stack.
14443   if (TUK == TUK_Friend) {
14444     // We might be replacing an existing declaration in the lookup tables;
14445     // if so, borrow its access specifier.
14446     if (PrevDecl)
14447       New->setAccess(PrevDecl->getAccess());
14448 
14449     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14450     DC->makeDeclVisibleInContext(New);
14451     if (Name) // can be null along some error paths
14452       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14453         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14454   } else if (Name) {
14455     S = getNonFieldDeclScope(S);
14456     PushOnScopeChains(New, S, !IsForwardReference);
14457     if (IsForwardReference)
14458       SearchDC->makeDeclVisibleInContext(New);
14459   } else {
14460     CurContext->addDecl(New);
14461   }
14462 
14463   // If this is the C FILE type, notify the AST context.
14464   if (IdentifierInfo *II = New->getIdentifier())
14465     if (!New->isInvalidDecl() &&
14466         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14467         II->isStr("FILE"))
14468       Context.setFILEDecl(New);
14469 
14470   if (PrevDecl)
14471     mergeDeclAttributes(New, PrevDecl);
14472 
14473   // If there's a #pragma GCC visibility in scope, set the visibility of this
14474   // record.
14475   AddPushedVisibilityAttribute(New);
14476 
14477   if (isMemberSpecialization && !New->isInvalidDecl())
14478     CompleteMemberSpecialization(New, Previous);
14479 
14480   OwnedDecl = true;
14481   // In C++, don't return an invalid declaration. We can't recover well from
14482   // the cases where we make the type anonymous.
14483   if (Invalid && getLangOpts().CPlusPlus) {
14484     if (New->isBeingDefined())
14485       if (auto RD = dyn_cast<RecordDecl>(New))
14486         RD->completeDefinition();
14487     return nullptr;
14488   } else {
14489     return New;
14490   }
14491 }
14492 
14493 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14494   AdjustDeclIfTemplate(TagD);
14495   TagDecl *Tag = cast<TagDecl>(TagD);
14496 
14497   // Enter the tag context.
14498   PushDeclContext(S, Tag);
14499 
14500   ActOnDocumentableDecl(TagD);
14501 
14502   // If there's a #pragma GCC visibility in scope, set the visibility of this
14503   // record.
14504   AddPushedVisibilityAttribute(Tag);
14505 }
14506 
14507 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14508                                     SkipBodyInfo &SkipBody) {
14509   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14510     return false;
14511 
14512   // Make the previous decl visible.
14513   makeMergedDefinitionVisible(SkipBody.Previous);
14514   return true;
14515 }
14516 
14517 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14518   assert(isa<ObjCContainerDecl>(IDecl) &&
14519          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14520   DeclContext *OCD = cast<DeclContext>(IDecl);
14521   assert(getContainingDC(OCD) == CurContext &&
14522       "The next DeclContext should be lexically contained in the current one.");
14523   CurContext = OCD;
14524   return IDecl;
14525 }
14526 
14527 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14528                                            SourceLocation FinalLoc,
14529                                            bool IsFinalSpelledSealed,
14530                                            SourceLocation LBraceLoc) {
14531   AdjustDeclIfTemplate(TagD);
14532   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14533 
14534   FieldCollector->StartClass();
14535 
14536   if (!Record->getIdentifier())
14537     return;
14538 
14539   if (FinalLoc.isValid())
14540     Record->addAttr(new (Context)
14541                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14542 
14543   // C++ [class]p2:
14544   //   [...] The class-name is also inserted into the scope of the
14545   //   class itself; this is known as the injected-class-name. For
14546   //   purposes of access checking, the injected-class-name is treated
14547   //   as if it were a public member name.
14548   CXXRecordDecl *InjectedClassName
14549     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14550                             Record->getLocStart(), Record->getLocation(),
14551                             Record->getIdentifier(),
14552                             /*PrevDecl=*/nullptr,
14553                             /*DelayTypeCreation=*/true);
14554   Context.getTypeDeclType(InjectedClassName, Record);
14555   InjectedClassName->setImplicit();
14556   InjectedClassName->setAccess(AS_public);
14557   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14558       InjectedClassName->setDescribedClassTemplate(Template);
14559   PushOnScopeChains(InjectedClassName, S);
14560   assert(InjectedClassName->isInjectedClassName() &&
14561          "Broken injected-class-name");
14562 }
14563 
14564 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14565                                     SourceRange BraceRange) {
14566   AdjustDeclIfTemplate(TagD);
14567   TagDecl *Tag = cast<TagDecl>(TagD);
14568   Tag->setBraceRange(BraceRange);
14569 
14570   // Make sure we "complete" the definition even it is invalid.
14571   if (Tag->isBeingDefined()) {
14572     assert(Tag->isInvalidDecl() && "We should already have completed it");
14573     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14574       RD->completeDefinition();
14575   }
14576 
14577   if (isa<CXXRecordDecl>(Tag)) {
14578     FieldCollector->FinishClass();
14579   }
14580 
14581   // Exit this scope of this tag's definition.
14582   PopDeclContext();
14583 
14584   if (getCurLexicalContext()->isObjCContainer() &&
14585       Tag->getDeclContext()->isFileContext())
14586     Tag->setTopLevelDeclInObjCContainer();
14587 
14588   // Notify the consumer that we've defined a tag.
14589   if (!Tag->isInvalidDecl())
14590     Consumer.HandleTagDeclDefinition(Tag);
14591 }
14592 
14593 void Sema::ActOnObjCContainerFinishDefinition() {
14594   // Exit this scope of this interface definition.
14595   PopDeclContext();
14596 }
14597 
14598 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14599   assert(DC == CurContext && "Mismatch of container contexts");
14600   OriginalLexicalContext = DC;
14601   ActOnObjCContainerFinishDefinition();
14602 }
14603 
14604 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14605   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14606   OriginalLexicalContext = nullptr;
14607 }
14608 
14609 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14610   AdjustDeclIfTemplate(TagD);
14611   TagDecl *Tag = cast<TagDecl>(TagD);
14612   Tag->setInvalidDecl();
14613 
14614   // Make sure we "complete" the definition even it is invalid.
14615   if (Tag->isBeingDefined()) {
14616     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14617       RD->completeDefinition();
14618   }
14619 
14620   // We're undoing ActOnTagStartDefinition here, not
14621   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14622   // the FieldCollector.
14623 
14624   PopDeclContext();
14625 }
14626 
14627 // Note that FieldName may be null for anonymous bitfields.
14628 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14629                                 IdentifierInfo *FieldName,
14630                                 QualType FieldTy, bool IsMsStruct,
14631                                 Expr *BitWidth, bool *ZeroWidth) {
14632   // Default to true; that shouldn't confuse checks for emptiness
14633   if (ZeroWidth)
14634     *ZeroWidth = true;
14635 
14636   // C99 6.7.2.1p4 - verify the field type.
14637   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14638   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14639     // Handle incomplete types with specific error.
14640     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14641       return ExprError();
14642     if (FieldName)
14643       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14644         << FieldName << FieldTy << BitWidth->getSourceRange();
14645     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14646       << FieldTy << BitWidth->getSourceRange();
14647   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14648                                              UPPC_BitFieldWidth))
14649     return ExprError();
14650 
14651   // If the bit-width is type- or value-dependent, don't try to check
14652   // it now.
14653   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14654     return BitWidth;
14655 
14656   llvm::APSInt Value;
14657   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14658   if (ICE.isInvalid())
14659     return ICE;
14660   BitWidth = ICE.get();
14661 
14662   if (Value != 0 && ZeroWidth)
14663     *ZeroWidth = false;
14664 
14665   // Zero-width bitfield is ok for anonymous field.
14666   if (Value == 0 && FieldName)
14667     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14668 
14669   if (Value.isSigned() && Value.isNegative()) {
14670     if (FieldName)
14671       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14672                << FieldName << Value.toString(10);
14673     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14674       << Value.toString(10);
14675   }
14676 
14677   if (!FieldTy->isDependentType()) {
14678     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14679     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14680     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14681 
14682     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14683     // ABI.
14684     bool CStdConstraintViolation =
14685         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14686     bool MSBitfieldViolation =
14687         Value.ugt(TypeStorageSize) &&
14688         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14689     if (CStdConstraintViolation || MSBitfieldViolation) {
14690       unsigned DiagWidth =
14691           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14692       if (FieldName)
14693         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14694                << FieldName << (unsigned)Value.getZExtValue()
14695                << !CStdConstraintViolation << DiagWidth;
14696 
14697       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14698              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14699              << DiagWidth;
14700     }
14701 
14702     // Warn on types where the user might conceivably expect to get all
14703     // specified bits as value bits: that's all integral types other than
14704     // 'bool'.
14705     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14706       if (FieldName)
14707         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14708             << FieldName << (unsigned)Value.getZExtValue()
14709             << (unsigned)TypeWidth;
14710       else
14711         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14712             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14713     }
14714   }
14715 
14716   return BitWidth;
14717 }
14718 
14719 /// ActOnField - Each field of a C struct/union is passed into this in order
14720 /// to create a FieldDecl object for it.
14721 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14722                        Declarator &D, Expr *BitfieldWidth) {
14723   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14724                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14725                                /*InitStyle=*/ICIS_NoInit, AS_public);
14726   return Res;
14727 }
14728 
14729 /// HandleField - Analyze a field of a C struct or a C++ data member.
14730 ///
14731 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14732                              SourceLocation DeclStart,
14733                              Declarator &D, Expr *BitWidth,
14734                              InClassInitStyle InitStyle,
14735                              AccessSpecifier AS) {
14736   if (D.isDecompositionDeclarator()) {
14737     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14738     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14739       << Decomp.getSourceRange();
14740     return nullptr;
14741   }
14742 
14743   IdentifierInfo *II = D.getIdentifier();
14744   SourceLocation Loc = DeclStart;
14745   if (II) Loc = D.getIdentifierLoc();
14746 
14747   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14748   QualType T = TInfo->getType();
14749   if (getLangOpts().CPlusPlus) {
14750     CheckExtraCXXDefaultArguments(D);
14751 
14752     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14753                                         UPPC_DataMemberType)) {
14754       D.setInvalidType();
14755       T = Context.IntTy;
14756       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14757     }
14758   }
14759 
14760   // TR 18037 does not allow fields to be declared with address spaces.
14761   if (T.getQualifiers().hasAddressSpace() ||
14762       T->isDependentAddressSpaceType() ||
14763       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14764     Diag(Loc, diag::err_field_with_address_space);
14765     D.setInvalidType();
14766   }
14767 
14768   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14769   // used as structure or union field: image, sampler, event or block types.
14770   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14771                           T->isSamplerT() || T->isBlockPointerType())) {
14772     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14773     D.setInvalidType();
14774   }
14775 
14776   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14777 
14778   if (D.getDeclSpec().isInlineSpecified())
14779     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14780         << getLangOpts().CPlusPlus17;
14781   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14782     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14783          diag::err_invalid_thread)
14784       << DeclSpec::getSpecifierName(TSCS);
14785 
14786   // Check to see if this name was declared as a member previously
14787   NamedDecl *PrevDecl = nullptr;
14788   LookupResult Previous(*this, II, Loc, LookupMemberName,
14789                         ForVisibleRedeclaration);
14790   LookupName(Previous, S);
14791   switch (Previous.getResultKind()) {
14792     case LookupResult::Found:
14793     case LookupResult::FoundUnresolvedValue:
14794       PrevDecl = Previous.getAsSingle<NamedDecl>();
14795       break;
14796 
14797     case LookupResult::FoundOverloaded:
14798       PrevDecl = Previous.getRepresentativeDecl();
14799       break;
14800 
14801     case LookupResult::NotFound:
14802     case LookupResult::NotFoundInCurrentInstantiation:
14803     case LookupResult::Ambiguous:
14804       break;
14805   }
14806   Previous.suppressDiagnostics();
14807 
14808   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14809     // Maybe we will complain about the shadowed template parameter.
14810     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14811     // Just pretend that we didn't see the previous declaration.
14812     PrevDecl = nullptr;
14813   }
14814 
14815   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14816     PrevDecl = nullptr;
14817 
14818   bool Mutable
14819     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14820   SourceLocation TSSL = D.getLocStart();
14821   FieldDecl *NewFD
14822     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14823                      TSSL, AS, PrevDecl, &D);
14824 
14825   if (NewFD->isInvalidDecl())
14826     Record->setInvalidDecl();
14827 
14828   if (D.getDeclSpec().isModulePrivateSpecified())
14829     NewFD->setModulePrivate();
14830 
14831   if (NewFD->isInvalidDecl() && PrevDecl) {
14832     // Don't introduce NewFD into scope; there's already something
14833     // with the same name in the same scope.
14834   } else if (II) {
14835     PushOnScopeChains(NewFD, S);
14836   } else
14837     Record->addDecl(NewFD);
14838 
14839   return NewFD;
14840 }
14841 
14842 /// \brief Build a new FieldDecl and check its well-formedness.
14843 ///
14844 /// This routine builds a new FieldDecl given the fields name, type,
14845 /// record, etc. \p PrevDecl should refer to any previous declaration
14846 /// with the same name and in the same scope as the field to be
14847 /// created.
14848 ///
14849 /// \returns a new FieldDecl.
14850 ///
14851 /// \todo The Declarator argument is a hack. It will be removed once
14852 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14853                                 TypeSourceInfo *TInfo,
14854                                 RecordDecl *Record, SourceLocation Loc,
14855                                 bool Mutable, Expr *BitWidth,
14856                                 InClassInitStyle InitStyle,
14857                                 SourceLocation TSSL,
14858                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14859                                 Declarator *D) {
14860   IdentifierInfo *II = Name.getAsIdentifierInfo();
14861   bool InvalidDecl = false;
14862   if (D) InvalidDecl = D->isInvalidType();
14863 
14864   // If we receive a broken type, recover by assuming 'int' and
14865   // marking this declaration as invalid.
14866   if (T.isNull()) {
14867     InvalidDecl = true;
14868     T = Context.IntTy;
14869   }
14870 
14871   QualType EltTy = Context.getBaseElementType(T);
14872   if (!EltTy->isDependentType()) {
14873     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14874       // Fields of incomplete type force their record to be invalid.
14875       Record->setInvalidDecl();
14876       InvalidDecl = true;
14877     } else {
14878       NamedDecl *Def;
14879       EltTy->isIncompleteType(&Def);
14880       if (Def && Def->isInvalidDecl()) {
14881         Record->setInvalidDecl();
14882         InvalidDecl = true;
14883       }
14884     }
14885   }
14886 
14887   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14888   if (BitWidth && getLangOpts().OpenCL) {
14889     Diag(Loc, diag::err_opencl_bitfields);
14890     InvalidDecl = true;
14891   }
14892 
14893   // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
14894   if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
14895       T.hasQualifiers()) {
14896     InvalidDecl = true;
14897     Diag(Loc, diag::err_anon_bitfield_qualifiers);
14898   }
14899 
14900   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14901   // than a variably modified type.
14902   if (!InvalidDecl && T->isVariablyModifiedType()) {
14903     bool SizeIsNegative;
14904     llvm::APSInt Oversized;
14905 
14906     TypeSourceInfo *FixedTInfo =
14907       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14908                                                     SizeIsNegative,
14909                                                     Oversized);
14910     if (FixedTInfo) {
14911       Diag(Loc, diag::warn_illegal_constant_array_size);
14912       TInfo = FixedTInfo;
14913       T = FixedTInfo->getType();
14914     } else {
14915       if (SizeIsNegative)
14916         Diag(Loc, diag::err_typecheck_negative_array_size);
14917       else if (Oversized.getBoolValue())
14918         Diag(Loc, diag::err_array_too_large)
14919           << Oversized.toString(10);
14920       else
14921         Diag(Loc, diag::err_typecheck_field_variable_size);
14922       InvalidDecl = true;
14923     }
14924   }
14925 
14926   // Fields can not have abstract class types
14927   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14928                                              diag::err_abstract_type_in_decl,
14929                                              AbstractFieldType))
14930     InvalidDecl = true;
14931 
14932   bool ZeroWidth = false;
14933   if (InvalidDecl)
14934     BitWidth = nullptr;
14935   // If this is declared as a bit-field, check the bit-field.
14936   if (BitWidth) {
14937     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14938                               &ZeroWidth).get();
14939     if (!BitWidth) {
14940       InvalidDecl = true;
14941       BitWidth = nullptr;
14942       ZeroWidth = false;
14943     }
14944   }
14945 
14946   // Check that 'mutable' is consistent with the type of the declaration.
14947   if (!InvalidDecl && Mutable) {
14948     unsigned DiagID = 0;
14949     if (T->isReferenceType())
14950       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14951                                         : diag::err_mutable_reference;
14952     else if (T.isConstQualified())
14953       DiagID = diag::err_mutable_const;
14954 
14955     if (DiagID) {
14956       SourceLocation ErrLoc = Loc;
14957       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14958         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14959       Diag(ErrLoc, DiagID);
14960       if (DiagID != diag::ext_mutable_reference) {
14961         Mutable = false;
14962         InvalidDecl = true;
14963       }
14964     }
14965   }
14966 
14967   // C++11 [class.union]p8 (DR1460):
14968   //   At most one variant member of a union may have a
14969   //   brace-or-equal-initializer.
14970   if (InitStyle != ICIS_NoInit)
14971     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14972 
14973   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14974                                        BitWidth, Mutable, InitStyle);
14975   if (InvalidDecl)
14976     NewFD->setInvalidDecl();
14977 
14978   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14979     Diag(Loc, diag::err_duplicate_member) << II;
14980     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14981     NewFD->setInvalidDecl();
14982   }
14983 
14984   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14985     if (Record->isUnion()) {
14986       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14987         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14988         if (RDecl->getDefinition()) {
14989           // C++ [class.union]p1: An object of a class with a non-trivial
14990           // constructor, a non-trivial copy constructor, a non-trivial
14991           // destructor, or a non-trivial copy assignment operator
14992           // cannot be a member of a union, nor can an array of such
14993           // objects.
14994           if (CheckNontrivialField(NewFD))
14995             NewFD->setInvalidDecl();
14996         }
14997       }
14998 
14999       // C++ [class.union]p1: If a union contains a member of reference type,
15000       // the program is ill-formed, except when compiling with MSVC extensions
15001       // enabled.
15002       if (EltTy->isReferenceType()) {
15003         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15004                                     diag::ext_union_member_of_reference_type :
15005                                     diag::err_union_member_of_reference_type)
15006           << NewFD->getDeclName() << EltTy;
15007         if (!getLangOpts().MicrosoftExt)
15008           NewFD->setInvalidDecl();
15009       }
15010     }
15011   }
15012 
15013   // FIXME: We need to pass in the attributes given an AST
15014   // representation, not a parser representation.
15015   if (D) {
15016     // FIXME: The current scope is almost... but not entirely... correct here.
15017     ProcessDeclAttributes(getCurScope(), NewFD, *D);
15018 
15019     if (NewFD->hasAttrs())
15020       CheckAlignasUnderalignment(NewFD);
15021   }
15022 
15023   // In auto-retain/release, infer strong retension for fields of
15024   // retainable type.
15025   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15026     NewFD->setInvalidDecl();
15027 
15028   if (T.isObjCGCWeak())
15029     Diag(Loc, diag::warn_attribute_weak_on_field);
15030 
15031   NewFD->setAccess(AS);
15032   return NewFD;
15033 }
15034 
15035 bool Sema::CheckNontrivialField(FieldDecl *FD) {
15036   assert(FD);
15037   assert(getLangOpts().CPlusPlus && "valid check only for C++");
15038 
15039   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15040     return false;
15041 
15042   QualType EltTy = Context.getBaseElementType(FD->getType());
15043   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15044     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15045     if (RDecl->getDefinition()) {
15046       // We check for copy constructors before constructors
15047       // because otherwise we'll never get complaints about
15048       // copy constructors.
15049 
15050       CXXSpecialMember member = CXXInvalid;
15051       // We're required to check for any non-trivial constructors. Since the
15052       // implicit default constructor is suppressed if there are any
15053       // user-declared constructors, we just need to check that there is a
15054       // trivial default constructor and a trivial copy constructor. (We don't
15055       // worry about move constructors here, since this is a C++98 check.)
15056       if (RDecl->hasNonTrivialCopyConstructor())
15057         member = CXXCopyConstructor;
15058       else if (!RDecl->hasTrivialDefaultConstructor())
15059         member = CXXDefaultConstructor;
15060       else if (RDecl->hasNonTrivialCopyAssignment())
15061         member = CXXCopyAssignment;
15062       else if (RDecl->hasNonTrivialDestructor())
15063         member = CXXDestructor;
15064 
15065       if (member != CXXInvalid) {
15066         if (!getLangOpts().CPlusPlus11 &&
15067             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15068           // Objective-C++ ARC: it is an error to have a non-trivial field of
15069           // a union. However, system headers in Objective-C programs
15070           // occasionally have Objective-C lifetime objects within unions,
15071           // and rather than cause the program to fail, we make those
15072           // members unavailable.
15073           SourceLocation Loc = FD->getLocation();
15074           if (getSourceManager().isInSystemHeader(Loc)) {
15075             if (!FD->hasAttr<UnavailableAttr>())
15076               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15077                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15078             return false;
15079           }
15080         }
15081 
15082         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15083                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15084                diag::err_illegal_union_or_anon_struct_member)
15085           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15086         DiagnoseNontrivial(RDecl, member);
15087         return !getLangOpts().CPlusPlus11;
15088       }
15089     }
15090   }
15091 
15092   return false;
15093 }
15094 
15095 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15096 ///  AST enum value.
15097 static ObjCIvarDecl::AccessControl
15098 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15099   switch (ivarVisibility) {
15100   default: llvm_unreachable("Unknown visitibility kind");
15101   case tok::objc_private: return ObjCIvarDecl::Private;
15102   case tok::objc_public: return ObjCIvarDecl::Public;
15103   case tok::objc_protected: return ObjCIvarDecl::Protected;
15104   case tok::objc_package: return ObjCIvarDecl::Package;
15105   }
15106 }
15107 
15108 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15109 /// in order to create an IvarDecl object for it.
15110 Decl *Sema::ActOnIvar(Scope *S,
15111                                 SourceLocation DeclStart,
15112                                 Declarator &D, Expr *BitfieldWidth,
15113                                 tok::ObjCKeywordKind Visibility) {
15114 
15115   IdentifierInfo *II = D.getIdentifier();
15116   Expr *BitWidth = (Expr*)BitfieldWidth;
15117   SourceLocation Loc = DeclStart;
15118   if (II) Loc = D.getIdentifierLoc();
15119 
15120   // FIXME: Unnamed fields can be handled in various different ways, for
15121   // example, unnamed unions inject all members into the struct namespace!
15122 
15123   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15124   QualType T = TInfo->getType();
15125 
15126   if (BitWidth) {
15127     // 6.7.2.1p3, 6.7.2.1p4
15128     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15129     if (!BitWidth)
15130       D.setInvalidType();
15131   } else {
15132     // Not a bitfield.
15133 
15134     // validate II.
15135 
15136   }
15137   if (T->isReferenceType()) {
15138     Diag(Loc, diag::err_ivar_reference_type);
15139     D.setInvalidType();
15140   }
15141   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15142   // than a variably modified type.
15143   else if (T->isVariablyModifiedType()) {
15144     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15145     D.setInvalidType();
15146   }
15147 
15148   // Get the visibility (access control) for this ivar.
15149   ObjCIvarDecl::AccessControl ac =
15150     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15151                                         : ObjCIvarDecl::None;
15152   // Must set ivar's DeclContext to its enclosing interface.
15153   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15154   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15155     return nullptr;
15156   ObjCContainerDecl *EnclosingContext;
15157   if (ObjCImplementationDecl *IMPDecl =
15158       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15159     if (LangOpts.ObjCRuntime.isFragile()) {
15160     // Case of ivar declared in an implementation. Context is that of its class.
15161       EnclosingContext = IMPDecl->getClassInterface();
15162       assert(EnclosingContext && "Implementation has no class interface!");
15163     }
15164     else
15165       EnclosingContext = EnclosingDecl;
15166   } else {
15167     if (ObjCCategoryDecl *CDecl =
15168         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15169       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15170         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15171         return nullptr;
15172       }
15173     }
15174     EnclosingContext = EnclosingDecl;
15175   }
15176 
15177   // Construct the decl.
15178   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15179                                              DeclStart, Loc, II, T,
15180                                              TInfo, ac, (Expr *)BitfieldWidth);
15181 
15182   if (II) {
15183     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15184                                            ForVisibleRedeclaration);
15185     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15186         && !isa<TagDecl>(PrevDecl)) {
15187       Diag(Loc, diag::err_duplicate_member) << II;
15188       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15189       NewID->setInvalidDecl();
15190     }
15191   }
15192 
15193   // Process attributes attached to the ivar.
15194   ProcessDeclAttributes(S, NewID, D);
15195 
15196   if (D.isInvalidType())
15197     NewID->setInvalidDecl();
15198 
15199   // In ARC, infer 'retaining' for ivars of retainable type.
15200   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15201     NewID->setInvalidDecl();
15202 
15203   if (D.getDeclSpec().isModulePrivateSpecified())
15204     NewID->setModulePrivate();
15205 
15206   if (II) {
15207     // FIXME: When interfaces are DeclContexts, we'll need to add
15208     // these to the interface.
15209     S->AddDecl(NewID);
15210     IdResolver.AddDecl(NewID);
15211   }
15212 
15213   if (LangOpts.ObjCRuntime.isNonFragile() &&
15214       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15215     Diag(Loc, diag::warn_ivars_in_interface);
15216 
15217   return NewID;
15218 }
15219 
15220 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15221 /// class and class extensions. For every class \@interface and class
15222 /// extension \@interface, if the last ivar is a bitfield of any type,
15223 /// then add an implicit `char :0` ivar to the end of that interface.
15224 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15225                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15226   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15227     return;
15228 
15229   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15230   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15231 
15232   if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15233     return;
15234   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15235   if (!ID) {
15236     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15237       if (!CD->IsClassExtension())
15238         return;
15239     }
15240     // No need to add this to end of @implementation.
15241     else
15242       return;
15243   }
15244   // All conditions are met. Add a new bitfield to the tail end of ivars.
15245   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15246   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15247 
15248   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15249                               DeclLoc, DeclLoc, nullptr,
15250                               Context.CharTy,
15251                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15252                                                                DeclLoc),
15253                               ObjCIvarDecl::Private, BW,
15254                               true);
15255   AllIvarDecls.push_back(Ivar);
15256 }
15257 
15258 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15259                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15260                        SourceLocation RBrac, AttributeList *Attr) {
15261   assert(EnclosingDecl && "missing record or interface decl");
15262 
15263   // If this is an Objective-C @implementation or category and we have
15264   // new fields here we should reset the layout of the interface since
15265   // it will now change.
15266   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15267     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15268     switch (DC->getKind()) {
15269     default: break;
15270     case Decl::ObjCCategory:
15271       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15272       break;
15273     case Decl::ObjCImplementation:
15274       Context.
15275         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15276       break;
15277     }
15278   }
15279 
15280   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15281 
15282   // Start counting up the number of named members; make sure to include
15283   // members of anonymous structs and unions in the total.
15284   unsigned NumNamedMembers = 0;
15285   if (Record) {
15286     for (const auto *I : Record->decls()) {
15287       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15288         if (IFD->getDeclName())
15289           ++NumNamedMembers;
15290     }
15291   }
15292 
15293   // Verify that all the fields are okay.
15294   SmallVector<FieldDecl*, 32> RecFields;
15295 
15296   bool ObjCFieldLifetimeErrReported = false;
15297   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15298        i != end; ++i) {
15299     FieldDecl *FD = cast<FieldDecl>(*i);
15300 
15301     // Get the type for the field.
15302     const Type *FDTy = FD->getType().getTypePtr();
15303 
15304     if (!FD->isAnonymousStructOrUnion()) {
15305       // Remember all fields written by the user.
15306       RecFields.push_back(FD);
15307     }
15308 
15309     // If the field is already invalid for some reason, don't emit more
15310     // diagnostics about it.
15311     if (FD->isInvalidDecl()) {
15312       EnclosingDecl->setInvalidDecl();
15313       continue;
15314     }
15315 
15316     // C99 6.7.2.1p2:
15317     //   A structure or union shall not contain a member with
15318     //   incomplete or function type (hence, a structure shall not
15319     //   contain an instance of itself, but may contain a pointer to
15320     //   an instance of itself), except that the last member of a
15321     //   structure with more than one named member may have incomplete
15322     //   array type; such a structure (and any union containing,
15323     //   possibly recursively, a member that is such a structure)
15324     //   shall not be a member of a structure or an element of an
15325     //   array.
15326     bool IsLastField = (i + 1 == Fields.end());
15327     if (FDTy->isFunctionType()) {
15328       // Field declared as a function.
15329       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15330         << FD->getDeclName();
15331       FD->setInvalidDecl();
15332       EnclosingDecl->setInvalidDecl();
15333       continue;
15334     } else if (FDTy->isIncompleteArrayType() &&
15335                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15336       if (Record) {
15337         // Flexible array member.
15338         // Microsoft and g++ is more permissive regarding flexible array.
15339         // It will accept flexible array in union and also
15340         // as the sole element of a struct/class.
15341         unsigned DiagID = 0;
15342         if (!Record->isUnion() && !IsLastField) {
15343           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15344             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15345           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15346           FD->setInvalidDecl();
15347           EnclosingDecl->setInvalidDecl();
15348           continue;
15349         } else if (Record->isUnion())
15350           DiagID = getLangOpts().MicrosoftExt
15351                        ? diag::ext_flexible_array_union_ms
15352                        : getLangOpts().CPlusPlus
15353                              ? diag::ext_flexible_array_union_gnu
15354                              : diag::err_flexible_array_union;
15355         else if (NumNamedMembers < 1)
15356           DiagID = getLangOpts().MicrosoftExt
15357                        ? diag::ext_flexible_array_empty_aggregate_ms
15358                        : getLangOpts().CPlusPlus
15359                              ? diag::ext_flexible_array_empty_aggregate_gnu
15360                              : diag::err_flexible_array_empty_aggregate;
15361 
15362         if (DiagID)
15363           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15364                                           << Record->getTagKind();
15365         // While the layout of types that contain virtual bases is not specified
15366         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15367         // virtual bases after the derived members.  This would make a flexible
15368         // array member declared at the end of an object not adjacent to the end
15369         // of the type.
15370         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15371           if (RD->getNumVBases() != 0)
15372             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15373               << FD->getDeclName() << Record->getTagKind();
15374         if (!getLangOpts().C99)
15375           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15376             << FD->getDeclName() << Record->getTagKind();
15377 
15378         // If the element type has a non-trivial destructor, we would not
15379         // implicitly destroy the elements, so disallow it for now.
15380         //
15381         // FIXME: GCC allows this. We should probably either implicitly delete
15382         // the destructor of the containing class, or just allow this.
15383         QualType BaseElem = Context.getBaseElementType(FD->getType());
15384         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15385           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15386             << FD->getDeclName() << FD->getType();
15387           FD->setInvalidDecl();
15388           EnclosingDecl->setInvalidDecl();
15389           continue;
15390         }
15391         // Okay, we have a legal flexible array member at the end of the struct.
15392         Record->setHasFlexibleArrayMember(true);
15393       } else {
15394         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15395         // unless they are followed by another ivar. That check is done
15396         // elsewhere, after synthesized ivars are known.
15397       }
15398     } else if (!FDTy->isDependentType() &&
15399                RequireCompleteType(FD->getLocation(), FD->getType(),
15400                                    diag::err_field_incomplete)) {
15401       // Incomplete type
15402       FD->setInvalidDecl();
15403       EnclosingDecl->setInvalidDecl();
15404       continue;
15405     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15406       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15407         // A type which contains a flexible array member is considered to be a
15408         // flexible array member.
15409         Record->setHasFlexibleArrayMember(true);
15410         if (!Record->isUnion()) {
15411           // If this is a struct/class and this is not the last element, reject
15412           // it.  Note that GCC supports variable sized arrays in the middle of
15413           // structures.
15414           if (!IsLastField)
15415             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15416               << FD->getDeclName() << FD->getType();
15417           else {
15418             // We support flexible arrays at the end of structs in
15419             // other structs as an extension.
15420             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15421               << FD->getDeclName();
15422           }
15423         }
15424       }
15425       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15426           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15427                                  diag::err_abstract_type_in_decl,
15428                                  AbstractIvarType)) {
15429         // Ivars can not have abstract class types
15430         FD->setInvalidDecl();
15431       }
15432       if (Record && FDTTy->getDecl()->hasObjectMember())
15433         Record->setHasObjectMember(true);
15434       if (Record && FDTTy->getDecl()->hasVolatileMember())
15435         Record->setHasVolatileMember(true);
15436     } else if (FDTy->isObjCObjectType()) {
15437       /// A field cannot be an Objective-c object
15438       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15439         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15440       QualType T = Context.getObjCObjectPointerType(FD->getType());
15441       FD->setType(T);
15442     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15443                Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15444       // It's an error in ARC or Weak if a field has lifetime.
15445       // We don't want to report this in a system header, though,
15446       // so we just make the field unavailable.
15447       // FIXME: that's really not sufficient; we need to make the type
15448       // itself invalid to, say, initialize or copy.
15449       QualType T = FD->getType();
15450       if (T.hasNonTrivialObjCLifetime()) {
15451         SourceLocation loc = FD->getLocation();
15452         if (getSourceManager().isInSystemHeader(loc)) {
15453           if (!FD->hasAttr<UnavailableAttr>()) {
15454             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15455                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15456           }
15457         } else {
15458           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15459             << T->isBlockPointerType() << Record->getTagKind();
15460         }
15461         ObjCFieldLifetimeErrReported = true;
15462       }
15463     } else if (getLangOpts().ObjC1 &&
15464                getLangOpts().getGC() != LangOptions::NonGC &&
15465                Record && !Record->hasObjectMember()) {
15466       if (FD->getType()->isObjCObjectPointerType() ||
15467           FD->getType().isObjCGCStrong())
15468         Record->setHasObjectMember(true);
15469       else if (Context.getAsArrayType(FD->getType())) {
15470         QualType BaseType = Context.getBaseElementType(FD->getType());
15471         if (BaseType->isRecordType() &&
15472             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15473           Record->setHasObjectMember(true);
15474         else if (BaseType->isObjCObjectPointerType() ||
15475                  BaseType.isObjCGCStrong())
15476                Record->setHasObjectMember(true);
15477       }
15478     }
15479 
15480     if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15481       QualType FT = FD->getType();
15482       if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15483         Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15484       QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15485       if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15486         Record->setNonTrivialToPrimitiveCopy(true);
15487       if (FT.isDestructedType()) {
15488         Record->setNonTrivialToPrimitiveDestroy(true);
15489         Record->setParamDestroyedInCallee(true);
15490       }
15491 
15492       if (const auto *RT = FT->getAs<RecordType>()) {
15493         if (RT->getDecl()->getArgPassingRestrictions() ==
15494             RecordDecl::APK_CanNeverPassInRegs)
15495           Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15496       } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15497         Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15498     }
15499 
15500     if (Record && FD->getType().isVolatileQualified())
15501       Record->setHasVolatileMember(true);
15502     // Keep track of the number of named members.
15503     if (FD->getIdentifier())
15504       ++NumNamedMembers;
15505   }
15506 
15507   // Okay, we successfully defined 'Record'.
15508   if (Record) {
15509     bool Completed = false;
15510     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15511       if (!CXXRecord->isInvalidDecl()) {
15512         // Set access bits correctly on the directly-declared conversions.
15513         for (CXXRecordDecl::conversion_iterator
15514                I = CXXRecord->conversion_begin(),
15515                E = CXXRecord->conversion_end(); I != E; ++I)
15516           I.setAccess((*I)->getAccess());
15517       }
15518 
15519       if (!CXXRecord->isDependentType()) {
15520         if (CXXRecord->hasUserDeclaredDestructor()) {
15521           // Adjust user-defined destructor exception spec.
15522           if (getLangOpts().CPlusPlus11)
15523             AdjustDestructorExceptionSpec(CXXRecord,
15524                                           CXXRecord->getDestructor());
15525         }
15526 
15527         // Add any implicitly-declared members to this class.
15528         AddImplicitlyDeclaredMembersToClass(CXXRecord);
15529 
15530         if (!CXXRecord->isInvalidDecl()) {
15531           // If we have virtual base classes, we may end up finding multiple
15532           // final overriders for a given virtual function. Check for this
15533           // problem now.
15534           if (CXXRecord->getNumVBases()) {
15535             CXXFinalOverriderMap FinalOverriders;
15536             CXXRecord->getFinalOverriders(FinalOverriders);
15537 
15538             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15539                                              MEnd = FinalOverriders.end();
15540                  M != MEnd; ++M) {
15541               for (OverridingMethods::iterator SO = M->second.begin(),
15542                                             SOEnd = M->second.end();
15543                    SO != SOEnd; ++SO) {
15544                 assert(SO->second.size() > 0 &&
15545                        "Virtual function without overriding functions?");
15546                 if (SO->second.size() == 1)
15547                   continue;
15548 
15549                 // C++ [class.virtual]p2:
15550                 //   In a derived class, if a virtual member function of a base
15551                 //   class subobject has more than one final overrider the
15552                 //   program is ill-formed.
15553                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15554                   << (const NamedDecl *)M->first << Record;
15555                 Diag(M->first->getLocation(),
15556                      diag::note_overridden_virtual_function);
15557                 for (OverridingMethods::overriding_iterator
15558                           OM = SO->second.begin(),
15559                        OMEnd = SO->second.end();
15560                      OM != OMEnd; ++OM)
15561                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15562                     << (const NamedDecl *)M->first << OM->Method->getParent();
15563 
15564                 Record->setInvalidDecl();
15565               }
15566             }
15567             CXXRecord->completeDefinition(&FinalOverriders);
15568             Completed = true;
15569           }
15570         }
15571       }
15572     }
15573 
15574     if (!Completed)
15575       Record->completeDefinition();
15576 
15577     // We may have deferred checking for a deleted destructor. Check now.
15578     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15579       auto *Dtor = CXXRecord->getDestructor();
15580       if (Dtor && Dtor->isImplicit() &&
15581           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15582         CXXRecord->setImplicitDestructorIsDeleted();
15583         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15584       }
15585     }
15586 
15587     if (Record->hasAttrs()) {
15588       CheckAlignasUnderalignment(Record);
15589 
15590       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15591         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15592                                            IA->getRange(), IA->getBestCase(),
15593                                            IA->getSemanticSpelling());
15594     }
15595 
15596     // Check if the structure/union declaration is a type that can have zero
15597     // size in C. For C this is a language extension, for C++ it may cause
15598     // compatibility problems.
15599     bool CheckForZeroSize;
15600     if (!getLangOpts().CPlusPlus) {
15601       CheckForZeroSize = true;
15602     } else {
15603       // For C++ filter out types that cannot be referenced in C code.
15604       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15605       CheckForZeroSize =
15606           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15607           !CXXRecord->isDependentType() &&
15608           CXXRecord->isCLike();
15609     }
15610     if (CheckForZeroSize) {
15611       bool ZeroSize = true;
15612       bool IsEmpty = true;
15613       unsigned NonBitFields = 0;
15614       for (RecordDecl::field_iterator I = Record->field_begin(),
15615                                       E = Record->field_end();
15616            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15617         IsEmpty = false;
15618         if (I->isUnnamedBitfield()) {
15619           if (!I->isZeroLengthBitField(Context))
15620             ZeroSize = false;
15621         } else {
15622           ++NonBitFields;
15623           QualType FieldType = I->getType();
15624           if (FieldType->isIncompleteType() ||
15625               !Context.getTypeSizeInChars(FieldType).isZero())
15626             ZeroSize = false;
15627         }
15628       }
15629 
15630       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15631       // allowed in C++, but warn if its declaration is inside
15632       // extern "C" block.
15633       if (ZeroSize) {
15634         Diag(RecLoc, getLangOpts().CPlusPlus ?
15635                          diag::warn_zero_size_struct_union_in_extern_c :
15636                          diag::warn_zero_size_struct_union_compat)
15637           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15638       }
15639 
15640       // Structs without named members are extension in C (C99 6.7.2.1p7),
15641       // but are accepted by GCC.
15642       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15643         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15644                                diag::ext_no_named_members_in_struct_union)
15645           << Record->isUnion();
15646       }
15647     }
15648   } else {
15649     ObjCIvarDecl **ClsFields =
15650       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15651     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15652       ID->setEndOfDefinitionLoc(RBrac);
15653       // Add ivar's to class's DeclContext.
15654       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15655         ClsFields[i]->setLexicalDeclContext(ID);
15656         ID->addDecl(ClsFields[i]);
15657       }
15658       // Must enforce the rule that ivars in the base classes may not be
15659       // duplicates.
15660       if (ID->getSuperClass())
15661         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15662     } else if (ObjCImplementationDecl *IMPDecl =
15663                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15664       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15665       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15666         // Ivar declared in @implementation never belongs to the implementation.
15667         // Only it is in implementation's lexical context.
15668         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15669       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15670       IMPDecl->setIvarLBraceLoc(LBrac);
15671       IMPDecl->setIvarRBraceLoc(RBrac);
15672     } else if (ObjCCategoryDecl *CDecl =
15673                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15674       // case of ivars in class extension; all other cases have been
15675       // reported as errors elsewhere.
15676       // FIXME. Class extension does not have a LocEnd field.
15677       // CDecl->setLocEnd(RBrac);
15678       // Add ivar's to class extension's DeclContext.
15679       // Diagnose redeclaration of private ivars.
15680       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15681       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15682         if (IDecl) {
15683           if (const ObjCIvarDecl *ClsIvar =
15684               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15685             Diag(ClsFields[i]->getLocation(),
15686                  diag::err_duplicate_ivar_declaration);
15687             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15688             continue;
15689           }
15690           for (const auto *Ext : IDecl->known_extensions()) {
15691             if (const ObjCIvarDecl *ClsExtIvar
15692                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15693               Diag(ClsFields[i]->getLocation(),
15694                    diag::err_duplicate_ivar_declaration);
15695               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15696               continue;
15697             }
15698           }
15699         }
15700         ClsFields[i]->setLexicalDeclContext(CDecl);
15701         CDecl->addDecl(ClsFields[i]);
15702       }
15703       CDecl->setIvarLBraceLoc(LBrac);
15704       CDecl->setIvarRBraceLoc(RBrac);
15705     }
15706   }
15707 
15708   if (Attr)
15709     ProcessDeclAttributeList(S, Record, Attr);
15710 }
15711 
15712 /// \brief Determine whether the given integral value is representable within
15713 /// the given type T.
15714 static bool isRepresentableIntegerValue(ASTContext &Context,
15715                                         llvm::APSInt &Value,
15716                                         QualType T) {
15717   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
15718          "Integral type required!");
15719   unsigned BitWidth = Context.getIntWidth(T);
15720 
15721   if (Value.isUnsigned() || Value.isNonNegative()) {
15722     if (T->isSignedIntegerOrEnumerationType())
15723       --BitWidth;
15724     return Value.getActiveBits() <= BitWidth;
15725   }
15726   return Value.getMinSignedBits() <= BitWidth;
15727 }
15728 
15729 // \brief Given an integral type, return the next larger integral type
15730 // (or a NULL type of no such type exists).
15731 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15732   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15733   // enum checking below.
15734   assert((T->isIntegralType(Context) ||
15735          T->isEnumeralType()) && "Integral type required!");
15736   const unsigned NumTypes = 4;
15737   QualType SignedIntegralTypes[NumTypes] = {
15738     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15739   };
15740   QualType UnsignedIntegralTypes[NumTypes] = {
15741     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15742     Context.UnsignedLongLongTy
15743   };
15744 
15745   unsigned BitWidth = Context.getTypeSize(T);
15746   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15747                                                         : UnsignedIntegralTypes;
15748   for (unsigned I = 0; I != NumTypes; ++I)
15749     if (Context.getTypeSize(Types[I]) > BitWidth)
15750       return Types[I];
15751 
15752   return QualType();
15753 }
15754 
15755 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15756                                           EnumConstantDecl *LastEnumConst,
15757                                           SourceLocation IdLoc,
15758                                           IdentifierInfo *Id,
15759                                           Expr *Val) {
15760   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15761   llvm::APSInt EnumVal(IntWidth);
15762   QualType EltTy;
15763 
15764   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15765     Val = nullptr;
15766 
15767   if (Val)
15768     Val = DefaultLvalueConversion(Val).get();
15769 
15770   if (Val) {
15771     if (Enum->isDependentType() || Val->isTypeDependent())
15772       EltTy = Context.DependentTy;
15773     else {
15774       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15775           !getLangOpts().MSVCCompat) {
15776         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15777         // constant-expression in the enumerator-definition shall be a converted
15778         // constant expression of the underlying type.
15779         EltTy = Enum->getIntegerType();
15780         ExprResult Converted =
15781           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15782                                            CCEK_Enumerator);
15783         if (Converted.isInvalid())
15784           Val = nullptr;
15785         else
15786           Val = Converted.get();
15787       } else if (!Val->isValueDependent() &&
15788                  !(Val = VerifyIntegerConstantExpression(Val,
15789                                                          &EnumVal).get())) {
15790         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15791       } else {
15792         if (Enum->isComplete()) {
15793           EltTy = Enum->getIntegerType();
15794 
15795           // In Obj-C and Microsoft mode, require the enumeration value to be
15796           // representable in the underlying type of the enumeration. In C++11,
15797           // we perform a non-narrowing conversion as part of converted constant
15798           // expression checking.
15799           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15800             if (getLangOpts().MSVCCompat) {
15801               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15802               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15803             } else
15804               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15805           } else
15806             Val = ImpCastExprToType(Val, EltTy,
15807                                     EltTy->isBooleanType() ?
15808                                     CK_IntegralToBoolean : CK_IntegralCast)
15809                     .get();
15810         } else if (getLangOpts().CPlusPlus) {
15811           // C++11 [dcl.enum]p5:
15812           //   If the underlying type is not fixed, the type of each enumerator
15813           //   is the type of its initializing value:
15814           //     - If an initializer is specified for an enumerator, the
15815           //       initializing value has the same type as the expression.
15816           EltTy = Val->getType();
15817         } else {
15818           // C99 6.7.2.2p2:
15819           //   The expression that defines the value of an enumeration constant
15820           //   shall be an integer constant expression that has a value
15821           //   representable as an int.
15822 
15823           // Complain if the value is not representable in an int.
15824           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15825             Diag(IdLoc, diag::ext_enum_value_not_int)
15826               << EnumVal.toString(10) << Val->getSourceRange()
15827               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15828           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15829             // Force the type of the expression to 'int'.
15830             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15831           }
15832           EltTy = Val->getType();
15833         }
15834       }
15835     }
15836   }
15837 
15838   if (!Val) {
15839     if (Enum->isDependentType())
15840       EltTy = Context.DependentTy;
15841     else if (!LastEnumConst) {
15842       // C++0x [dcl.enum]p5:
15843       //   If the underlying type is not fixed, the type of each enumerator
15844       //   is the type of its initializing value:
15845       //     - If no initializer is specified for the first enumerator, the
15846       //       initializing value has an unspecified integral type.
15847       //
15848       // GCC uses 'int' for its unspecified integral type, as does
15849       // C99 6.7.2.2p3.
15850       if (Enum->isFixed()) {
15851         EltTy = Enum->getIntegerType();
15852       }
15853       else {
15854         EltTy = Context.IntTy;
15855       }
15856     } else {
15857       // Assign the last value + 1.
15858       EnumVal = LastEnumConst->getInitVal();
15859       ++EnumVal;
15860       EltTy = LastEnumConst->getType();
15861 
15862       // Check for overflow on increment.
15863       if (EnumVal < LastEnumConst->getInitVal()) {
15864         // C++0x [dcl.enum]p5:
15865         //   If the underlying type is not fixed, the type of each enumerator
15866         //   is the type of its initializing value:
15867         //
15868         //     - Otherwise the type of the initializing value is the same as
15869         //       the type of the initializing value of the preceding enumerator
15870         //       unless the incremented value is not representable in that type,
15871         //       in which case the type is an unspecified integral type
15872         //       sufficient to contain the incremented value. If no such type
15873         //       exists, the program is ill-formed.
15874         QualType T = getNextLargerIntegralType(Context, EltTy);
15875         if (T.isNull() || Enum->isFixed()) {
15876           // There is no integral type larger enough to represent this
15877           // value. Complain, then allow the value to wrap around.
15878           EnumVal = LastEnumConst->getInitVal();
15879           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15880           ++EnumVal;
15881           if (Enum->isFixed())
15882             // When the underlying type is fixed, this is ill-formed.
15883             Diag(IdLoc, diag::err_enumerator_wrapped)
15884               << EnumVal.toString(10)
15885               << EltTy;
15886           else
15887             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15888               << EnumVal.toString(10);
15889         } else {
15890           EltTy = T;
15891         }
15892 
15893         // Retrieve the last enumerator's value, extent that type to the
15894         // type that is supposed to be large enough to represent the incremented
15895         // value, then increment.
15896         EnumVal = LastEnumConst->getInitVal();
15897         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15898         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15899         ++EnumVal;
15900 
15901         // If we're not in C++, diagnose the overflow of enumerator values,
15902         // which in C99 means that the enumerator value is not representable in
15903         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15904         // permits enumerator values that are representable in some larger
15905         // integral type.
15906         if (!getLangOpts().CPlusPlus && !T.isNull())
15907           Diag(IdLoc, diag::warn_enum_value_overflow);
15908       } else if (!getLangOpts().CPlusPlus &&
15909                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15910         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15911         Diag(IdLoc, diag::ext_enum_value_not_int)
15912           << EnumVal.toString(10) << 1;
15913       }
15914     }
15915   }
15916 
15917   if (!EltTy->isDependentType()) {
15918     // Make the enumerator value match the signedness and size of the
15919     // enumerator's type.
15920     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15921     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15922   }
15923 
15924   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15925                                   Val, EnumVal);
15926 }
15927 
15928 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15929                                                 SourceLocation IILoc) {
15930   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15931       !getLangOpts().CPlusPlus)
15932     return SkipBodyInfo();
15933 
15934   // We have an anonymous enum definition. Look up the first enumerator to
15935   // determine if we should merge the definition with an existing one and
15936   // skip the body.
15937   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15938                                          forRedeclarationInCurContext());
15939   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15940   if (!PrevECD)
15941     return SkipBodyInfo();
15942 
15943   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15944   NamedDecl *Hidden;
15945   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15946     SkipBodyInfo Skip;
15947     Skip.Previous = Hidden;
15948     return Skip;
15949   }
15950 
15951   return SkipBodyInfo();
15952 }
15953 
15954 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15955                               SourceLocation IdLoc, IdentifierInfo *Id,
15956                               AttributeList *Attr,
15957                               SourceLocation EqualLoc, Expr *Val) {
15958   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15959   EnumConstantDecl *LastEnumConst =
15960     cast_or_null<EnumConstantDecl>(lastEnumConst);
15961 
15962   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15963   // we find one that is.
15964   S = getNonFieldDeclScope(S);
15965 
15966   // Verify that there isn't already something declared with this name in this
15967   // scope.
15968   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15969                                          ForVisibleRedeclaration);
15970   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15971     // Maybe we will complain about the shadowed template parameter.
15972     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15973     // Just pretend that we didn't see the previous declaration.
15974     PrevDecl = nullptr;
15975   }
15976 
15977   // C++ [class.mem]p15:
15978   // If T is the name of a class, then each of the following shall have a name
15979   // different from T:
15980   // - every enumerator of every member of class T that is an unscoped
15981   // enumerated type
15982   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15983     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15984                             DeclarationNameInfo(Id, IdLoc));
15985 
15986   EnumConstantDecl *New =
15987     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15988   if (!New)
15989     return nullptr;
15990 
15991   if (PrevDecl) {
15992     // When in C++, we may get a TagDecl with the same name; in this case the
15993     // enum constant will 'hide' the tag.
15994     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15995            "Received TagDecl when not in C++!");
15996     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15997       if (isa<EnumConstantDecl>(PrevDecl))
15998         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15999       else
16000         Diag(IdLoc, diag::err_redefinition) << Id;
16001       notePreviousDefinition(PrevDecl, IdLoc);
16002       return nullptr;
16003     }
16004   }
16005 
16006   // Process attributes.
16007   if (Attr) ProcessDeclAttributeList(S, New, Attr);
16008   AddPragmaAttributes(S, New);
16009 
16010   // Register this decl in the current scope stack.
16011   New->setAccess(TheEnumDecl->getAccess());
16012   PushOnScopeChains(New, S);
16013 
16014   ActOnDocumentableDecl(New);
16015 
16016   return New;
16017 }
16018 
16019 // Returns true when the enum initial expression does not trigger the
16020 // duplicate enum warning.  A few common cases are exempted as follows:
16021 // Element2 = Element1
16022 // Element2 = Element1 + 1
16023 // Element2 = Element1 - 1
16024 // Where Element2 and Element1 are from the same enum.
16025 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16026   Expr *InitExpr = ECD->getInitExpr();
16027   if (!InitExpr)
16028     return true;
16029   InitExpr = InitExpr->IgnoreImpCasts();
16030 
16031   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16032     if (!BO->isAdditiveOp())
16033       return true;
16034     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16035     if (!IL)
16036       return true;
16037     if (IL->getValue() != 1)
16038       return true;
16039 
16040     InitExpr = BO->getLHS();
16041   }
16042 
16043   // This checks if the elements are from the same enum.
16044   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16045   if (!DRE)
16046     return true;
16047 
16048   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16049   if (!EnumConstant)
16050     return true;
16051 
16052   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16053       Enum)
16054     return true;
16055 
16056   return false;
16057 }
16058 
16059 // Emits a warning when an element is implicitly set a value that
16060 // a previous element has already been set to.
16061 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16062                                         EnumDecl *Enum, QualType EnumType) {
16063   // Avoid anonymous enums
16064   if (!Enum->getIdentifier())
16065     return;
16066 
16067   // Only check for small enums.
16068   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16069     return;
16070 
16071   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16072     return;
16073 
16074   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16075   typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16076 
16077   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16078   typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
16079 
16080   // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16081   auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16082     llvm::APSInt Val = D->getInitVal();
16083     return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16084   };
16085 
16086   DuplicatesVector DupVector;
16087   ValueToVectorMap EnumMap;
16088 
16089   // Populate the EnumMap with all values represented by enum constants without
16090   // an initializer.
16091   for (auto *Element : Elements) {
16092     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16093 
16094     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16095     // this constant.  Skip this enum since it may be ill-formed.
16096     if (!ECD) {
16097       return;
16098     }
16099 
16100     // Constants with initalizers are handled in the next loop.
16101     if (ECD->getInitExpr())
16102       continue;
16103 
16104     // Duplicate values are handled in the next loop.
16105     EnumMap.insert({EnumConstantToKey(ECD), ECD});
16106   }
16107 
16108   if (EnumMap.size() == 0)
16109     return;
16110 
16111   // Create vectors for any values that has duplicates.
16112   for (auto *Element : Elements) {
16113     // The last loop returned if any constant was null.
16114     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16115     if (!ValidDuplicateEnum(ECD, Enum))
16116       continue;
16117 
16118     auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16119     if (Iter == EnumMap.end())
16120       continue;
16121 
16122     DeclOrVector& Entry = Iter->second;
16123     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16124       // Ensure constants are different.
16125       if (D == ECD)
16126         continue;
16127 
16128       // Create new vector and push values onto it.
16129       auto Vec = llvm::make_unique<ECDVector>();
16130       Vec->push_back(D);
16131       Vec->push_back(ECD);
16132 
16133       // Update entry to point to the duplicates vector.
16134       Entry = Vec.get();
16135 
16136       // Store the vector somewhere we can consult later for quick emission of
16137       // diagnostics.
16138       DupVector.emplace_back(std::move(Vec));
16139       continue;
16140     }
16141 
16142     ECDVector *Vec = Entry.get<ECDVector*>();
16143     // Make sure constants are not added more than once.
16144     if (*Vec->begin() == ECD)
16145       continue;
16146 
16147     Vec->push_back(ECD);
16148   }
16149 
16150   // Emit diagnostics.
16151   for (const auto &Vec : DupVector) {
16152     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16153 
16154     // Emit warning for one enum constant.
16155     auto *FirstECD = Vec->front();
16156     S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16157       << FirstECD << FirstECD->getInitVal().toString(10)
16158       << FirstECD->getSourceRange();
16159 
16160     // Emit one note for each of the remaining enum constants with
16161     // the same value.
16162     for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16163       S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16164         << ECD << ECD->getInitVal().toString(10)
16165         << ECD->getSourceRange();
16166   }
16167 }
16168 
16169 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16170                              bool AllowMask) const {
16171   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16172   assert(ED->isCompleteDefinition() && "expected enum definition");
16173 
16174   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16175   llvm::APInt &FlagBits = R.first->second;
16176 
16177   if (R.second) {
16178     for (auto *E : ED->enumerators()) {
16179       const auto &EVal = E->getInitVal();
16180       // Only single-bit enumerators introduce new flag values.
16181       if (EVal.isPowerOf2())
16182         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16183     }
16184   }
16185 
16186   // A value is in a flag enum if either its bits are a subset of the enum's
16187   // flag bits (the first condition) or we are allowing masks and the same is
16188   // true of its complement (the second condition). When masks are allowed, we
16189   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16190   //
16191   // While it's true that any value could be used as a mask, the assumption is
16192   // that a mask will have all of the insignificant bits set. Anything else is
16193   // likely a logic error.
16194   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16195   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16196 }
16197 
16198 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16199                          Decl *EnumDeclX,
16200                          ArrayRef<Decl *> Elements,
16201                          Scope *S, AttributeList *Attr) {
16202   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16203   QualType EnumType = Context.getTypeDeclType(Enum);
16204 
16205   if (Attr)
16206     ProcessDeclAttributeList(S, Enum, Attr);
16207 
16208   if (Enum->isDependentType()) {
16209     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16210       EnumConstantDecl *ECD =
16211         cast_or_null<EnumConstantDecl>(Elements[i]);
16212       if (!ECD) continue;
16213 
16214       ECD->setType(EnumType);
16215     }
16216 
16217     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16218     return;
16219   }
16220 
16221   // TODO: If the result value doesn't fit in an int, it must be a long or long
16222   // long value.  ISO C does not support this, but GCC does as an extension,
16223   // emit a warning.
16224   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16225   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16226   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16227 
16228   // Verify that all the values are okay, compute the size of the values, and
16229   // reverse the list.
16230   unsigned NumNegativeBits = 0;
16231   unsigned NumPositiveBits = 0;
16232 
16233   // Keep track of whether all elements have type int.
16234   bool AllElementsInt = true;
16235 
16236   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16237     EnumConstantDecl *ECD =
16238       cast_or_null<EnumConstantDecl>(Elements[i]);
16239     if (!ECD) continue;  // Already issued a diagnostic.
16240 
16241     const llvm::APSInt &InitVal = ECD->getInitVal();
16242 
16243     // Keep track of the size of positive and negative values.
16244     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16245       NumPositiveBits = std::max(NumPositiveBits,
16246                                  (unsigned)InitVal.getActiveBits());
16247     else
16248       NumNegativeBits = std::max(NumNegativeBits,
16249                                  (unsigned)InitVal.getMinSignedBits());
16250 
16251     // Keep track of whether every enum element has type int (very commmon).
16252     if (AllElementsInt)
16253       AllElementsInt = ECD->getType() == Context.IntTy;
16254   }
16255 
16256   // Figure out the type that should be used for this enum.
16257   QualType BestType;
16258   unsigned BestWidth;
16259 
16260   // C++0x N3000 [conv.prom]p3:
16261   //   An rvalue of an unscoped enumeration type whose underlying
16262   //   type is not fixed can be converted to an rvalue of the first
16263   //   of the following types that can represent all the values of
16264   //   the enumeration: int, unsigned int, long int, unsigned long
16265   //   int, long long int, or unsigned long long int.
16266   // C99 6.4.4.3p2:
16267   //   An identifier declared as an enumeration constant has type int.
16268   // The C99 rule is modified by a gcc extension
16269   QualType BestPromotionType;
16270 
16271   bool Packed = Enum->hasAttr<PackedAttr>();
16272   // -fshort-enums is the equivalent to specifying the packed attribute on all
16273   // enum definitions.
16274   if (LangOpts.ShortEnums)
16275     Packed = true;
16276 
16277   // If the enum already has a type because it is fixed or dictated by the
16278   // target, promote that type instead of analyzing the enumerators.
16279   if (Enum->isComplete()) {
16280     BestType = Enum->getIntegerType();
16281     if (BestType->isPromotableIntegerType())
16282       BestPromotionType = Context.getPromotedIntegerType(BestType);
16283     else
16284       BestPromotionType = BestType;
16285 
16286     BestWidth = Context.getIntWidth(BestType);
16287   }
16288   else if (NumNegativeBits) {
16289     // If there is a negative value, figure out the smallest integer type (of
16290     // int/long/longlong) that fits.
16291     // If it's packed, check also if it fits a char or a short.
16292     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16293       BestType = Context.SignedCharTy;
16294       BestWidth = CharWidth;
16295     } else if (Packed && NumNegativeBits <= ShortWidth &&
16296                NumPositiveBits < ShortWidth) {
16297       BestType = Context.ShortTy;
16298       BestWidth = ShortWidth;
16299     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16300       BestType = Context.IntTy;
16301       BestWidth = IntWidth;
16302     } else {
16303       BestWidth = Context.getTargetInfo().getLongWidth();
16304 
16305       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16306         BestType = Context.LongTy;
16307       } else {
16308         BestWidth = Context.getTargetInfo().getLongLongWidth();
16309 
16310         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16311           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16312         BestType = Context.LongLongTy;
16313       }
16314     }
16315     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16316   } else {
16317     // If there is no negative value, figure out the smallest type that fits
16318     // all of the enumerator values.
16319     // If it's packed, check also if it fits a char or a short.
16320     if (Packed && NumPositiveBits <= CharWidth) {
16321       BestType = Context.UnsignedCharTy;
16322       BestPromotionType = Context.IntTy;
16323       BestWidth = CharWidth;
16324     } else if (Packed && NumPositiveBits <= ShortWidth) {
16325       BestType = Context.UnsignedShortTy;
16326       BestPromotionType = Context.IntTy;
16327       BestWidth = ShortWidth;
16328     } else if (NumPositiveBits <= IntWidth) {
16329       BestType = Context.UnsignedIntTy;
16330       BestWidth = IntWidth;
16331       BestPromotionType
16332         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16333                            ? Context.UnsignedIntTy : Context.IntTy;
16334     } else if (NumPositiveBits <=
16335                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16336       BestType = Context.UnsignedLongTy;
16337       BestPromotionType
16338         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16339                            ? Context.UnsignedLongTy : Context.LongTy;
16340     } else {
16341       BestWidth = Context.getTargetInfo().getLongLongWidth();
16342       assert(NumPositiveBits <= BestWidth &&
16343              "How could an initializer get larger than ULL?");
16344       BestType = Context.UnsignedLongLongTy;
16345       BestPromotionType
16346         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16347                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16348     }
16349   }
16350 
16351   // Loop over all of the enumerator constants, changing their types to match
16352   // the type of the enum if needed.
16353   for (auto *D : Elements) {
16354     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16355     if (!ECD) continue;  // Already issued a diagnostic.
16356 
16357     // Standard C says the enumerators have int type, but we allow, as an
16358     // extension, the enumerators to be larger than int size.  If each
16359     // enumerator value fits in an int, type it as an int, otherwise type it the
16360     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16361     // that X has type 'int', not 'unsigned'.
16362 
16363     // Determine whether the value fits into an int.
16364     llvm::APSInt InitVal = ECD->getInitVal();
16365 
16366     // If it fits into an integer type, force it.  Otherwise force it to match
16367     // the enum decl type.
16368     QualType NewTy;
16369     unsigned NewWidth;
16370     bool NewSign;
16371     if (!getLangOpts().CPlusPlus &&
16372         !Enum->isFixed() &&
16373         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16374       NewTy = Context.IntTy;
16375       NewWidth = IntWidth;
16376       NewSign = true;
16377     } else if (ECD->getType() == BestType) {
16378       // Already the right type!
16379       if (getLangOpts().CPlusPlus)
16380         // C++ [dcl.enum]p4: Following the closing brace of an
16381         // enum-specifier, each enumerator has the type of its
16382         // enumeration.
16383         ECD->setType(EnumType);
16384       continue;
16385     } else {
16386       NewTy = BestType;
16387       NewWidth = BestWidth;
16388       NewSign = BestType->isSignedIntegerOrEnumerationType();
16389     }
16390 
16391     // Adjust the APSInt value.
16392     InitVal = InitVal.extOrTrunc(NewWidth);
16393     InitVal.setIsSigned(NewSign);
16394     ECD->setInitVal(InitVal);
16395 
16396     // Adjust the Expr initializer and type.
16397     if (ECD->getInitExpr() &&
16398         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16399       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16400                                                 CK_IntegralCast,
16401                                                 ECD->getInitExpr(),
16402                                                 /*base paths*/ nullptr,
16403                                                 VK_RValue));
16404     if (getLangOpts().CPlusPlus)
16405       // C++ [dcl.enum]p4: Following the closing brace of an
16406       // enum-specifier, each enumerator has the type of its
16407       // enumeration.
16408       ECD->setType(EnumType);
16409     else
16410       ECD->setType(NewTy);
16411   }
16412 
16413   Enum->completeDefinition(BestType, BestPromotionType,
16414                            NumPositiveBits, NumNegativeBits);
16415 
16416   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16417 
16418   if (Enum->isClosedFlag()) {
16419     for (Decl *D : Elements) {
16420       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16421       if (!ECD) continue;  // Already issued a diagnostic.
16422 
16423       llvm::APSInt InitVal = ECD->getInitVal();
16424       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16425           !IsValueInFlagEnum(Enum, InitVal, true))
16426         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16427           << ECD << Enum;
16428     }
16429   }
16430 
16431   // Now that the enum type is defined, ensure it's not been underaligned.
16432   if (Enum->hasAttrs())
16433     CheckAlignasUnderalignment(Enum);
16434 }
16435 
16436 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16437                                   SourceLocation StartLoc,
16438                                   SourceLocation EndLoc) {
16439   StringLiteral *AsmString = cast<StringLiteral>(expr);
16440 
16441   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16442                                                    AsmString, StartLoc,
16443                                                    EndLoc);
16444   CurContext->addDecl(New);
16445   return New;
16446 }
16447 
16448 static void checkModuleImportContext(Sema &S, Module *M,
16449                                      SourceLocation ImportLoc, DeclContext *DC,
16450                                      bool FromInclude = false) {
16451   SourceLocation ExternCLoc;
16452 
16453   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16454     switch (LSD->getLanguage()) {
16455     case LinkageSpecDecl::lang_c:
16456       if (ExternCLoc.isInvalid())
16457         ExternCLoc = LSD->getLocStart();
16458       break;
16459     case LinkageSpecDecl::lang_cxx:
16460       break;
16461     }
16462     DC = LSD->getParent();
16463   }
16464 
16465   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16466     DC = DC->getParent();
16467 
16468   if (!isa<TranslationUnitDecl>(DC)) {
16469     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16470                           ? diag::ext_module_import_not_at_top_level_noop
16471                           : diag::err_module_import_not_at_top_level_fatal)
16472         << M->getFullModuleName() << DC;
16473     S.Diag(cast<Decl>(DC)->getLocStart(),
16474            diag::note_module_import_not_at_top_level) << DC;
16475   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16476     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16477       << M->getFullModuleName();
16478     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16479   }
16480 }
16481 
16482 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16483                                            SourceLocation ModuleLoc,
16484                                            ModuleDeclKind MDK,
16485                                            ModuleIdPath Path) {
16486   assert(getLangOpts().ModulesTS &&
16487          "should only have module decl in modules TS");
16488 
16489   // A module implementation unit requires that we are not compiling a module
16490   // of any kind. A module interface unit requires that we are not compiling a
16491   // module map.
16492   switch (getLangOpts().getCompilingModule()) {
16493   case LangOptions::CMK_None:
16494     // It's OK to compile a module interface as a normal translation unit.
16495     break;
16496 
16497   case LangOptions::CMK_ModuleInterface:
16498     if (MDK != ModuleDeclKind::Implementation)
16499       break;
16500 
16501     // We were asked to compile a module interface unit but this is a module
16502     // implementation unit. That indicates the 'export' is missing.
16503     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16504       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16505     MDK = ModuleDeclKind::Interface;
16506     break;
16507 
16508   case LangOptions::CMK_ModuleMap:
16509     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16510     return nullptr;
16511   }
16512 
16513   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16514 
16515   // FIXME: Most of this work should be done by the preprocessor rather than
16516   // here, in order to support macro import.
16517 
16518   // Only one module-declaration is permitted per source file.
16519   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16520     Diag(ModuleLoc, diag::err_module_redeclaration);
16521     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16522          diag::note_prev_module_declaration);
16523     return nullptr;
16524   }
16525 
16526   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16527   // modules, the dots here are just another character that can appear in a
16528   // module name.
16529   std::string ModuleName;
16530   for (auto &Piece : Path) {
16531     if (!ModuleName.empty())
16532       ModuleName += ".";
16533     ModuleName += Piece.first->getName();
16534   }
16535 
16536   // If a module name was explicitly specified on the command line, it must be
16537   // correct.
16538   if (!getLangOpts().CurrentModule.empty() &&
16539       getLangOpts().CurrentModule != ModuleName) {
16540     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16541         << SourceRange(Path.front().second, Path.back().second)
16542         << getLangOpts().CurrentModule;
16543     return nullptr;
16544   }
16545   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16546 
16547   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16548   Module *Mod;
16549 
16550   switch (MDK) {
16551   case ModuleDeclKind::Interface: {
16552     // We can't have parsed or imported a definition of this module or parsed a
16553     // module map defining it already.
16554     if (auto *M = Map.findModule(ModuleName)) {
16555       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16556       if (M->DefinitionLoc.isValid())
16557         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16558       else if (const auto *FE = M->getASTFile())
16559         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16560             << FE->getName();
16561       Mod = M;
16562       break;
16563     }
16564 
16565     // Create a Module for the module that we're defining.
16566     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16567                                            ModuleScopes.front().Module);
16568     assert(Mod && "module creation should not fail");
16569     break;
16570   }
16571 
16572   case ModuleDeclKind::Partition:
16573     // FIXME: Check we are in a submodule of the named module.
16574     return nullptr;
16575 
16576   case ModuleDeclKind::Implementation:
16577     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16578         PP.getIdentifierInfo(ModuleName), Path[0].second);
16579     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16580                                        /*IsIncludeDirective=*/false);
16581     if (!Mod) {
16582       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16583       // Create an empty module interface unit for error recovery.
16584       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16585                                              ModuleScopes.front().Module);
16586     }
16587     break;
16588   }
16589 
16590   // Switch from the global module to the named module.
16591   ModuleScopes.back().Module = Mod;
16592   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16593   VisibleModules.setVisible(Mod, ModuleLoc);
16594 
16595   // From now on, we have an owning module for all declarations we see.
16596   // However, those declarations are module-private unless explicitly
16597   // exported.
16598   auto *TU = Context.getTranslationUnitDecl();
16599   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16600   TU->setLocalOwningModule(Mod);
16601 
16602   // FIXME: Create a ModuleDecl.
16603   return nullptr;
16604 }
16605 
16606 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16607                                    SourceLocation ImportLoc,
16608                                    ModuleIdPath Path) {
16609   Module *Mod =
16610       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16611                                    /*IsIncludeDirective=*/false);
16612   if (!Mod)
16613     return true;
16614 
16615   VisibleModules.setVisible(Mod, ImportLoc);
16616 
16617   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16618 
16619   // FIXME: we should support importing a submodule within a different submodule
16620   // of the same top-level module. Until we do, make it an error rather than
16621   // silently ignoring the import.
16622   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16623   // warn on a redundant import of the current module?
16624   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16625       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16626     Diag(ImportLoc, getLangOpts().isCompilingModule()
16627                         ? diag::err_module_self_import
16628                         : diag::err_module_import_in_implementation)
16629         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16630 
16631   SmallVector<SourceLocation, 2> IdentifierLocs;
16632   Module *ModCheck = Mod;
16633   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16634     // If we've run out of module parents, just drop the remaining identifiers.
16635     // We need the length to be consistent.
16636     if (!ModCheck)
16637       break;
16638     ModCheck = ModCheck->Parent;
16639 
16640     IdentifierLocs.push_back(Path[I].second);
16641   }
16642 
16643   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16644                                           Mod, IdentifierLocs);
16645   if (!ModuleScopes.empty())
16646     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16647   CurContext->addDecl(Import);
16648 
16649   // Re-export the module if needed.
16650   if (Import->isExported() &&
16651       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16652     getCurrentModule()->Exports.emplace_back(Mod, false);
16653 
16654   return Import;
16655 }
16656 
16657 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16658   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16659   BuildModuleInclude(DirectiveLoc, Mod);
16660 }
16661 
16662 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16663   // Determine whether we're in the #include buffer for a module. The #includes
16664   // in that buffer do not qualify as module imports; they're just an
16665   // implementation detail of us building the module.
16666   //
16667   // FIXME: Should we even get ActOnModuleInclude calls for those?
16668   bool IsInModuleIncludes =
16669       TUKind == TU_Module &&
16670       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16671 
16672   bool ShouldAddImport = !IsInModuleIncludes;
16673 
16674   // If this module import was due to an inclusion directive, create an
16675   // implicit import declaration to capture it in the AST.
16676   if (ShouldAddImport) {
16677     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16678     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16679                                                      DirectiveLoc, Mod,
16680                                                      DirectiveLoc);
16681     if (!ModuleScopes.empty())
16682       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16683     TU->addDecl(ImportD);
16684     Consumer.HandleImplicitImportDecl(ImportD);
16685   }
16686 
16687   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16688   VisibleModules.setVisible(Mod, DirectiveLoc);
16689 }
16690 
16691 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16692   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16693 
16694   ModuleScopes.push_back({});
16695   ModuleScopes.back().Module = Mod;
16696   if (getLangOpts().ModulesLocalVisibility)
16697     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16698 
16699   VisibleModules.setVisible(Mod, DirectiveLoc);
16700 
16701   // The enclosing context is now part of this module.
16702   // FIXME: Consider creating a child DeclContext to hold the entities
16703   // lexically within the module.
16704   if (getLangOpts().trackLocalOwningModule()) {
16705     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16706       cast<Decl>(DC)->setModuleOwnershipKind(
16707           getLangOpts().ModulesLocalVisibility
16708               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16709               : Decl::ModuleOwnershipKind::Visible);
16710       cast<Decl>(DC)->setLocalOwningModule(Mod);
16711     }
16712   }
16713 }
16714 
16715 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16716   if (getLangOpts().ModulesLocalVisibility) {
16717     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16718     // Leaving a module hides namespace names, so our visible namespace cache
16719     // is now out of date.
16720     VisibleNamespaceCache.clear();
16721   }
16722 
16723   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16724          "left the wrong module scope");
16725   ModuleScopes.pop_back();
16726 
16727   // We got to the end of processing a local module. Create an
16728   // ImportDecl as we would for an imported module.
16729   FileID File = getSourceManager().getFileID(EomLoc);
16730   SourceLocation DirectiveLoc;
16731   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16732     // We reached the end of a #included module header. Use the #include loc.
16733     assert(File != getSourceManager().getMainFileID() &&
16734            "end of submodule in main source file");
16735     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16736   } else {
16737     // We reached an EOM pragma. Use the pragma location.
16738     DirectiveLoc = EomLoc;
16739   }
16740   BuildModuleInclude(DirectiveLoc, Mod);
16741 
16742   // Any further declarations are in whatever module we returned to.
16743   if (getLangOpts().trackLocalOwningModule()) {
16744     // The parser guarantees that this is the same context that we entered
16745     // the module within.
16746     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16747       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16748       if (!getCurrentModule())
16749         cast<Decl>(DC)->setModuleOwnershipKind(
16750             Decl::ModuleOwnershipKind::Unowned);
16751     }
16752   }
16753 }
16754 
16755 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16756                                                       Module *Mod) {
16757   // Bail if we're not allowed to implicitly import a module here.
16758   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16759       VisibleModules.isVisible(Mod))
16760     return;
16761 
16762   // Create the implicit import declaration.
16763   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16764   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16765                                                    Loc, Mod, Loc);
16766   TU->addDecl(ImportD);
16767   Consumer.HandleImplicitImportDecl(ImportD);
16768 
16769   // Make the module visible.
16770   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16771   VisibleModules.setVisible(Mod, Loc);
16772 }
16773 
16774 /// We have parsed the start of an export declaration, including the '{'
16775 /// (if present).
16776 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16777                                  SourceLocation LBraceLoc) {
16778   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16779 
16780   // C++ Modules TS draft:
16781   //   An export-declaration shall appear in the purview of a module other than
16782   //   the global module.
16783   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16784     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16785 
16786   //   An export-declaration [...] shall not contain more than one
16787   //   export keyword.
16788   //
16789   // The intent here is that an export-declaration cannot appear within another
16790   // export-declaration.
16791   if (D->isExported())
16792     Diag(ExportLoc, diag::err_export_within_export);
16793 
16794   CurContext->addDecl(D);
16795   PushDeclContext(S, D);
16796   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16797   return D;
16798 }
16799 
16800 /// Complete the definition of an export declaration.
16801 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16802   auto *ED = cast<ExportDecl>(D);
16803   if (RBraceLoc.isValid())
16804     ED->setRBraceLoc(RBraceLoc);
16805 
16806   // FIXME: Diagnose export of internal-linkage declaration (including
16807   // anonymous namespace).
16808 
16809   PopDeclContext();
16810   return D;
16811 }
16812 
16813 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16814                                       IdentifierInfo* AliasName,
16815                                       SourceLocation PragmaLoc,
16816                                       SourceLocation NameLoc,
16817                                       SourceLocation AliasNameLoc) {
16818   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16819                                          LookupOrdinaryName);
16820   AsmLabelAttr *Attr =
16821       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16822 
16823   // If a declaration that:
16824   // 1) declares a function or a variable
16825   // 2) has external linkage
16826   // already exists, add a label attribute to it.
16827   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16828     if (isDeclExternC(PrevDecl))
16829       PrevDecl->addAttr(Attr);
16830     else
16831       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16832           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16833   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16834   } else
16835     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16836 }
16837 
16838 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16839                              SourceLocation PragmaLoc,
16840                              SourceLocation NameLoc) {
16841   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16842 
16843   if (PrevDecl) {
16844     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16845   } else {
16846     (void)WeakUndeclaredIdentifiers.insert(
16847       std::pair<IdentifierInfo*,WeakInfo>
16848         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16849   }
16850 }
16851 
16852 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16853                                 IdentifierInfo* AliasName,
16854                                 SourceLocation PragmaLoc,
16855                                 SourceLocation NameLoc,
16856                                 SourceLocation AliasNameLoc) {
16857   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16858                                     LookupOrdinaryName);
16859   WeakInfo W = WeakInfo(Name, NameLoc);
16860 
16861   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16862     if (!PrevDecl->hasAttr<AliasAttr>())
16863       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16864         DeclApplyPragmaWeak(TUScope, ND, W);
16865   } else {
16866     (void)WeakUndeclaredIdentifiers.insert(
16867       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16868   }
16869 }
16870 
16871 Decl *Sema::getObjCDeclContext() const {
16872   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16873 }
16874