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   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1523     return Method->isCopyAssignmentOperator();
1524   return false;
1525 }
1526 
1527 // We need this to handle
1528 //
1529 // typedef struct {
1530 //   void *foo() { return 0; }
1531 // } A;
1532 //
1533 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1534 // for example. If 'A', foo will have external linkage. If we have '*A',
1535 // foo will have no linkage. Since we can't know until we get to the end
1536 // of the typedef, this function finds out if D might have non-external linkage.
1537 // Callers should verify at the end of the TU if it D has external linkage or
1538 // not.
1539 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1540   const DeclContext *DC = D->getDeclContext();
1541   while (!DC->isTranslationUnit()) {
1542     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1543       if (!RD->hasNameForLinkage())
1544         return true;
1545     }
1546     DC = DC->getParent();
1547   }
1548 
1549   return !D->isExternallyVisible();
1550 }
1551 
1552 // FIXME: This needs to be refactored; some other isInMainFile users want
1553 // these semantics.
1554 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1555   if (S.TUKind != TU_Complete)
1556     return false;
1557   return S.SourceMgr.isInMainFile(Loc);
1558 }
1559 
1560 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1561   assert(D);
1562 
1563   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1564     return false;
1565 
1566   // Ignore all entities declared within templates, and out-of-line definitions
1567   // of members of class templates.
1568   if (D->getDeclContext()->isDependentContext() ||
1569       D->getLexicalDeclContext()->isDependentContext())
1570     return false;
1571 
1572   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1573     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1574       return false;
1575     // A non-out-of-line declaration of a member specialization was implicitly
1576     // instantiated; it's the out-of-line declaration that we're interested in.
1577     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1578         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1579       return false;
1580 
1581     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1582       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1583         return false;
1584     } else {
1585       // 'static inline' functions are defined in headers; don't warn.
1586       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1587         return false;
1588     }
1589 
1590     if (FD->doesThisDeclarationHaveABody() &&
1591         Context.DeclMustBeEmitted(FD))
1592       return false;
1593   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594     // Constants and utility variables are defined in headers with internal
1595     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1596     // like "inline".)
1597     if (!isMainFileLoc(*this, VD->getLocation()))
1598       return false;
1599 
1600     if (Context.DeclMustBeEmitted(VD))
1601       return false;
1602 
1603     if (VD->isStaticDataMember() &&
1604         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1605       return false;
1606     if (VD->isStaticDataMember() &&
1607         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1608         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1609       return false;
1610 
1611     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1612       return false;
1613   } else {
1614     return false;
1615   }
1616 
1617   // Only warn for unused decls internal to the translation unit.
1618   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1619   // for inline functions defined in the main source file, for instance.
1620   return mightHaveNonExternalLinkage(D);
1621 }
1622 
1623 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1624   if (!D)
1625     return;
1626 
1627   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1628     const FunctionDecl *First = FD->getFirstDecl();
1629     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1630       return; // First should already be in the vector.
1631   }
1632 
1633   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1634     const VarDecl *First = VD->getFirstDecl();
1635     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1636       return; // First should already be in the vector.
1637   }
1638 
1639   if (ShouldWarnIfUnusedFileScopedDecl(D))
1640     UnusedFileScopedDecls.push_back(D);
1641 }
1642 
1643 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1644   if (D->isInvalidDecl())
1645     return false;
1646 
1647   bool Referenced = false;
1648   if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1649     // For a decomposition declaration, warn if none of the bindings are
1650     // referenced, instead of if the variable itself is referenced (which
1651     // it is, by the bindings' expressions).
1652     for (auto *BD : DD->bindings()) {
1653       if (BD->isReferenced()) {
1654         Referenced = true;
1655         break;
1656       }
1657     }
1658   } else if (!D->getDeclName()) {
1659     return false;
1660   } else if (D->isReferenced() || D->isUsed()) {
1661     Referenced = true;
1662   }
1663 
1664   if (Referenced || D->hasAttr<UnusedAttr>() ||
1665       D->hasAttr<ObjCPreciseLifetimeAttr>())
1666     return false;
1667 
1668   if (isa<LabelDecl>(D))
1669     return true;
1670 
1671   // Except for labels, we only care about unused decls that are local to
1672   // functions.
1673   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1674   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1675     // For dependent types, the diagnostic is deferred.
1676     WithinFunction =
1677         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1678   if (!WithinFunction)
1679     return false;
1680 
1681   if (isa<TypedefNameDecl>(D))
1682     return true;
1683 
1684   // White-list anything that isn't a local variable.
1685   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1686     return false;
1687 
1688   // Types of valid local variables should be complete, so this should succeed.
1689   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1690 
1691     // White-list anything with an __attribute__((unused)) type.
1692     const auto *Ty = VD->getType().getTypePtr();
1693 
1694     // Only look at the outermost level of typedef.
1695     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1696       if (TT->getDecl()->hasAttr<UnusedAttr>())
1697         return false;
1698     }
1699 
1700     // If we failed to complete the type for some reason, or if the type is
1701     // dependent, don't diagnose the variable.
1702     if (Ty->isIncompleteType() || Ty->isDependentType())
1703       return false;
1704 
1705     // Look at the element type to ensure that the warning behaviour is
1706     // consistent for both scalars and arrays.
1707     Ty = Ty->getBaseElementTypeUnsafe();
1708 
1709     if (const TagType *TT = Ty->getAs<TagType>()) {
1710       const TagDecl *Tag = TT->getDecl();
1711       if (Tag->hasAttr<UnusedAttr>())
1712         return false;
1713 
1714       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1715         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1716           return false;
1717 
1718         if (const Expr *Init = VD->getInit()) {
1719           if (const ExprWithCleanups *Cleanups =
1720                   dyn_cast<ExprWithCleanups>(Init))
1721             Init = Cleanups->getSubExpr();
1722           const CXXConstructExpr *Construct =
1723             dyn_cast<CXXConstructExpr>(Init);
1724           if (Construct && !Construct->isElidable()) {
1725             CXXConstructorDecl *CD = Construct->getConstructor();
1726             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1727                 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1728               return false;
1729           }
1730         }
1731       }
1732     }
1733 
1734     // TODO: __attribute__((unused)) templates?
1735   }
1736 
1737   return true;
1738 }
1739 
1740 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1741                                      FixItHint &Hint) {
1742   if (isa<LabelDecl>(D)) {
1743     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1744                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1745     if (AfterColon.isInvalid())
1746       return;
1747     Hint = FixItHint::CreateRemoval(CharSourceRange::
1748                                     getCharRange(D->getLocStart(), AfterColon));
1749   }
1750 }
1751 
1752 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1753   if (D->getTypeForDecl()->isDependentType())
1754     return;
1755 
1756   for (auto *TmpD : D->decls()) {
1757     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1758       DiagnoseUnusedDecl(T);
1759     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1760       DiagnoseUnusedNestedTypedefs(R);
1761   }
1762 }
1763 
1764 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1765 /// unless they are marked attr(unused).
1766 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1767   if (!ShouldDiagnoseUnusedDecl(D))
1768     return;
1769 
1770   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1771     // typedefs can be referenced later on, so the diagnostics are emitted
1772     // at end-of-translation-unit.
1773     UnusedLocalTypedefNameCandidates.insert(TD);
1774     return;
1775   }
1776 
1777   FixItHint Hint;
1778   GenerateFixForUnusedDecl(D, Context, Hint);
1779 
1780   unsigned DiagID;
1781   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1782     DiagID = diag::warn_unused_exception_param;
1783   else if (isa<LabelDecl>(D))
1784     DiagID = diag::warn_unused_label;
1785   else
1786     DiagID = diag::warn_unused_variable;
1787 
1788   Diag(D->getLocation(), DiagID) << D << Hint;
1789 }
1790 
1791 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1792   // Verify that we have no forward references left.  If so, there was a goto
1793   // or address of a label taken, but no definition of it.  Label fwd
1794   // definitions are indicated with a null substmt which is also not a resolved
1795   // MS inline assembly label name.
1796   bool Diagnose = false;
1797   if (L->isMSAsmLabel())
1798     Diagnose = !L->isResolvedMSAsmLabel();
1799   else
1800     Diagnose = L->getStmt() == nullptr;
1801   if (Diagnose)
1802     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1803 }
1804 
1805 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1806   S->mergeNRVOIntoParent();
1807 
1808   if (S->decl_empty()) return;
1809   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1810          "Scope shouldn't contain decls!");
1811 
1812   for (auto *TmpD : S->decls()) {
1813     assert(TmpD && "This decl didn't get pushed??");
1814 
1815     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1816     NamedDecl *D = cast<NamedDecl>(TmpD);
1817 
1818     // Diagnose unused variables in this scope.
1819     if (!S->hasUnrecoverableErrorOccurred()) {
1820       DiagnoseUnusedDecl(D);
1821       if (const auto *RD = dyn_cast<RecordDecl>(D))
1822         DiagnoseUnusedNestedTypedefs(RD);
1823     }
1824 
1825     if (!D->getDeclName()) continue;
1826 
1827     // If this was a forward reference to a label, verify it was defined.
1828     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1829       CheckPoppedLabel(LD, *this);
1830 
1831     // Remove this name from our lexical scope, and warn on it if we haven't
1832     // already.
1833     IdResolver.RemoveDecl(D);
1834     auto ShadowI = ShadowingDecls.find(D);
1835     if (ShadowI != ShadowingDecls.end()) {
1836       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1837         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1838             << D << FD << FD->getParent();
1839         Diag(FD->getLocation(), diag::note_previous_declaration);
1840       }
1841       ShadowingDecls.erase(ShadowI);
1842     }
1843   }
1844 }
1845 
1846 /// \brief Look for an Objective-C class in the translation unit.
1847 ///
1848 /// \param Id The name of the Objective-C class we're looking for. If
1849 /// typo-correction fixes this name, the Id will be updated
1850 /// to the fixed name.
1851 ///
1852 /// \param IdLoc The location of the name in the translation unit.
1853 ///
1854 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1855 /// if there is no class with the given name.
1856 ///
1857 /// \returns The declaration of the named Objective-C class, or NULL if the
1858 /// class could not be found.
1859 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1860                                               SourceLocation IdLoc,
1861                                               bool DoTypoCorrection) {
1862   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1863   // creation from this context.
1864   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1865 
1866   if (!IDecl && DoTypoCorrection) {
1867     // Perform typo correction at the given location, but only if we
1868     // find an Objective-C class name.
1869     if (TypoCorrection C = CorrectTypo(
1870             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1871             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1872             CTK_ErrorRecovery)) {
1873       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1874       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1875       Id = IDecl->getIdentifier();
1876     }
1877   }
1878   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1879   // This routine must always return a class definition, if any.
1880   if (Def && Def->getDefinition())
1881       Def = Def->getDefinition();
1882   return Def;
1883 }
1884 
1885 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1886 /// from S, where a non-field would be declared. This routine copes
1887 /// with the difference between C and C++ scoping rules in structs and
1888 /// unions. For example, the following code is well-formed in C but
1889 /// ill-formed in C++:
1890 /// @code
1891 /// struct S6 {
1892 ///   enum { BAR } e;
1893 /// };
1894 ///
1895 /// void test_S6() {
1896 ///   struct S6 a;
1897 ///   a.e = BAR;
1898 /// }
1899 /// @endcode
1900 /// For the declaration of BAR, this routine will return a different
1901 /// scope. The scope S will be the scope of the unnamed enumeration
1902 /// within S6. In C++, this routine will return the scope associated
1903 /// with S6, because the enumeration's scope is a transparent
1904 /// context but structures can contain non-field names. In C, this
1905 /// routine will return the translation unit scope, since the
1906 /// enumeration's scope is a transparent context and structures cannot
1907 /// contain non-field names.
1908 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1909   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1910          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1911          (S->isClassScope() && !getLangOpts().CPlusPlus))
1912     S = S->getParent();
1913   return S;
1914 }
1915 
1916 /// \brief Looks up the declaration of "struct objc_super" and
1917 /// saves it for later use in building builtin declaration of
1918 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1919 /// pre-existing declaration exists no action takes place.
1920 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1921                                         IdentifierInfo *II) {
1922   if (!II->isStr("objc_msgSendSuper"))
1923     return;
1924   ASTContext &Context = ThisSema.Context;
1925 
1926   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1927                       SourceLocation(), Sema::LookupTagName);
1928   ThisSema.LookupName(Result, S);
1929   if (Result.getResultKind() == LookupResult::Found)
1930     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1931       Context.setObjCSuperType(Context.getTagDeclType(TD));
1932 }
1933 
1934 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1935   switch (Error) {
1936   case ASTContext::GE_None:
1937     return "";
1938   case ASTContext::GE_Missing_stdio:
1939     return "stdio.h";
1940   case ASTContext::GE_Missing_setjmp:
1941     return "setjmp.h";
1942   case ASTContext::GE_Missing_ucontext:
1943     return "ucontext.h";
1944   }
1945   llvm_unreachable("unhandled error kind");
1946 }
1947 
1948 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1949 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1950 /// if we're creating this built-in in anticipation of redeclaring the
1951 /// built-in.
1952 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1953                                      Scope *S, bool ForRedeclaration,
1954                                      SourceLocation Loc) {
1955   LookupPredefedObjCSuperType(*this, S, II);
1956 
1957   ASTContext::GetBuiltinTypeError Error;
1958   QualType R = Context.GetBuiltinType(ID, Error);
1959   if (Error) {
1960     if (ForRedeclaration)
1961       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1962           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1963     return nullptr;
1964   }
1965 
1966   if (!ForRedeclaration &&
1967       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1968        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1969     Diag(Loc, diag::ext_implicit_lib_function_decl)
1970         << Context.BuiltinInfo.getName(ID) << R;
1971     if (Context.BuiltinInfo.getHeaderName(ID) &&
1972         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1973       Diag(Loc, diag::note_include_header_or_declare)
1974           << Context.BuiltinInfo.getHeaderName(ID)
1975           << Context.BuiltinInfo.getName(ID);
1976   }
1977 
1978   if (R.isNull())
1979     return nullptr;
1980 
1981   DeclContext *Parent = Context.getTranslationUnitDecl();
1982   if (getLangOpts().CPlusPlus) {
1983     LinkageSpecDecl *CLinkageDecl =
1984         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1985                                 LinkageSpecDecl::lang_c, false);
1986     CLinkageDecl->setImplicit();
1987     Parent->addDecl(CLinkageDecl);
1988     Parent = CLinkageDecl;
1989   }
1990 
1991   FunctionDecl *New = FunctionDecl::Create(Context,
1992                                            Parent,
1993                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1994                                            SC_Extern,
1995                                            false,
1996                                            R->isFunctionProtoType());
1997   New->setImplicit();
1998 
1999   // Create Decl objects for each parameter, adding them to the
2000   // FunctionDecl.
2001   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2002     SmallVector<ParmVarDecl*, 16> Params;
2003     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2004       ParmVarDecl *parm =
2005           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2006                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2007                               SC_None, nullptr);
2008       parm->setScopeInfo(0, i);
2009       Params.push_back(parm);
2010     }
2011     New->setParams(Params);
2012   }
2013 
2014   AddKnownFunctionAttributes(New);
2015   RegisterLocallyScopedExternCDecl(New, S);
2016 
2017   // TUScope is the translation-unit scope to insert this function into.
2018   // FIXME: This is hideous. We need to teach PushOnScopeChains to
2019   // relate Scopes to DeclContexts, and probably eliminate CurContext
2020   // entirely, but we're not there yet.
2021   DeclContext *SavedContext = CurContext;
2022   CurContext = Parent;
2023   PushOnScopeChains(New, TUScope);
2024   CurContext = SavedContext;
2025   return New;
2026 }
2027 
2028 /// Typedef declarations don't have linkage, but they still denote the same
2029 /// entity if their types are the same.
2030 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2031 /// isSameEntity.
2032 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2033                                                      TypedefNameDecl *Decl,
2034                                                      LookupResult &Previous) {
2035   // This is only interesting when modules are enabled.
2036   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2037     return;
2038 
2039   // Empty sets are uninteresting.
2040   if (Previous.empty())
2041     return;
2042 
2043   LookupResult::Filter Filter = Previous.makeFilter();
2044   while (Filter.hasNext()) {
2045     NamedDecl *Old = Filter.next();
2046 
2047     // Non-hidden declarations are never ignored.
2048     if (S.isVisible(Old))
2049       continue;
2050 
2051     // Declarations of the same entity are not ignored, even if they have
2052     // different linkages.
2053     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2054       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2055                                 Decl->getUnderlyingType()))
2056         continue;
2057 
2058       // If both declarations give a tag declaration a typedef name for linkage
2059       // purposes, then they declare the same entity.
2060       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2061           Decl->getAnonDeclWithTypedefName())
2062         continue;
2063     }
2064 
2065     Filter.erase();
2066   }
2067 
2068   Filter.done();
2069 }
2070 
2071 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2072   QualType OldType;
2073   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2074     OldType = OldTypedef->getUnderlyingType();
2075   else
2076     OldType = Context.getTypeDeclType(Old);
2077   QualType NewType = New->getUnderlyingType();
2078 
2079   if (NewType->isVariablyModifiedType()) {
2080     // Must not redefine a typedef with a variably-modified type.
2081     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2082     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2083       << Kind << NewType;
2084     if (Old->getLocation().isValid())
2085       notePreviousDefinition(Old, New->getLocation());
2086     New->setInvalidDecl();
2087     return true;
2088   }
2089 
2090   if (OldType != NewType &&
2091       !OldType->isDependentType() &&
2092       !NewType->isDependentType() &&
2093       !Context.hasSameType(OldType, NewType)) {
2094     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2095     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2096       << Kind << NewType << OldType;
2097     if (Old->getLocation().isValid())
2098       notePreviousDefinition(Old, New->getLocation());
2099     New->setInvalidDecl();
2100     return true;
2101   }
2102   return false;
2103 }
2104 
2105 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2106 /// same name and scope as a previous declaration 'Old'.  Figure out
2107 /// how to resolve this situation, merging decls or emitting
2108 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2109 ///
2110 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2111                                 LookupResult &OldDecls) {
2112   // If the new decl is known invalid already, don't bother doing any
2113   // merging checks.
2114   if (New->isInvalidDecl()) return;
2115 
2116   // Allow multiple definitions for ObjC built-in typedefs.
2117   // FIXME: Verify the underlying types are equivalent!
2118   if (getLangOpts().ObjC1) {
2119     const IdentifierInfo *TypeID = New->getIdentifier();
2120     switch (TypeID->getLength()) {
2121     default: break;
2122     case 2:
2123       {
2124         if (!TypeID->isStr("id"))
2125           break;
2126         QualType T = New->getUnderlyingType();
2127         if (!T->isPointerType())
2128           break;
2129         if (!T->isVoidPointerType()) {
2130           QualType PT = T->getAs<PointerType>()->getPointeeType();
2131           if (!PT->isStructureType())
2132             break;
2133         }
2134         Context.setObjCIdRedefinitionType(T);
2135         // Install the built-in type for 'id', ignoring the current definition.
2136         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2137         return;
2138       }
2139     case 5:
2140       if (!TypeID->isStr("Class"))
2141         break;
2142       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2143       // Install the built-in type for 'Class', ignoring the current definition.
2144       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2145       return;
2146     case 3:
2147       if (!TypeID->isStr("SEL"))
2148         break;
2149       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2150       // Install the built-in type for 'SEL', ignoring the current definition.
2151       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2152       return;
2153     }
2154     // Fall through - the typedef name was not a builtin type.
2155   }
2156 
2157   // Verify the old decl was also a type.
2158   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2159   if (!Old) {
2160     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2161       << New->getDeclName();
2162 
2163     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2164     if (OldD->getLocation().isValid())
2165       notePreviousDefinition(OldD, New->getLocation());
2166 
2167     return New->setInvalidDecl();
2168   }
2169 
2170   // If the old declaration is invalid, just give up here.
2171   if (Old->isInvalidDecl())
2172     return New->setInvalidDecl();
2173 
2174   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2175     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2176     auto *NewTag = New->getAnonDeclWithTypedefName();
2177     NamedDecl *Hidden = nullptr;
2178     if (OldTag && NewTag &&
2179         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2180         !hasVisibleDefinition(OldTag, &Hidden)) {
2181       // There is a definition of this tag, but it is not visible. Use it
2182       // instead of our tag.
2183       New->setTypeForDecl(OldTD->getTypeForDecl());
2184       if (OldTD->isModed())
2185         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2186                                     OldTD->getUnderlyingType());
2187       else
2188         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2189 
2190       // Make the old tag definition visible.
2191       makeMergedDefinitionVisible(Hidden);
2192 
2193       // If this was an unscoped enumeration, yank all of its enumerators
2194       // out of the scope.
2195       if (isa<EnumDecl>(NewTag)) {
2196         Scope *EnumScope = getNonFieldDeclScope(S);
2197         for (auto *D : NewTag->decls()) {
2198           auto *ED = cast<EnumConstantDecl>(D);
2199           assert(EnumScope->isDeclScope(ED));
2200           EnumScope->RemoveDecl(ED);
2201           IdResolver.RemoveDecl(ED);
2202           ED->getLexicalDeclContext()->removeDecl(ED);
2203         }
2204       }
2205     }
2206   }
2207 
2208   // If the typedef types are not identical, reject them in all languages and
2209   // with any extensions enabled.
2210   if (isIncompatibleTypedef(Old, New))
2211     return;
2212 
2213   // The types match.  Link up the redeclaration chain and merge attributes if
2214   // the old declaration was a typedef.
2215   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2216     New->setPreviousDecl(Typedef);
2217     mergeDeclAttributes(New, Old);
2218   }
2219 
2220   if (getLangOpts().MicrosoftExt)
2221     return;
2222 
2223   if (getLangOpts().CPlusPlus) {
2224     // C++ [dcl.typedef]p2:
2225     //   In a given non-class scope, a typedef specifier can be used to
2226     //   redefine the name of any type declared in that scope to refer
2227     //   to the type to which it already refers.
2228     if (!isa<CXXRecordDecl>(CurContext))
2229       return;
2230 
2231     // C++0x [dcl.typedef]p4:
2232     //   In a given class scope, a typedef specifier can be used to redefine
2233     //   any class-name declared in that scope that is not also a typedef-name
2234     //   to refer to the type to which it already refers.
2235     //
2236     // This wording came in via DR424, which was a correction to the
2237     // wording in DR56, which accidentally banned code like:
2238     //
2239     //   struct S {
2240     //     typedef struct A { } A;
2241     //   };
2242     //
2243     // in the C++03 standard. We implement the C++0x semantics, which
2244     // allow the above but disallow
2245     //
2246     //   struct S {
2247     //     typedef int I;
2248     //     typedef int I;
2249     //   };
2250     //
2251     // since that was the intent of DR56.
2252     if (!isa<TypedefNameDecl>(Old))
2253       return;
2254 
2255     Diag(New->getLocation(), diag::err_redefinition)
2256       << New->getDeclName();
2257     notePreviousDefinition(Old, New->getLocation());
2258     return New->setInvalidDecl();
2259   }
2260 
2261   // Modules always permit redefinition of typedefs, as does C11.
2262   if (getLangOpts().Modules || getLangOpts().C11)
2263     return;
2264 
2265   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2266   // is normally mapped to an error, but can be controlled with
2267   // -Wtypedef-redefinition.  If either the original or the redefinition is
2268   // in a system header, don't emit this for compatibility with GCC.
2269   if (getDiagnostics().getSuppressSystemWarnings() &&
2270       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2271       (Old->isImplicit() ||
2272        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2273        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2274     return;
2275 
2276   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2277     << New->getDeclName();
2278   notePreviousDefinition(Old, New->getLocation());
2279 }
2280 
2281 /// DeclhasAttr - returns true if decl Declaration already has the target
2282 /// attribute.
2283 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2284   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2285   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2286   for (const auto *i : D->attrs())
2287     if (i->getKind() == A->getKind()) {
2288       if (Ann) {
2289         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2290           return true;
2291         continue;
2292       }
2293       // FIXME: Don't hardcode this check
2294       if (OA && isa<OwnershipAttr>(i))
2295         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2296       return true;
2297     }
2298 
2299   return false;
2300 }
2301 
2302 static bool isAttributeTargetADefinition(Decl *D) {
2303   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2304     return VD->isThisDeclarationADefinition();
2305   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2306     return TD->isCompleteDefinition() || TD->isBeingDefined();
2307   return true;
2308 }
2309 
2310 /// Merge alignment attributes from \p Old to \p New, taking into account the
2311 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2312 ///
2313 /// \return \c true if any attributes were added to \p New.
2314 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2315   // Look for alignas attributes on Old, and pick out whichever attribute
2316   // specifies the strictest alignment requirement.
2317   AlignedAttr *OldAlignasAttr = nullptr;
2318   AlignedAttr *OldStrictestAlignAttr = nullptr;
2319   unsigned OldAlign = 0;
2320   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2321     // FIXME: We have no way of representing inherited dependent alignments
2322     // in a case like:
2323     //   template<int A, int B> struct alignas(A) X;
2324     //   template<int A, int B> struct alignas(B) X {};
2325     // For now, we just ignore any alignas attributes which are not on the
2326     // definition in such a case.
2327     if (I->isAlignmentDependent())
2328       return false;
2329 
2330     if (I->isAlignas())
2331       OldAlignasAttr = I;
2332 
2333     unsigned Align = I->getAlignment(S.Context);
2334     if (Align > OldAlign) {
2335       OldAlign = Align;
2336       OldStrictestAlignAttr = I;
2337     }
2338   }
2339 
2340   // Look for alignas attributes on New.
2341   AlignedAttr *NewAlignasAttr = nullptr;
2342   unsigned NewAlign = 0;
2343   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2344     if (I->isAlignmentDependent())
2345       return false;
2346 
2347     if (I->isAlignas())
2348       NewAlignasAttr = I;
2349 
2350     unsigned Align = I->getAlignment(S.Context);
2351     if (Align > NewAlign)
2352       NewAlign = Align;
2353   }
2354 
2355   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2356     // Both declarations have 'alignas' attributes. We require them to match.
2357     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2358     // fall short. (If two declarations both have alignas, they must both match
2359     // every definition, and so must match each other if there is a definition.)
2360 
2361     // If either declaration only contains 'alignas(0)' specifiers, then it
2362     // specifies the natural alignment for the type.
2363     if (OldAlign == 0 || NewAlign == 0) {
2364       QualType Ty;
2365       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2366         Ty = VD->getType();
2367       else
2368         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2369 
2370       if (OldAlign == 0)
2371         OldAlign = S.Context.getTypeAlign(Ty);
2372       if (NewAlign == 0)
2373         NewAlign = S.Context.getTypeAlign(Ty);
2374     }
2375 
2376     if (OldAlign != NewAlign) {
2377       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2378         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2379         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2380       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2381     }
2382   }
2383 
2384   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2385     // C++11 [dcl.align]p6:
2386     //   if any declaration of an entity has an alignment-specifier,
2387     //   every defining declaration of that entity shall specify an
2388     //   equivalent alignment.
2389     // C11 6.7.5/7:
2390     //   If the definition of an object does not have an alignment
2391     //   specifier, any other declaration of that object shall also
2392     //   have no alignment specifier.
2393     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2394       << OldAlignasAttr;
2395     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2396       << OldAlignasAttr;
2397   }
2398 
2399   bool AnyAdded = false;
2400 
2401   // Ensure we have an attribute representing the strictest alignment.
2402   if (OldAlign > NewAlign) {
2403     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2404     Clone->setInherited(true);
2405     New->addAttr(Clone);
2406     AnyAdded = true;
2407   }
2408 
2409   // Ensure we have an alignas attribute if the old declaration had one.
2410   if (OldAlignasAttr && !NewAlignasAttr &&
2411       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2412     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2413     Clone->setInherited(true);
2414     New->addAttr(Clone);
2415     AnyAdded = true;
2416   }
2417 
2418   return AnyAdded;
2419 }
2420 
2421 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2422                                const InheritableAttr *Attr,
2423                                Sema::AvailabilityMergeKind AMK) {
2424   // This function copies an attribute Attr from a previous declaration to the
2425   // new declaration D if the new declaration doesn't itself have that attribute
2426   // yet or if that attribute allows duplicates.
2427   // If you're adding a new attribute that requires logic different from
2428   // "use explicit attribute on decl if present, else use attribute from
2429   // previous decl", for example if the attribute needs to be consistent
2430   // between redeclarations, you need to call a custom merge function here.
2431   InheritableAttr *NewAttr = nullptr;
2432   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2433   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2434     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2435                                       AA->isImplicit(), AA->getIntroduced(),
2436                                       AA->getDeprecated(),
2437                                       AA->getObsoleted(), AA->getUnavailable(),
2438                                       AA->getMessage(), AA->getStrict(),
2439                                       AA->getReplacement(), AMK,
2440                                       AttrSpellingListIndex);
2441   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2442     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2443                                     AttrSpellingListIndex);
2444   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2445     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2446                                         AttrSpellingListIndex);
2447   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2448     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2449                                    AttrSpellingListIndex);
2450   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2451     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2452                                    AttrSpellingListIndex);
2453   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2454     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2455                                 FA->getFormatIdx(), FA->getFirstArg(),
2456                                 AttrSpellingListIndex);
2457   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2458     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2459                                  AttrSpellingListIndex);
2460   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2461     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2462                                        AttrSpellingListIndex,
2463                                        IA->getSemanticSpelling());
2464   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2465     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2466                                       &S.Context.Idents.get(AA->getSpelling()),
2467                                       AttrSpellingListIndex);
2468   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2469            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2470             isa<CUDAGlobalAttr>(Attr))) {
2471     // CUDA target attributes are part of function signature for
2472     // overloading purposes and must not be merged.
2473     return false;
2474   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2475     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2476   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2477     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2478   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2479     NewAttr = S.mergeInternalLinkageAttr(
2480         D, InternalLinkageA->getRange(),
2481         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2482         AttrSpellingListIndex);
2483   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2484     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2485                                 &S.Context.Idents.get(CommonA->getSpelling()),
2486                                 AttrSpellingListIndex);
2487   else if (isa<AlignedAttr>(Attr))
2488     // AlignedAttrs are handled separately, because we need to handle all
2489     // such attributes on a declaration at the same time.
2490     NewAttr = nullptr;
2491   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2492            (AMK == Sema::AMK_Override ||
2493             AMK == Sema::AMK_ProtocolImplementation))
2494     NewAttr = nullptr;
2495   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2496     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2497                               UA->getGuid());
2498   else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2499     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2500 
2501   if (NewAttr) {
2502     NewAttr->setInherited(true);
2503     D->addAttr(NewAttr);
2504     if (isa<MSInheritanceAttr>(NewAttr))
2505       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2506     return true;
2507   }
2508 
2509   return false;
2510 }
2511 
2512 static const NamedDecl *getDefinition(const Decl *D) {
2513   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2514     return TD->getDefinition();
2515   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2516     const VarDecl *Def = VD->getDefinition();
2517     if (Def)
2518       return Def;
2519     return VD->getActingDefinition();
2520   }
2521   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2522     return FD->getDefinition();
2523   return nullptr;
2524 }
2525 
2526 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2527   for (const auto *Attribute : D->attrs())
2528     if (Attribute->getKind() == Kind)
2529       return true;
2530   return false;
2531 }
2532 
2533 /// checkNewAttributesAfterDef - If we already have a definition, check that
2534 /// there are no new attributes in this declaration.
2535 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2536   if (!New->hasAttrs())
2537     return;
2538 
2539   const NamedDecl *Def = getDefinition(Old);
2540   if (!Def || Def == New)
2541     return;
2542 
2543   AttrVec &NewAttributes = New->getAttrs();
2544   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2545     const Attr *NewAttribute = NewAttributes[I];
2546 
2547     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2548       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2549         Sema::SkipBodyInfo SkipBody;
2550         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2551 
2552         // If we're skipping this definition, drop the "alias" attribute.
2553         if (SkipBody.ShouldSkip) {
2554           NewAttributes.erase(NewAttributes.begin() + I);
2555           --E;
2556           continue;
2557         }
2558       } else {
2559         VarDecl *VD = cast<VarDecl>(New);
2560         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2561                                 VarDecl::TentativeDefinition
2562                             ? diag::err_alias_after_tentative
2563                             : diag::err_redefinition;
2564         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2565         if (Diag == diag::err_redefinition)
2566           S.notePreviousDefinition(Def, VD->getLocation());
2567         else
2568           S.Diag(Def->getLocation(), diag::note_previous_definition);
2569         VD->setInvalidDecl();
2570       }
2571       ++I;
2572       continue;
2573     }
2574 
2575     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2576       // Tentative definitions are only interesting for the alias check above.
2577       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2578         ++I;
2579         continue;
2580       }
2581     }
2582 
2583     if (hasAttribute(Def, NewAttribute->getKind())) {
2584       ++I;
2585       continue; // regular attr merging will take care of validating this.
2586     }
2587 
2588     if (isa<C11NoReturnAttr>(NewAttribute)) {
2589       // C's _Noreturn is allowed to be added to a function after it is defined.
2590       ++I;
2591       continue;
2592     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2593       if (AA->isAlignas()) {
2594         // C++11 [dcl.align]p6:
2595         //   if any declaration of an entity has an alignment-specifier,
2596         //   every defining declaration of that entity shall specify an
2597         //   equivalent alignment.
2598         // C11 6.7.5/7:
2599         //   If the definition of an object does not have an alignment
2600         //   specifier, any other declaration of that object shall also
2601         //   have no alignment specifier.
2602         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2603           << AA;
2604         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2605           << AA;
2606         NewAttributes.erase(NewAttributes.begin() + I);
2607         --E;
2608         continue;
2609       }
2610     }
2611 
2612     S.Diag(NewAttribute->getLocation(),
2613            diag::warn_attribute_precede_definition);
2614     S.Diag(Def->getLocation(), diag::note_previous_definition);
2615     NewAttributes.erase(NewAttributes.begin() + I);
2616     --E;
2617   }
2618 }
2619 
2620 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2621 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2622                                AvailabilityMergeKind AMK) {
2623   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2624     UsedAttr *NewAttr = OldAttr->clone(Context);
2625     NewAttr->setInherited(true);
2626     New->addAttr(NewAttr);
2627   }
2628 
2629   if (!Old->hasAttrs() && !New->hasAttrs())
2630     return;
2631 
2632   // Attributes declared post-definition are currently ignored.
2633   checkNewAttributesAfterDef(*this, New, Old);
2634 
2635   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2636     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2637       if (OldA->getLabel() != NewA->getLabel()) {
2638         // This redeclaration changes __asm__ label.
2639         Diag(New->getLocation(), diag::err_different_asm_label);
2640         Diag(OldA->getLocation(), diag::note_previous_declaration);
2641       }
2642     } else if (Old->isUsed()) {
2643       // This redeclaration adds an __asm__ label to a declaration that has
2644       // already been ODR-used.
2645       Diag(New->getLocation(), diag::err_late_asm_label_name)
2646         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2647     }
2648   }
2649 
2650   // Re-declaration cannot add abi_tag's.
2651   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2652     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2653       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2654         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2655                       NewTag) == OldAbiTagAttr->tags_end()) {
2656           Diag(NewAbiTagAttr->getLocation(),
2657                diag::err_new_abi_tag_on_redeclaration)
2658               << NewTag;
2659           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2660         }
2661       }
2662     } else {
2663       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2664       Diag(Old->getLocation(), diag::note_previous_declaration);
2665     }
2666   }
2667 
2668   // This redeclaration adds a section attribute.
2669   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2670     if (auto *VD = dyn_cast<VarDecl>(New)) {
2671       if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2672         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2673         Diag(Old->getLocation(), diag::note_previous_declaration);
2674       }
2675     }
2676   }
2677 
2678   if (!Old->hasAttrs())
2679     return;
2680 
2681   bool foundAny = New->hasAttrs();
2682 
2683   // Ensure that any moving of objects within the allocated map is done before
2684   // we process them.
2685   if (!foundAny) New->setAttrs(AttrVec());
2686 
2687   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2688     // Ignore deprecated/unavailable/availability attributes if requested.
2689     AvailabilityMergeKind LocalAMK = AMK_None;
2690     if (isa<DeprecatedAttr>(I) ||
2691         isa<UnavailableAttr>(I) ||
2692         isa<AvailabilityAttr>(I)) {
2693       switch (AMK) {
2694       case AMK_None:
2695         continue;
2696 
2697       case AMK_Redeclaration:
2698       case AMK_Override:
2699       case AMK_ProtocolImplementation:
2700         LocalAMK = AMK;
2701         break;
2702       }
2703     }
2704 
2705     // Already handled.
2706     if (isa<UsedAttr>(I))
2707       continue;
2708 
2709     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2710       foundAny = true;
2711   }
2712 
2713   if (mergeAlignedAttrs(*this, New, Old))
2714     foundAny = true;
2715 
2716   if (!foundAny) New->dropAttrs();
2717 }
2718 
2719 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2720 /// to the new one.
2721 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2722                                      const ParmVarDecl *oldDecl,
2723                                      Sema &S) {
2724   // C++11 [dcl.attr.depend]p2:
2725   //   The first declaration of a function shall specify the
2726   //   carries_dependency attribute for its declarator-id if any declaration
2727   //   of the function specifies the carries_dependency attribute.
2728   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2729   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2730     S.Diag(CDA->getLocation(),
2731            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2732     // Find the first declaration of the parameter.
2733     // FIXME: Should we build redeclaration chains for function parameters?
2734     const FunctionDecl *FirstFD =
2735       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2736     const ParmVarDecl *FirstVD =
2737       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2738     S.Diag(FirstVD->getLocation(),
2739            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2740   }
2741 
2742   if (!oldDecl->hasAttrs())
2743     return;
2744 
2745   bool foundAny = newDecl->hasAttrs();
2746 
2747   // Ensure that any moving of objects within the allocated map is
2748   // done before we process them.
2749   if (!foundAny) newDecl->setAttrs(AttrVec());
2750 
2751   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2752     if (!DeclHasAttr(newDecl, I)) {
2753       InheritableAttr *newAttr =
2754         cast<InheritableParamAttr>(I->clone(S.Context));
2755       newAttr->setInherited(true);
2756       newDecl->addAttr(newAttr);
2757       foundAny = true;
2758     }
2759   }
2760 
2761   if (!foundAny) newDecl->dropAttrs();
2762 }
2763 
2764 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2765                                 const ParmVarDecl *OldParam,
2766                                 Sema &S) {
2767   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2768     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2769       if (*Oldnullability != *Newnullability) {
2770         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2771           << DiagNullabilityKind(
2772                *Newnullability,
2773                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2774                 != 0))
2775           << DiagNullabilityKind(
2776                *Oldnullability,
2777                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2778                 != 0));
2779         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2780       }
2781     } else {
2782       QualType NewT = NewParam->getType();
2783       NewT = S.Context.getAttributedType(
2784                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2785                          NewT, NewT);
2786       NewParam->setType(NewT);
2787     }
2788   }
2789 }
2790 
2791 namespace {
2792 
2793 /// Used in MergeFunctionDecl to keep track of function parameters in
2794 /// C.
2795 struct GNUCompatibleParamWarning {
2796   ParmVarDecl *OldParm;
2797   ParmVarDecl *NewParm;
2798   QualType PromotedType;
2799 };
2800 
2801 } // end anonymous namespace
2802 
2803 /// getSpecialMember - get the special member enum for a method.
2804 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2805   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2806     if (Ctor->isDefaultConstructor())
2807       return Sema::CXXDefaultConstructor;
2808 
2809     if (Ctor->isCopyConstructor())
2810       return Sema::CXXCopyConstructor;
2811 
2812     if (Ctor->isMoveConstructor())
2813       return Sema::CXXMoveConstructor;
2814   } else if (isa<CXXDestructorDecl>(MD)) {
2815     return Sema::CXXDestructor;
2816   } else if (MD->isCopyAssignmentOperator()) {
2817     return Sema::CXXCopyAssignment;
2818   } else if (MD->isMoveAssignmentOperator()) {
2819     return Sema::CXXMoveAssignment;
2820   }
2821 
2822   return Sema::CXXInvalid;
2823 }
2824 
2825 // Determine whether the previous declaration was a definition, implicit
2826 // declaration, or a declaration.
2827 template <typename T>
2828 static std::pair<diag::kind, SourceLocation>
2829 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2830   diag::kind PrevDiag;
2831   SourceLocation OldLocation = Old->getLocation();
2832   if (Old->isThisDeclarationADefinition())
2833     PrevDiag = diag::note_previous_definition;
2834   else if (Old->isImplicit()) {
2835     PrevDiag = diag::note_previous_implicit_declaration;
2836     if (OldLocation.isInvalid())
2837       OldLocation = New->getLocation();
2838   } else
2839     PrevDiag = diag::note_previous_declaration;
2840   return std::make_pair(PrevDiag, OldLocation);
2841 }
2842 
2843 /// canRedefineFunction - checks if a function can be redefined. Currently,
2844 /// only extern inline functions can be redefined, and even then only in
2845 /// GNU89 mode.
2846 static bool canRedefineFunction(const FunctionDecl *FD,
2847                                 const LangOptions& LangOpts) {
2848   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2849           !LangOpts.CPlusPlus &&
2850           FD->isInlineSpecified() &&
2851           FD->getStorageClass() == SC_Extern);
2852 }
2853 
2854 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2855   const AttributedType *AT = T->getAs<AttributedType>();
2856   while (AT && !AT->isCallingConv())
2857     AT = AT->getModifiedType()->getAs<AttributedType>();
2858   return AT;
2859 }
2860 
2861 template <typename T>
2862 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2863   const DeclContext *DC = Old->getDeclContext();
2864   if (DC->isRecord())
2865     return false;
2866 
2867   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2868   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2869     return true;
2870   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2871     return true;
2872   return false;
2873 }
2874 
2875 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2876 static bool isExternC(VarTemplateDecl *) { return false; }
2877 
2878 /// \brief Check whether a redeclaration of an entity introduced by a
2879 /// using-declaration is valid, given that we know it's not an overload
2880 /// (nor a hidden tag declaration).
2881 template<typename ExpectedDecl>
2882 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2883                                    ExpectedDecl *New) {
2884   // C++11 [basic.scope.declarative]p4:
2885   //   Given a set of declarations in a single declarative region, each of
2886   //   which specifies the same unqualified name,
2887   //   -- they shall all refer to the same entity, or all refer to functions
2888   //      and function templates; or
2889   //   -- exactly one declaration shall declare a class name or enumeration
2890   //      name that is not a typedef name and the other declarations shall all
2891   //      refer to the same variable or enumerator, or all refer to functions
2892   //      and function templates; in this case the class name or enumeration
2893   //      name is hidden (3.3.10).
2894 
2895   // C++11 [namespace.udecl]p14:
2896   //   If a function declaration in namespace scope or block scope has the
2897   //   same name and the same parameter-type-list as a function introduced
2898   //   by a using-declaration, and the declarations do not declare the same
2899   //   function, the program is ill-formed.
2900 
2901   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2902   if (Old &&
2903       !Old->getDeclContext()->getRedeclContext()->Equals(
2904           New->getDeclContext()->getRedeclContext()) &&
2905       !(isExternC(Old) && isExternC(New)))
2906     Old = nullptr;
2907 
2908   if (!Old) {
2909     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2910     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2911     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2912     return true;
2913   }
2914   return false;
2915 }
2916 
2917 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2918                                             const FunctionDecl *B) {
2919   assert(A->getNumParams() == B->getNumParams());
2920 
2921   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2922     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2923     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2924     if (AttrA == AttrB)
2925       return true;
2926     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2927   };
2928 
2929   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2930 }
2931 
2932 /// If necessary, adjust the semantic declaration context for a qualified
2933 /// declaration to name the correct inline namespace within the qualifier.
2934 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2935                                                DeclaratorDecl *OldD) {
2936   // The only case where we need to update the DeclContext is when
2937   // redeclaration lookup for a qualified name finds a declaration
2938   // in an inline namespace within the context named by the qualifier:
2939   //
2940   //   inline namespace N { int f(); }
2941   //   int ::f(); // Sema DC needs adjusting from :: to N::.
2942   //
2943   // For unqualified declarations, the semantic context *can* change
2944   // along the redeclaration chain (for local extern declarations,
2945   // extern "C" declarations, and friend declarations in particular).
2946   if (!NewD->getQualifier())
2947     return;
2948 
2949   // NewD is probably already in the right context.
2950   auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2951   auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2952   if (NamedDC->Equals(SemaDC))
2953     return;
2954 
2955   assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2956           NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2957          "unexpected context for redeclaration");
2958 
2959   auto *LexDC = NewD->getLexicalDeclContext();
2960   auto FixSemaDC = [=](NamedDecl *D) {
2961     if (!D)
2962       return;
2963     D->setDeclContext(SemaDC);
2964     D->setLexicalDeclContext(LexDC);
2965   };
2966 
2967   FixSemaDC(NewD);
2968   if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2969     FixSemaDC(FD->getDescribedFunctionTemplate());
2970   else if (auto *VD = dyn_cast<VarDecl>(NewD))
2971     FixSemaDC(VD->getDescribedVarTemplate());
2972 }
2973 
2974 /// MergeFunctionDecl - We just parsed a function 'New' from
2975 /// declarator D which has the same name and scope as a previous
2976 /// declaration 'Old'.  Figure out how to resolve this situation,
2977 /// merging decls or emitting diagnostics as appropriate.
2978 ///
2979 /// In C++, New and Old must be declarations that are not
2980 /// overloaded. Use IsOverload to determine whether New and Old are
2981 /// overloaded, and to select the Old declaration that New should be
2982 /// merged with.
2983 ///
2984 /// Returns true if there was an error, false otherwise.
2985 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2986                              Scope *S, bool MergeTypeWithOld) {
2987   // Verify the old decl was also a function.
2988   FunctionDecl *Old = OldD->getAsFunction();
2989   if (!Old) {
2990     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2991       if (New->getFriendObjectKind()) {
2992         Diag(New->getLocation(), diag::err_using_decl_friend);
2993         Diag(Shadow->getTargetDecl()->getLocation(),
2994              diag::note_using_decl_target);
2995         Diag(Shadow->getUsingDecl()->getLocation(),
2996              diag::note_using_decl) << 0;
2997         return true;
2998       }
2999 
3000       // Check whether the two declarations might declare the same function.
3001       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3002         return true;
3003       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3004     } else {
3005       Diag(New->getLocation(), diag::err_redefinition_different_kind)
3006         << New->getDeclName();
3007       notePreviousDefinition(OldD, New->getLocation());
3008       return true;
3009     }
3010   }
3011 
3012   // If the old declaration is invalid, just give up here.
3013   if (Old->isInvalidDecl())
3014     return true;
3015 
3016   diag::kind PrevDiag;
3017   SourceLocation OldLocation;
3018   std::tie(PrevDiag, OldLocation) =
3019       getNoteDiagForInvalidRedeclaration(Old, New);
3020 
3021   // Don't complain about this if we're in GNU89 mode and the old function
3022   // is an extern inline function.
3023   // Don't complain about specializations. They are not supposed to have
3024   // storage classes.
3025   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3026       New->getStorageClass() == SC_Static &&
3027       Old->hasExternalFormalLinkage() &&
3028       !New->getTemplateSpecializationInfo() &&
3029       !canRedefineFunction(Old, getLangOpts())) {
3030     if (getLangOpts().MicrosoftExt) {
3031       Diag(New->getLocation(), diag::ext_static_non_static) << New;
3032       Diag(OldLocation, PrevDiag);
3033     } else {
3034       Diag(New->getLocation(), diag::err_static_non_static) << New;
3035       Diag(OldLocation, PrevDiag);
3036       return true;
3037     }
3038   }
3039 
3040   if (New->hasAttr<InternalLinkageAttr>() &&
3041       !Old->hasAttr<InternalLinkageAttr>()) {
3042     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3043         << New->getDeclName();
3044     notePreviousDefinition(Old, New->getLocation());
3045     New->dropAttr<InternalLinkageAttr>();
3046   }
3047 
3048   if (CheckRedeclarationModuleOwnership(New, Old))
3049     return true;
3050 
3051   if (!getLangOpts().CPlusPlus) {
3052     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3053     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3054       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3055         << New << OldOvl;
3056 
3057       // Try our best to find a decl that actually has the overloadable
3058       // attribute for the note. In most cases (e.g. programs with only one
3059       // broken declaration/definition), this won't matter.
3060       //
3061       // FIXME: We could do this if we juggled some extra state in
3062       // OverloadableAttr, rather than just removing it.
3063       const Decl *DiagOld = Old;
3064       if (OldOvl) {
3065         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3066           const auto *A = D->getAttr<OverloadableAttr>();
3067           return A && !A->isImplicit();
3068         });
3069         // If we've implicitly added *all* of the overloadable attrs to this
3070         // chain, emitting a "previous redecl" note is pointless.
3071         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3072       }
3073 
3074       if (DiagOld)
3075         Diag(DiagOld->getLocation(),
3076              diag::note_attribute_overloadable_prev_overload)
3077           << OldOvl;
3078 
3079       if (OldOvl)
3080         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3081       else
3082         New->dropAttr<OverloadableAttr>();
3083     }
3084   }
3085 
3086   // If a function is first declared with a calling convention, but is later
3087   // declared or defined without one, all following decls assume the calling
3088   // convention of the first.
3089   //
3090   // It's OK if a function is first declared without a calling convention,
3091   // but is later declared or defined with the default calling convention.
3092   //
3093   // To test if either decl has an explicit calling convention, we look for
3094   // AttributedType sugar nodes on the type as written.  If they are missing or
3095   // were canonicalized away, we assume the calling convention was implicit.
3096   //
3097   // Note also that we DO NOT return at this point, because we still have
3098   // other tests to run.
3099   QualType OldQType = Context.getCanonicalType(Old->getType());
3100   QualType NewQType = Context.getCanonicalType(New->getType());
3101   const FunctionType *OldType = cast<FunctionType>(OldQType);
3102   const FunctionType *NewType = cast<FunctionType>(NewQType);
3103   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3104   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3105   bool RequiresAdjustment = false;
3106 
3107   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3108     FunctionDecl *First = Old->getFirstDecl();
3109     const FunctionType *FT =
3110         First->getType().getCanonicalType()->castAs<FunctionType>();
3111     FunctionType::ExtInfo FI = FT->getExtInfo();
3112     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3113     if (!NewCCExplicit) {
3114       // Inherit the CC from the previous declaration if it was specified
3115       // there but not here.
3116       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3117       RequiresAdjustment = true;
3118     } else {
3119       // Calling conventions aren't compatible, so complain.
3120       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3121       Diag(New->getLocation(), diag::err_cconv_change)
3122         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3123         << !FirstCCExplicit
3124         << (!FirstCCExplicit ? "" :
3125             FunctionType::getNameForCallConv(FI.getCC()));
3126 
3127       // Put the note on the first decl, since it is the one that matters.
3128       Diag(First->getLocation(), diag::note_previous_declaration);
3129       return true;
3130     }
3131   }
3132 
3133   // FIXME: diagnose the other way around?
3134   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3135     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3136     RequiresAdjustment = true;
3137   }
3138 
3139   // Merge regparm attribute.
3140   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3141       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3142     if (NewTypeInfo.getHasRegParm()) {
3143       Diag(New->getLocation(), diag::err_regparm_mismatch)
3144         << NewType->getRegParmType()
3145         << OldType->getRegParmType();
3146       Diag(OldLocation, diag::note_previous_declaration);
3147       return true;
3148     }
3149 
3150     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3151     RequiresAdjustment = true;
3152   }
3153 
3154   // Merge ns_returns_retained attribute.
3155   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3156     if (NewTypeInfo.getProducesResult()) {
3157       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3158           << "'ns_returns_retained'";
3159       Diag(OldLocation, diag::note_previous_declaration);
3160       return true;
3161     }
3162 
3163     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3164     RequiresAdjustment = true;
3165   }
3166 
3167   if (OldTypeInfo.getNoCallerSavedRegs() !=
3168       NewTypeInfo.getNoCallerSavedRegs()) {
3169     if (NewTypeInfo.getNoCallerSavedRegs()) {
3170       AnyX86NoCallerSavedRegistersAttr *Attr =
3171         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3172       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3173       Diag(OldLocation, diag::note_previous_declaration);
3174       return true;
3175     }
3176 
3177     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3178     RequiresAdjustment = true;
3179   }
3180 
3181   if (RequiresAdjustment) {
3182     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3183     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3184     New->setType(QualType(AdjustedType, 0));
3185     NewQType = Context.getCanonicalType(New->getType());
3186     NewType = cast<FunctionType>(NewQType);
3187   }
3188 
3189   // If this redeclaration makes the function inline, we may need to add it to
3190   // UndefinedButUsed.
3191   if (!Old->isInlined() && New->isInlined() &&
3192       !New->hasAttr<GNUInlineAttr>() &&
3193       !getLangOpts().GNUInline &&
3194       Old->isUsed(false) &&
3195       !Old->isDefined() && !New->isThisDeclarationADefinition())
3196     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3197                                            SourceLocation()));
3198 
3199   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3200   // about it.
3201   if (New->hasAttr<GNUInlineAttr>() &&
3202       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3203     UndefinedButUsed.erase(Old->getCanonicalDecl());
3204   }
3205 
3206   // If pass_object_size params don't match up perfectly, this isn't a valid
3207   // redeclaration.
3208   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3209       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3210     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3211         << New->getDeclName();
3212     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3213     return true;
3214   }
3215 
3216   if (getLangOpts().CPlusPlus) {
3217     // C++1z [over.load]p2
3218     //   Certain function declarations cannot be overloaded:
3219     //     -- Function declarations that differ only in the return type,
3220     //        the exception specification, or both cannot be overloaded.
3221 
3222     // Check the exception specifications match. This may recompute the type of
3223     // both Old and New if it resolved exception specifications, so grab the
3224     // types again after this. Because this updates the type, we do this before
3225     // any of the other checks below, which may update the "de facto" NewQType
3226     // but do not necessarily update the type of New.
3227     if (CheckEquivalentExceptionSpec(Old, New))
3228       return true;
3229     OldQType = Context.getCanonicalType(Old->getType());
3230     NewQType = Context.getCanonicalType(New->getType());
3231 
3232     // Go back to the type source info to compare the declared return types,
3233     // per C++1y [dcl.type.auto]p13:
3234     //   Redeclarations or specializations of a function or function template
3235     //   with a declared return type that uses a placeholder type shall also
3236     //   use that placeholder, not a deduced type.
3237     QualType OldDeclaredReturnType =
3238         (Old->getTypeSourceInfo()
3239              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3240              : OldType)->getReturnType();
3241     QualType NewDeclaredReturnType =
3242         (New->getTypeSourceInfo()
3243              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3244              : NewType)->getReturnType();
3245     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3246         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3247           New->isLocalExternDecl())) {
3248       QualType ResQT;
3249       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3250           OldDeclaredReturnType->isObjCObjectPointerType())
3251         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3252       if (ResQT.isNull()) {
3253         if (New->isCXXClassMember() && New->isOutOfLine())
3254           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3255               << New << New->getReturnTypeSourceRange();
3256         else
3257           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3258               << New->getReturnTypeSourceRange();
3259         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3260                                     << Old->getReturnTypeSourceRange();
3261         return true;
3262       }
3263       else
3264         NewQType = ResQT;
3265     }
3266 
3267     QualType OldReturnType = OldType->getReturnType();
3268     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3269     if (OldReturnType != NewReturnType) {
3270       // If this function has a deduced return type and has already been
3271       // defined, copy the deduced value from the old declaration.
3272       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3273       if (OldAT && OldAT->isDeduced()) {
3274         New->setType(
3275             SubstAutoType(New->getType(),
3276                           OldAT->isDependentType() ? Context.DependentTy
3277                                                    : OldAT->getDeducedType()));
3278         NewQType = Context.getCanonicalType(
3279             SubstAutoType(NewQType,
3280                           OldAT->isDependentType() ? Context.DependentTy
3281                                                    : OldAT->getDeducedType()));
3282       }
3283     }
3284 
3285     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3286     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3287     if (OldMethod && NewMethod) {
3288       // Preserve triviality.
3289       NewMethod->setTrivial(OldMethod->isTrivial());
3290 
3291       // MSVC allows explicit template specialization at class scope:
3292       // 2 CXXMethodDecls referring to the same function will be injected.
3293       // We don't want a redeclaration error.
3294       bool IsClassScopeExplicitSpecialization =
3295                               OldMethod->isFunctionTemplateSpecialization() &&
3296                               NewMethod->isFunctionTemplateSpecialization();
3297       bool isFriend = NewMethod->getFriendObjectKind();
3298 
3299       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3300           !IsClassScopeExplicitSpecialization) {
3301         //    -- Member function declarations with the same name and the
3302         //       same parameter types cannot be overloaded if any of them
3303         //       is a static member function declaration.
3304         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3305           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3306           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3307           return true;
3308         }
3309 
3310         // C++ [class.mem]p1:
3311         //   [...] A member shall not be declared twice in the
3312         //   member-specification, except that a nested class or member
3313         //   class template can be declared and then later defined.
3314         if (!inTemplateInstantiation()) {
3315           unsigned NewDiag;
3316           if (isa<CXXConstructorDecl>(OldMethod))
3317             NewDiag = diag::err_constructor_redeclared;
3318           else if (isa<CXXDestructorDecl>(NewMethod))
3319             NewDiag = diag::err_destructor_redeclared;
3320           else if (isa<CXXConversionDecl>(NewMethod))
3321             NewDiag = diag::err_conv_function_redeclared;
3322           else
3323             NewDiag = diag::err_member_redeclared;
3324 
3325           Diag(New->getLocation(), NewDiag);
3326         } else {
3327           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3328             << New << New->getType();
3329         }
3330         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3331         return true;
3332 
3333       // Complain if this is an explicit declaration of a special
3334       // member that was initially declared implicitly.
3335       //
3336       // As an exception, it's okay to befriend such methods in order
3337       // to permit the implicit constructor/destructor/operator calls.
3338       } else if (OldMethod->isImplicit()) {
3339         if (isFriend) {
3340           NewMethod->setImplicit();
3341         } else {
3342           Diag(NewMethod->getLocation(),
3343                diag::err_definition_of_implicitly_declared_member)
3344             << New << getSpecialMember(OldMethod);
3345           return true;
3346         }
3347       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3348         Diag(NewMethod->getLocation(),
3349              diag::err_definition_of_explicitly_defaulted_member)
3350           << getSpecialMember(OldMethod);
3351         return true;
3352       }
3353     }
3354 
3355     // C++11 [dcl.attr.noreturn]p1:
3356     //   The first declaration of a function shall specify the noreturn
3357     //   attribute if any declaration of that function specifies the noreturn
3358     //   attribute.
3359     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3360     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3361       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3362       Diag(Old->getFirstDecl()->getLocation(),
3363            diag::note_noreturn_missing_first_decl);
3364     }
3365 
3366     // C++11 [dcl.attr.depend]p2:
3367     //   The first declaration of a function shall specify the
3368     //   carries_dependency attribute for its declarator-id if any declaration
3369     //   of the function specifies the carries_dependency attribute.
3370     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3371     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3372       Diag(CDA->getLocation(),
3373            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3374       Diag(Old->getFirstDecl()->getLocation(),
3375            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3376     }
3377 
3378     // (C++98 8.3.5p3):
3379     //   All declarations for a function shall agree exactly in both the
3380     //   return type and the parameter-type-list.
3381     // We also want to respect all the extended bits except noreturn.
3382 
3383     // noreturn should now match unless the old type info didn't have it.
3384     QualType OldQTypeForComparison = OldQType;
3385     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3386       auto *OldType = OldQType->castAs<FunctionProtoType>();
3387       const FunctionType *OldTypeForComparison
3388         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3389       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3390       assert(OldQTypeForComparison.isCanonical());
3391     }
3392 
3393     if (haveIncompatibleLanguageLinkages(Old, New)) {
3394       // As a special case, retain the language linkage from previous
3395       // declarations of a friend function as an extension.
3396       //
3397       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3398       // and is useful because there's otherwise no way to specify language
3399       // linkage within class scope.
3400       //
3401       // Check cautiously as the friend object kind isn't yet complete.
3402       if (New->getFriendObjectKind() != Decl::FOK_None) {
3403         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3404         Diag(OldLocation, PrevDiag);
3405       } else {
3406         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3407         Diag(OldLocation, PrevDiag);
3408         return true;
3409       }
3410     }
3411 
3412     if (OldQTypeForComparison == NewQType)
3413       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3414 
3415     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3416         New->isLocalExternDecl()) {
3417       // It's OK if we couldn't merge types for a local function declaraton
3418       // if either the old or new type is dependent. We'll merge the types
3419       // when we instantiate the function.
3420       return false;
3421     }
3422 
3423     // Fall through for conflicting redeclarations and redefinitions.
3424   }
3425 
3426   // C: Function types need to be compatible, not identical. This handles
3427   // duplicate function decls like "void f(int); void f(enum X);" properly.
3428   if (!getLangOpts().CPlusPlus &&
3429       Context.typesAreCompatible(OldQType, NewQType)) {
3430     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3431     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3432     const FunctionProtoType *OldProto = nullptr;
3433     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3434         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3435       // The old declaration provided a function prototype, but the
3436       // new declaration does not. Merge in the prototype.
3437       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3438       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3439       NewQType =
3440           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3441                                   OldProto->getExtProtoInfo());
3442       New->setType(NewQType);
3443       New->setHasInheritedPrototype();
3444 
3445       // Synthesize parameters with the same types.
3446       SmallVector<ParmVarDecl*, 16> Params;
3447       for (const auto &ParamType : OldProto->param_types()) {
3448         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3449                                                  SourceLocation(), nullptr,
3450                                                  ParamType, /*TInfo=*/nullptr,
3451                                                  SC_None, nullptr);
3452         Param->setScopeInfo(0, Params.size());
3453         Param->setImplicit();
3454         Params.push_back(Param);
3455       }
3456 
3457       New->setParams(Params);
3458     }
3459 
3460     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3461   }
3462 
3463   // GNU C permits a K&R definition to follow a prototype declaration
3464   // if the declared types of the parameters in the K&R definition
3465   // match the types in the prototype declaration, even when the
3466   // promoted types of the parameters from the K&R definition differ
3467   // from the types in the prototype. GCC then keeps the types from
3468   // the prototype.
3469   //
3470   // If a variadic prototype is followed by a non-variadic K&R definition,
3471   // the K&R definition becomes variadic.  This is sort of an edge case, but
3472   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3473   // C99 6.9.1p8.
3474   if (!getLangOpts().CPlusPlus &&
3475       Old->hasPrototype() && !New->hasPrototype() &&
3476       New->getType()->getAs<FunctionProtoType>() &&
3477       Old->getNumParams() == New->getNumParams()) {
3478     SmallVector<QualType, 16> ArgTypes;
3479     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3480     const FunctionProtoType *OldProto
3481       = Old->getType()->getAs<FunctionProtoType>();
3482     const FunctionProtoType *NewProto
3483       = New->getType()->getAs<FunctionProtoType>();
3484 
3485     // Determine whether this is the GNU C extension.
3486     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3487                                                NewProto->getReturnType());
3488     bool LooseCompatible = !MergedReturn.isNull();
3489     for (unsigned Idx = 0, End = Old->getNumParams();
3490          LooseCompatible && Idx != End; ++Idx) {
3491       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3492       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3493       if (Context.typesAreCompatible(OldParm->getType(),
3494                                      NewProto->getParamType(Idx))) {
3495         ArgTypes.push_back(NewParm->getType());
3496       } else if (Context.typesAreCompatible(OldParm->getType(),
3497                                             NewParm->getType(),
3498                                             /*CompareUnqualified=*/true)) {
3499         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3500                                            NewProto->getParamType(Idx) };
3501         Warnings.push_back(Warn);
3502         ArgTypes.push_back(NewParm->getType());
3503       } else
3504         LooseCompatible = false;
3505     }
3506 
3507     if (LooseCompatible) {
3508       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3509         Diag(Warnings[Warn].NewParm->getLocation(),
3510              diag::ext_param_promoted_not_compatible_with_prototype)
3511           << Warnings[Warn].PromotedType
3512           << Warnings[Warn].OldParm->getType();
3513         if (Warnings[Warn].OldParm->getLocation().isValid())
3514           Diag(Warnings[Warn].OldParm->getLocation(),
3515                diag::note_previous_declaration);
3516       }
3517 
3518       if (MergeTypeWithOld)
3519         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3520                                              OldProto->getExtProtoInfo()));
3521       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3522     }
3523 
3524     // Fall through to diagnose conflicting types.
3525   }
3526 
3527   // A function that has already been declared has been redeclared or
3528   // defined with a different type; show an appropriate diagnostic.
3529 
3530   // If the previous declaration was an implicitly-generated builtin
3531   // declaration, then at the very least we should use a specialized note.
3532   unsigned BuiltinID;
3533   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3534     // If it's actually a library-defined builtin function like 'malloc'
3535     // or 'printf', just warn about the incompatible redeclaration.
3536     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3537       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3538       Diag(OldLocation, diag::note_previous_builtin_declaration)
3539         << Old << Old->getType();
3540 
3541       // If this is a global redeclaration, just forget hereafter
3542       // about the "builtin-ness" of the function.
3543       //
3544       // Doing this for local extern declarations is problematic.  If
3545       // the builtin declaration remains visible, a second invalid
3546       // local declaration will produce a hard error; if it doesn't
3547       // remain visible, a single bogus local redeclaration (which is
3548       // actually only a warning) could break all the downstream code.
3549       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3550         New->getIdentifier()->revertBuiltin();
3551 
3552       return false;
3553     }
3554 
3555     PrevDiag = diag::note_previous_builtin_declaration;
3556   }
3557 
3558   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3559   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3560   return true;
3561 }
3562 
3563 /// \brief Completes the merge of two function declarations that are
3564 /// known to be compatible.
3565 ///
3566 /// This routine handles the merging of attributes and other
3567 /// properties of function declarations from the old declaration to
3568 /// the new declaration, once we know that New is in fact a
3569 /// redeclaration of Old.
3570 ///
3571 /// \returns false
3572 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3573                                         Scope *S, bool MergeTypeWithOld) {
3574   // Merge the attributes
3575   mergeDeclAttributes(New, Old);
3576 
3577   // Merge "pure" flag.
3578   if (Old->isPure())
3579     New->setPure();
3580 
3581   // Merge "used" flag.
3582   if (Old->getMostRecentDecl()->isUsed(false))
3583     New->setIsUsed();
3584 
3585   // Merge attributes from the parameters.  These can mismatch with K&R
3586   // declarations.
3587   if (New->getNumParams() == Old->getNumParams())
3588       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3589         ParmVarDecl *NewParam = New->getParamDecl(i);
3590         ParmVarDecl *OldParam = Old->getParamDecl(i);
3591         mergeParamDeclAttributes(NewParam, OldParam, *this);
3592         mergeParamDeclTypes(NewParam, OldParam, *this);
3593       }
3594 
3595   if (getLangOpts().CPlusPlus)
3596     return MergeCXXFunctionDecl(New, Old, S);
3597 
3598   // Merge the function types so the we get the composite types for the return
3599   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3600   // was visible.
3601   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3602   if (!Merged.isNull() && MergeTypeWithOld)
3603     New->setType(Merged);
3604 
3605   return false;
3606 }
3607 
3608 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3609                                 ObjCMethodDecl *oldMethod) {
3610   // Merge the attributes, including deprecated/unavailable
3611   AvailabilityMergeKind MergeKind =
3612     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3613       ? AMK_ProtocolImplementation
3614       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3615                                                        : AMK_Override;
3616 
3617   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3618 
3619   // Merge attributes from the parameters.
3620   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3621                                        oe = oldMethod->param_end();
3622   for (ObjCMethodDecl::param_iterator
3623          ni = newMethod->param_begin(), ne = newMethod->param_end();
3624        ni != ne && oi != oe; ++ni, ++oi)
3625     mergeParamDeclAttributes(*ni, *oi, *this);
3626 }
3627 
3628 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3629   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3630 
3631   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3632          ? diag::err_redefinition_different_type
3633          : diag::err_redeclaration_different_type)
3634     << New->getDeclName() << New->getType() << Old->getType();
3635 
3636   diag::kind PrevDiag;
3637   SourceLocation OldLocation;
3638   std::tie(PrevDiag, OldLocation)
3639     = getNoteDiagForInvalidRedeclaration(Old, New);
3640   S.Diag(OldLocation, PrevDiag);
3641   New->setInvalidDecl();
3642 }
3643 
3644 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3645 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3646 /// emitting diagnostics as appropriate.
3647 ///
3648 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3649 /// to here in AddInitializerToDecl. We can't check them before the initializer
3650 /// is attached.
3651 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3652                              bool MergeTypeWithOld) {
3653   if (New->isInvalidDecl() || Old->isInvalidDecl())
3654     return;
3655 
3656   QualType MergedT;
3657   if (getLangOpts().CPlusPlus) {
3658     if (New->getType()->isUndeducedType()) {
3659       // We don't know what the new type is until the initializer is attached.
3660       return;
3661     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3662       // These could still be something that needs exception specs checked.
3663       return MergeVarDeclExceptionSpecs(New, Old);
3664     }
3665     // C++ [basic.link]p10:
3666     //   [...] the types specified by all declarations referring to a given
3667     //   object or function shall be identical, except that declarations for an
3668     //   array object can specify array types that differ by the presence or
3669     //   absence of a major array bound (8.3.4).
3670     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3671       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3672       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3673 
3674       // We are merging a variable declaration New into Old. If it has an array
3675       // bound, and that bound differs from Old's bound, we should diagnose the
3676       // mismatch.
3677       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3678         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3679              PrevVD = PrevVD->getPreviousDecl()) {
3680           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3681           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3682             continue;
3683 
3684           if (!Context.hasSameType(NewArray, PrevVDTy))
3685             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3686         }
3687       }
3688 
3689       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3690         if (Context.hasSameType(OldArray->getElementType(),
3691                                 NewArray->getElementType()))
3692           MergedT = New->getType();
3693       }
3694       // FIXME: Check visibility. New is hidden but has a complete type. If New
3695       // has no array bound, it should not inherit one from Old, if Old is not
3696       // visible.
3697       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3698         if (Context.hasSameType(OldArray->getElementType(),
3699                                 NewArray->getElementType()))
3700           MergedT = Old->getType();
3701       }
3702     }
3703     else if (New->getType()->isObjCObjectPointerType() &&
3704                Old->getType()->isObjCObjectPointerType()) {
3705       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3706                                               Old->getType());
3707     }
3708   } else {
3709     // C 6.2.7p2:
3710     //   All declarations that refer to the same object or function shall have
3711     //   compatible type.
3712     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3713   }
3714   if (MergedT.isNull()) {
3715     // It's OK if we couldn't merge types if either type is dependent, for a
3716     // block-scope variable. In other cases (static data members of class
3717     // templates, variable templates, ...), we require the types to be
3718     // equivalent.
3719     // FIXME: The C++ standard doesn't say anything about this.
3720     if ((New->getType()->isDependentType() ||
3721          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3722       // If the old type was dependent, we can't merge with it, so the new type
3723       // becomes dependent for now. We'll reproduce the original type when we
3724       // instantiate the TypeSourceInfo for the variable.
3725       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3726         New->setType(Context.DependentTy);
3727       return;
3728     }
3729     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3730   }
3731 
3732   // Don't actually update the type on the new declaration if the old
3733   // declaration was an extern declaration in a different scope.
3734   if (MergeTypeWithOld)
3735     New->setType(MergedT);
3736 }
3737 
3738 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3739                                   LookupResult &Previous) {
3740   // C11 6.2.7p4:
3741   //   For an identifier with internal or external linkage declared
3742   //   in a scope in which a prior declaration of that identifier is
3743   //   visible, if the prior declaration specifies internal or
3744   //   external linkage, the type of the identifier at the later
3745   //   declaration becomes the composite type.
3746   //
3747   // If the variable isn't visible, we do not merge with its type.
3748   if (Previous.isShadowed())
3749     return false;
3750 
3751   if (S.getLangOpts().CPlusPlus) {
3752     // C++11 [dcl.array]p3:
3753     //   If there is a preceding declaration of the entity in the same
3754     //   scope in which the bound was specified, an omitted array bound
3755     //   is taken to be the same as in that earlier declaration.
3756     return NewVD->isPreviousDeclInSameBlockScope() ||
3757            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3758             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3759   } else {
3760     // If the old declaration was function-local, don't merge with its
3761     // type unless we're in the same function.
3762     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3763            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3764   }
3765 }
3766 
3767 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3768 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3769 /// situation, merging decls or emitting diagnostics as appropriate.
3770 ///
3771 /// Tentative definition rules (C99 6.9.2p2) are checked by
3772 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3773 /// definitions here, since the initializer hasn't been attached.
3774 ///
3775 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3776   // If the new decl is already invalid, don't do any other checking.
3777   if (New->isInvalidDecl())
3778     return;
3779 
3780   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3781     return;
3782 
3783   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3784 
3785   // Verify the old decl was also a variable or variable template.
3786   VarDecl *Old = nullptr;
3787   VarTemplateDecl *OldTemplate = nullptr;
3788   if (Previous.isSingleResult()) {
3789     if (NewTemplate) {
3790       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3791       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3792 
3793       if (auto *Shadow =
3794               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3795         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3796           return New->setInvalidDecl();
3797     } else {
3798       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3799 
3800       if (auto *Shadow =
3801               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3802         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3803           return New->setInvalidDecl();
3804     }
3805   }
3806   if (!Old) {
3807     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3808         << New->getDeclName();
3809     notePreviousDefinition(Previous.getRepresentativeDecl(),
3810                            New->getLocation());
3811     return New->setInvalidDecl();
3812   }
3813 
3814   // Ensure the template parameters are compatible.
3815   if (NewTemplate &&
3816       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3817                                       OldTemplate->getTemplateParameters(),
3818                                       /*Complain=*/true, TPL_TemplateMatch))
3819     return New->setInvalidDecl();
3820 
3821   // C++ [class.mem]p1:
3822   //   A member shall not be declared twice in the member-specification [...]
3823   //
3824   // Here, we need only consider static data members.
3825   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3826     Diag(New->getLocation(), diag::err_duplicate_member)
3827       << New->getIdentifier();
3828     Diag(Old->getLocation(), diag::note_previous_declaration);
3829     New->setInvalidDecl();
3830   }
3831 
3832   mergeDeclAttributes(New, Old);
3833   // Warn if an already-declared variable is made a weak_import in a subsequent
3834   // declaration
3835   if (New->hasAttr<WeakImportAttr>() &&
3836       Old->getStorageClass() == SC_None &&
3837       !Old->hasAttr<WeakImportAttr>()) {
3838     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3839     notePreviousDefinition(Old, New->getLocation());
3840     // Remove weak_import attribute on new declaration.
3841     New->dropAttr<WeakImportAttr>();
3842   }
3843 
3844   if (New->hasAttr<InternalLinkageAttr>() &&
3845       !Old->hasAttr<InternalLinkageAttr>()) {
3846     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3847         << New->getDeclName();
3848     notePreviousDefinition(Old, New->getLocation());
3849     New->dropAttr<InternalLinkageAttr>();
3850   }
3851 
3852   // Merge the types.
3853   VarDecl *MostRecent = Old->getMostRecentDecl();
3854   if (MostRecent != Old) {
3855     MergeVarDeclTypes(New, MostRecent,
3856                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3857     if (New->isInvalidDecl())
3858       return;
3859   }
3860 
3861   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3862   if (New->isInvalidDecl())
3863     return;
3864 
3865   diag::kind PrevDiag;
3866   SourceLocation OldLocation;
3867   std::tie(PrevDiag, OldLocation) =
3868       getNoteDiagForInvalidRedeclaration(Old, New);
3869 
3870   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3871   if (New->getStorageClass() == SC_Static &&
3872       !New->isStaticDataMember() &&
3873       Old->hasExternalFormalLinkage()) {
3874     if (getLangOpts().MicrosoftExt) {
3875       Diag(New->getLocation(), diag::ext_static_non_static)
3876           << New->getDeclName();
3877       Diag(OldLocation, PrevDiag);
3878     } else {
3879       Diag(New->getLocation(), diag::err_static_non_static)
3880           << New->getDeclName();
3881       Diag(OldLocation, PrevDiag);
3882       return New->setInvalidDecl();
3883     }
3884   }
3885   // C99 6.2.2p4:
3886   //   For an identifier declared with the storage-class specifier
3887   //   extern in a scope in which a prior declaration of that
3888   //   identifier is visible,23) if the prior declaration specifies
3889   //   internal or external linkage, the linkage of the identifier at
3890   //   the later declaration is the same as the linkage specified at
3891   //   the prior declaration. If no prior declaration is visible, or
3892   //   if the prior declaration specifies no linkage, then the
3893   //   identifier has external linkage.
3894   if (New->hasExternalStorage() && Old->hasLinkage())
3895     /* Okay */;
3896   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3897            !New->isStaticDataMember() &&
3898            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3899     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3900     Diag(OldLocation, PrevDiag);
3901     return New->setInvalidDecl();
3902   }
3903 
3904   // Check if extern is followed by non-extern and vice-versa.
3905   if (New->hasExternalStorage() &&
3906       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3907     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3908     Diag(OldLocation, PrevDiag);
3909     return New->setInvalidDecl();
3910   }
3911   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3912       !New->hasExternalStorage()) {
3913     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3914     Diag(OldLocation, PrevDiag);
3915     return New->setInvalidDecl();
3916   }
3917 
3918   if (CheckRedeclarationModuleOwnership(New, Old))
3919     return;
3920 
3921   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3922 
3923   // FIXME: The test for external storage here seems wrong? We still
3924   // need to check for mismatches.
3925   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3926       // Don't complain about out-of-line definitions of static members.
3927       !(Old->getLexicalDeclContext()->isRecord() &&
3928         !New->getLexicalDeclContext()->isRecord())) {
3929     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3930     Diag(OldLocation, PrevDiag);
3931     return New->setInvalidDecl();
3932   }
3933 
3934   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3935     if (VarDecl *Def = Old->getDefinition()) {
3936       // C++1z [dcl.fcn.spec]p4:
3937       //   If the definition of a variable appears in a translation unit before
3938       //   its first declaration as inline, the program is ill-formed.
3939       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3940       Diag(Def->getLocation(), diag::note_previous_definition);
3941     }
3942   }
3943 
3944   // If this redeclaration makes the variable inline, we may need to add it to
3945   // UndefinedButUsed.
3946   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3947       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3948     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3949                                            SourceLocation()));
3950 
3951   if (New->getTLSKind() != Old->getTLSKind()) {
3952     if (!Old->getTLSKind()) {
3953       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3954       Diag(OldLocation, PrevDiag);
3955     } else if (!New->getTLSKind()) {
3956       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3957       Diag(OldLocation, PrevDiag);
3958     } else {
3959       // Do not allow redeclaration to change the variable between requiring
3960       // static and dynamic initialization.
3961       // FIXME: GCC allows this, but uses the TLS keyword on the first
3962       // declaration to determine the kind. Do we need to be compatible here?
3963       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3964         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3965       Diag(OldLocation, PrevDiag);
3966     }
3967   }
3968 
3969   // C++ doesn't have tentative definitions, so go right ahead and check here.
3970   if (getLangOpts().CPlusPlus &&
3971       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3972     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3973         Old->getCanonicalDecl()->isConstexpr()) {
3974       // This definition won't be a definition any more once it's been merged.
3975       Diag(New->getLocation(),
3976            diag::warn_deprecated_redundant_constexpr_static_def);
3977     } else if (VarDecl *Def = Old->getDefinition()) {
3978       if (checkVarDeclRedefinition(Def, New))
3979         return;
3980     }
3981   }
3982 
3983   if (haveIncompatibleLanguageLinkages(Old, New)) {
3984     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3985     Diag(OldLocation, PrevDiag);
3986     New->setInvalidDecl();
3987     return;
3988   }
3989 
3990   // Merge "used" flag.
3991   if (Old->getMostRecentDecl()->isUsed(false))
3992     New->setIsUsed();
3993 
3994   // Keep a chain of previous declarations.
3995   New->setPreviousDecl(Old);
3996   if (NewTemplate)
3997     NewTemplate->setPreviousDecl(OldTemplate);
3998   adjustDeclContextForDeclaratorDecl(New, Old);
3999 
4000   // Inherit access appropriately.
4001   New->setAccess(Old->getAccess());
4002   if (NewTemplate)
4003     NewTemplate->setAccess(New->getAccess());
4004 
4005   if (Old->isInline())
4006     New->setImplicitlyInline();
4007 }
4008 
4009 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4010   SourceManager &SrcMgr = getSourceManager();
4011   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4012   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4013   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4014   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4015   auto &HSI = PP.getHeaderSearchInfo();
4016   StringRef HdrFilename =
4017       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4018 
4019   auto noteFromModuleOrInclude = [&](Module *Mod,
4020                                      SourceLocation IncLoc) -> bool {
4021     // Redefinition errors with modules are common with non modular mapped
4022     // headers, example: a non-modular header H in module A that also gets
4023     // included directly in a TU. Pointing twice to the same header/definition
4024     // is confusing, try to get better diagnostics when modules is on.
4025     if (IncLoc.isValid()) {
4026       if (Mod) {
4027         Diag(IncLoc, diag::note_redefinition_modules_same_file)
4028             << HdrFilename.str() << Mod->getFullModuleName();
4029         if (!Mod->DefinitionLoc.isInvalid())
4030           Diag(Mod->DefinitionLoc, diag::note_defined_here)
4031               << Mod->getFullModuleName();
4032       } else {
4033         Diag(IncLoc, diag::note_redefinition_include_same_file)
4034             << HdrFilename.str();
4035       }
4036       return true;
4037     }
4038 
4039     return false;
4040   };
4041 
4042   // Is it the same file and same offset? Provide more information on why
4043   // this leads to a redefinition error.
4044   bool EmittedDiag = false;
4045   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4046     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4047     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4048     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4049     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4050 
4051     // If the header has no guards, emit a note suggesting one.
4052     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4053       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4054 
4055     if (EmittedDiag)
4056       return;
4057   }
4058 
4059   // Redefinition coming from different files or couldn't do better above.
4060   Diag(Old->getLocation(), diag::note_previous_definition);
4061 }
4062 
4063 /// We've just determined that \p Old and \p New both appear to be definitions
4064 /// of the same variable. Either diagnose or fix the problem.
4065 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4066   if (!hasVisibleDefinition(Old) &&
4067       (New->getFormalLinkage() == InternalLinkage ||
4068        New->isInline() ||
4069        New->getDescribedVarTemplate() ||
4070        New->getNumTemplateParameterLists() ||
4071        New->getDeclContext()->isDependentContext())) {
4072     // The previous definition is hidden, and multiple definitions are
4073     // permitted (in separate TUs). Demote this to a declaration.
4074     New->demoteThisDefinitionToDeclaration();
4075 
4076     // Make the canonical definition visible.
4077     if (auto *OldTD = Old->getDescribedVarTemplate())
4078       makeMergedDefinitionVisible(OldTD);
4079     makeMergedDefinitionVisible(Old);
4080     return false;
4081   } else {
4082     Diag(New->getLocation(), diag::err_redefinition) << New;
4083     notePreviousDefinition(Old, New->getLocation());
4084     New->setInvalidDecl();
4085     return true;
4086   }
4087 }
4088 
4089 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4090 /// no declarator (e.g. "struct foo;") is parsed.
4091 Decl *
4092 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4093                                  RecordDecl *&AnonRecord) {
4094   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4095                                     AnonRecord);
4096 }
4097 
4098 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4099 // disambiguate entities defined in different scopes.
4100 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4101 // compatibility.
4102 // We will pick our mangling number depending on which version of MSVC is being
4103 // targeted.
4104 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4105   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4106              ? S->getMSCurManglingNumber()
4107              : S->getMSLastManglingNumber();
4108 }
4109 
4110 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4111   if (!Context.getLangOpts().CPlusPlus)
4112     return;
4113 
4114   if (isa<CXXRecordDecl>(Tag->getParent())) {
4115     // If this tag is the direct child of a class, number it if
4116     // it is anonymous.
4117     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4118       return;
4119     MangleNumberingContext &MCtx =
4120         Context.getManglingNumberContext(Tag->getParent());
4121     Context.setManglingNumber(
4122         Tag, MCtx.getManglingNumber(
4123                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4124     return;
4125   }
4126 
4127   // If this tag isn't a direct child of a class, number it if it is local.
4128   Decl *ManglingContextDecl;
4129   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4130           Tag->getDeclContext(), ManglingContextDecl)) {
4131     Context.setManglingNumber(
4132         Tag, MCtx->getManglingNumber(
4133                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4134   }
4135 }
4136 
4137 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4138                                         TypedefNameDecl *NewTD) {
4139   if (TagFromDeclSpec->isInvalidDecl())
4140     return;
4141 
4142   // Do nothing if the tag already has a name for linkage purposes.
4143   if (TagFromDeclSpec->hasNameForLinkage())
4144     return;
4145 
4146   // A well-formed anonymous tag must always be a TUK_Definition.
4147   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4148 
4149   // The type must match the tag exactly;  no qualifiers allowed.
4150   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4151                            Context.getTagDeclType(TagFromDeclSpec))) {
4152     if (getLangOpts().CPlusPlus)
4153       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4154     return;
4155   }
4156 
4157   // If we've already computed linkage for the anonymous tag, then
4158   // adding a typedef name for the anonymous decl can change that
4159   // linkage, which might be a serious problem.  Diagnose this as
4160   // unsupported and ignore the typedef name.  TODO: we should
4161   // pursue this as a language defect and establish a formal rule
4162   // for how to handle it.
4163   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4164     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4165 
4166     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4167     tagLoc = getLocForEndOfToken(tagLoc);
4168 
4169     llvm::SmallString<40> textToInsert;
4170     textToInsert += ' ';
4171     textToInsert += NewTD->getIdentifier()->getName();
4172     Diag(tagLoc, diag::note_typedef_changes_linkage)
4173         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4174     return;
4175   }
4176 
4177   // Otherwise, set this is the anon-decl typedef for the tag.
4178   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4179 }
4180 
4181 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4182   switch (T) {
4183   case DeclSpec::TST_class:
4184     return 0;
4185   case DeclSpec::TST_struct:
4186     return 1;
4187   case DeclSpec::TST_interface:
4188     return 2;
4189   case DeclSpec::TST_union:
4190     return 3;
4191   case DeclSpec::TST_enum:
4192     return 4;
4193   default:
4194     llvm_unreachable("unexpected type specifier");
4195   }
4196 }
4197 
4198 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4199 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4200 /// parameters to cope with template friend declarations.
4201 Decl *
4202 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4203                                  MultiTemplateParamsArg TemplateParams,
4204                                  bool IsExplicitInstantiation,
4205                                  RecordDecl *&AnonRecord) {
4206   Decl *TagD = nullptr;
4207   TagDecl *Tag = nullptr;
4208   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4209       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4210       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4211       DS.getTypeSpecType() == DeclSpec::TST_union ||
4212       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4213     TagD = DS.getRepAsDecl();
4214 
4215     if (!TagD) // We probably had an error
4216       return nullptr;
4217 
4218     // Note that the above type specs guarantee that the
4219     // type rep is a Decl, whereas in many of the others
4220     // it's a Type.
4221     if (isa<TagDecl>(TagD))
4222       Tag = cast<TagDecl>(TagD);
4223     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4224       Tag = CTD->getTemplatedDecl();
4225   }
4226 
4227   if (Tag) {
4228     handleTagNumbering(Tag, S);
4229     Tag->setFreeStanding();
4230     if (Tag->isInvalidDecl())
4231       return Tag;
4232   }
4233 
4234   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4235     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4236     // or incomplete types shall not be restrict-qualified."
4237     if (TypeQuals & DeclSpec::TQ_restrict)
4238       Diag(DS.getRestrictSpecLoc(),
4239            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4240            << DS.getSourceRange();
4241   }
4242 
4243   if (DS.isInlineSpecified())
4244     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4245         << getLangOpts().CPlusPlus17;
4246 
4247   if (DS.isConstexprSpecified()) {
4248     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4249     // and definitions of functions and variables.
4250     if (Tag)
4251       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4252           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4253     else
4254       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4255     // Don't emit warnings after this error.
4256     return TagD;
4257   }
4258 
4259   DiagnoseFunctionSpecifiers(DS);
4260 
4261   if (DS.isFriendSpecified()) {
4262     // If we're dealing with a decl but not a TagDecl, assume that
4263     // whatever routines created it handled the friendship aspect.
4264     if (TagD && !Tag)
4265       return nullptr;
4266     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4267   }
4268 
4269   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4270   bool IsExplicitSpecialization =
4271     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4272   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4273       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4274       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4275     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4276     // nested-name-specifier unless it is an explicit instantiation
4277     // or an explicit specialization.
4278     //
4279     // FIXME: We allow class template partial specializations here too, per the
4280     // obvious intent of DR1819.
4281     //
4282     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4283     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4284         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4285     return nullptr;
4286   }
4287 
4288   // Track whether this decl-specifier declares anything.
4289   bool DeclaresAnything = true;
4290 
4291   // Handle anonymous struct definitions.
4292   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4293     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4294         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4295       if (getLangOpts().CPlusPlus ||
4296           Record->getDeclContext()->isRecord()) {
4297         // If CurContext is a DeclContext that can contain statements,
4298         // RecursiveASTVisitor won't visit the decls that
4299         // BuildAnonymousStructOrUnion() will put into CurContext.
4300         // Also store them here so that they can be part of the
4301         // DeclStmt that gets created in this case.
4302         // FIXME: Also return the IndirectFieldDecls created by
4303         // BuildAnonymousStructOr union, for the same reason?
4304         if (CurContext->isFunctionOrMethod())
4305           AnonRecord = Record;
4306         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4307                                            Context.getPrintingPolicy());
4308       }
4309 
4310       DeclaresAnything = false;
4311     }
4312   }
4313 
4314   // C11 6.7.2.1p2:
4315   //   A struct-declaration that does not declare an anonymous structure or
4316   //   anonymous union shall contain a struct-declarator-list.
4317   //
4318   // This rule also existed in C89 and C99; the grammar for struct-declaration
4319   // did not permit a struct-declaration without a struct-declarator-list.
4320   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4321       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4322     // Check for Microsoft C extension: anonymous struct/union member.
4323     // Handle 2 kinds of anonymous struct/union:
4324     //   struct STRUCT;
4325     //   union UNION;
4326     // and
4327     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4328     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4329     if ((Tag && Tag->getDeclName()) ||
4330         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4331       RecordDecl *Record = nullptr;
4332       if (Tag)
4333         Record = dyn_cast<RecordDecl>(Tag);
4334       else if (const RecordType *RT =
4335                    DS.getRepAsType().get()->getAsStructureType())
4336         Record = RT->getDecl();
4337       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4338         Record = UT->getDecl();
4339 
4340       if (Record && getLangOpts().MicrosoftExt) {
4341         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4342           << Record->isUnion() << DS.getSourceRange();
4343         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4344       }
4345 
4346       DeclaresAnything = false;
4347     }
4348   }
4349 
4350   // Skip all the checks below if we have a type error.
4351   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4352       (TagD && TagD->isInvalidDecl()))
4353     return TagD;
4354 
4355   if (getLangOpts().CPlusPlus &&
4356       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4357     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4358       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4359           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4360         DeclaresAnything = false;
4361 
4362   if (!DS.isMissingDeclaratorOk()) {
4363     // Customize diagnostic for a typedef missing a name.
4364     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4365       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4366         << DS.getSourceRange();
4367     else
4368       DeclaresAnything = false;
4369   }
4370 
4371   if (DS.isModulePrivateSpecified() &&
4372       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4373     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4374       << Tag->getTagKind()
4375       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4376 
4377   ActOnDocumentableDecl(TagD);
4378 
4379   // C 6.7/2:
4380   //   A declaration [...] shall declare at least a declarator [...], a tag,
4381   //   or the members of an enumeration.
4382   // C++ [dcl.dcl]p3:
4383   //   [If there are no declarators], and except for the declaration of an
4384   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4385   //   names into the program, or shall redeclare a name introduced by a
4386   //   previous declaration.
4387   if (!DeclaresAnything) {
4388     // In C, we allow this as a (popular) extension / bug. Don't bother
4389     // producing further diagnostics for redundant qualifiers after this.
4390     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4391     return TagD;
4392   }
4393 
4394   // C++ [dcl.stc]p1:
4395   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4396   //   init-declarator-list of the declaration shall not be empty.
4397   // C++ [dcl.fct.spec]p1:
4398   //   If a cv-qualifier appears in a decl-specifier-seq, the
4399   //   init-declarator-list of the declaration shall not be empty.
4400   //
4401   // Spurious qualifiers here appear to be valid in C.
4402   unsigned DiagID = diag::warn_standalone_specifier;
4403   if (getLangOpts().CPlusPlus)
4404     DiagID = diag::ext_standalone_specifier;
4405 
4406   // Note that a linkage-specification sets a storage class, but
4407   // 'extern "C" struct foo;' is actually valid and not theoretically
4408   // useless.
4409   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4410     if (SCS == DeclSpec::SCS_mutable)
4411       // Since mutable is not a viable storage class specifier in C, there is
4412       // no reason to treat it as an extension. Instead, diagnose as an error.
4413       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4414     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4415       Diag(DS.getStorageClassSpecLoc(), DiagID)
4416         << DeclSpec::getSpecifierName(SCS);
4417   }
4418 
4419   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4420     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4421       << DeclSpec::getSpecifierName(TSCS);
4422   if (DS.getTypeQualifiers()) {
4423     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4424       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4425     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4426       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4427     // Restrict is covered above.
4428     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4429       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4430     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4431       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4432   }
4433 
4434   // Warn about ignored type attributes, for example:
4435   // __attribute__((aligned)) struct A;
4436   // Attributes should be placed after tag to apply to type declaration.
4437   if (!DS.getAttributes().empty()) {
4438     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4439     if (TypeSpecType == DeclSpec::TST_class ||
4440         TypeSpecType == DeclSpec::TST_struct ||
4441         TypeSpecType == DeclSpec::TST_interface ||
4442         TypeSpecType == DeclSpec::TST_union ||
4443         TypeSpecType == DeclSpec::TST_enum) {
4444       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4445            attrs = attrs->getNext())
4446         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4447             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4448     }
4449   }
4450 
4451   return TagD;
4452 }
4453 
4454 /// We are trying to inject an anonymous member into the given scope;
4455 /// check if there's an existing declaration that can't be overloaded.
4456 ///
4457 /// \return true if this is a forbidden redeclaration
4458 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4459                                          Scope *S,
4460                                          DeclContext *Owner,
4461                                          DeclarationName Name,
4462                                          SourceLocation NameLoc,
4463                                          bool IsUnion) {
4464   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4465                  Sema::ForVisibleRedeclaration);
4466   if (!SemaRef.LookupName(R, S)) return false;
4467 
4468   // Pick a representative declaration.
4469   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4470   assert(PrevDecl && "Expected a non-null Decl");
4471 
4472   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4473     return false;
4474 
4475   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4476     << IsUnion << Name;
4477   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4478 
4479   return true;
4480 }
4481 
4482 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4483 /// anonymous struct or union AnonRecord into the owning context Owner
4484 /// and scope S. This routine will be invoked just after we realize
4485 /// that an unnamed union or struct is actually an anonymous union or
4486 /// struct, e.g.,
4487 ///
4488 /// @code
4489 /// union {
4490 ///   int i;
4491 ///   float f;
4492 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4493 ///    // f into the surrounding scope.x
4494 /// @endcode
4495 ///
4496 /// This routine is recursive, injecting the names of nested anonymous
4497 /// structs/unions into the owning context and scope as well.
4498 static bool
4499 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4500                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4501                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4502   bool Invalid = false;
4503 
4504   // Look every FieldDecl and IndirectFieldDecl with a name.
4505   for (auto *D : AnonRecord->decls()) {
4506     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4507         cast<NamedDecl>(D)->getDeclName()) {
4508       ValueDecl *VD = cast<ValueDecl>(D);
4509       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4510                                        VD->getLocation(),
4511                                        AnonRecord->isUnion())) {
4512         // C++ [class.union]p2:
4513         //   The names of the members of an anonymous union shall be
4514         //   distinct from the names of any other entity in the
4515         //   scope in which the anonymous union is declared.
4516         Invalid = true;
4517       } else {
4518         // C++ [class.union]p2:
4519         //   For the purpose of name lookup, after the anonymous union
4520         //   definition, the members of the anonymous union are
4521         //   considered to have been defined in the scope in which the
4522         //   anonymous union is declared.
4523         unsigned OldChainingSize = Chaining.size();
4524         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4525           Chaining.append(IF->chain_begin(), IF->chain_end());
4526         else
4527           Chaining.push_back(VD);
4528 
4529         assert(Chaining.size() >= 2);
4530         NamedDecl **NamedChain =
4531           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4532         for (unsigned i = 0; i < Chaining.size(); i++)
4533           NamedChain[i] = Chaining[i];
4534 
4535         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4536             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4537             VD->getType(), {NamedChain, Chaining.size()});
4538 
4539         for (const auto *Attr : VD->attrs())
4540           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4541 
4542         IndirectField->setAccess(AS);
4543         IndirectField->setImplicit();
4544         SemaRef.PushOnScopeChains(IndirectField, S);
4545 
4546         // That includes picking up the appropriate access specifier.
4547         if (AS != AS_none) IndirectField->setAccess(AS);
4548 
4549         Chaining.resize(OldChainingSize);
4550       }
4551     }
4552   }
4553 
4554   return Invalid;
4555 }
4556 
4557 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4558 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4559 /// illegal input values are mapped to SC_None.
4560 static StorageClass
4561 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4562   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4563   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4564          "Parser allowed 'typedef' as storage class VarDecl.");
4565   switch (StorageClassSpec) {
4566   case DeclSpec::SCS_unspecified:    return SC_None;
4567   case DeclSpec::SCS_extern:
4568     if (DS.isExternInLinkageSpec())
4569       return SC_None;
4570     return SC_Extern;
4571   case DeclSpec::SCS_static:         return SC_Static;
4572   case DeclSpec::SCS_auto:           return SC_Auto;
4573   case DeclSpec::SCS_register:       return SC_Register;
4574   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4575     // Illegal SCSs map to None: error reporting is up to the caller.
4576   case DeclSpec::SCS_mutable:        // Fall through.
4577   case DeclSpec::SCS_typedef:        return SC_None;
4578   }
4579   llvm_unreachable("unknown storage class specifier");
4580 }
4581 
4582 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4583   assert(Record->hasInClassInitializer());
4584 
4585   for (const auto *I : Record->decls()) {
4586     const auto *FD = dyn_cast<FieldDecl>(I);
4587     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4588       FD = IFD->getAnonField();
4589     if (FD && FD->hasInClassInitializer())
4590       return FD->getLocation();
4591   }
4592 
4593   llvm_unreachable("couldn't find in-class initializer");
4594 }
4595 
4596 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4597                                       SourceLocation DefaultInitLoc) {
4598   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4599     return;
4600 
4601   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4602   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4603 }
4604 
4605 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4606                                       CXXRecordDecl *AnonUnion) {
4607   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4608     return;
4609 
4610   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4611 }
4612 
4613 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4614 /// anonymous structure or union. Anonymous unions are a C++ feature
4615 /// (C++ [class.union]) and a C11 feature; anonymous structures
4616 /// are a C11 feature and GNU C++ extension.
4617 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4618                                         AccessSpecifier AS,
4619                                         RecordDecl *Record,
4620                                         const PrintingPolicy &Policy) {
4621   DeclContext *Owner = Record->getDeclContext();
4622 
4623   // Diagnose whether this anonymous struct/union is an extension.
4624   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4625     Diag(Record->getLocation(), diag::ext_anonymous_union);
4626   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4627     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4628   else if (!Record->isUnion() && !getLangOpts().C11)
4629     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4630 
4631   // C and C++ require different kinds of checks for anonymous
4632   // structs/unions.
4633   bool Invalid = false;
4634   if (getLangOpts().CPlusPlus) {
4635     const char *PrevSpec = nullptr;
4636     unsigned DiagID;
4637     if (Record->isUnion()) {
4638       // C++ [class.union]p6:
4639       //   Anonymous unions declared in a named namespace or in the
4640       //   global namespace shall be declared static.
4641       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4642           (isa<TranslationUnitDecl>(Owner) ||
4643            (isa<NamespaceDecl>(Owner) &&
4644             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4645         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4646           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4647 
4648         // Recover by adding 'static'.
4649         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4650                                PrevSpec, DiagID, Policy);
4651       }
4652       // C++ [class.union]p6:
4653       //   A storage class is not allowed in a declaration of an
4654       //   anonymous union in a class scope.
4655       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4656                isa<RecordDecl>(Owner)) {
4657         Diag(DS.getStorageClassSpecLoc(),
4658              diag::err_anonymous_union_with_storage_spec)
4659           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4660 
4661         // Recover by removing the storage specifier.
4662         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4663                                SourceLocation(),
4664                                PrevSpec, DiagID, Context.getPrintingPolicy());
4665       }
4666     }
4667 
4668     // Ignore const/volatile/restrict qualifiers.
4669     if (DS.getTypeQualifiers()) {
4670       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4671         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4672           << Record->isUnion() << "const"
4673           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4674       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4675         Diag(DS.getVolatileSpecLoc(),
4676              diag::ext_anonymous_struct_union_qualified)
4677           << Record->isUnion() << "volatile"
4678           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4679       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4680         Diag(DS.getRestrictSpecLoc(),
4681              diag::ext_anonymous_struct_union_qualified)
4682           << Record->isUnion() << "restrict"
4683           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4684       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4685         Diag(DS.getAtomicSpecLoc(),
4686              diag::ext_anonymous_struct_union_qualified)
4687           << Record->isUnion() << "_Atomic"
4688           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4689       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4690         Diag(DS.getUnalignedSpecLoc(),
4691              diag::ext_anonymous_struct_union_qualified)
4692           << Record->isUnion() << "__unaligned"
4693           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4694 
4695       DS.ClearTypeQualifiers();
4696     }
4697 
4698     // C++ [class.union]p2:
4699     //   The member-specification of an anonymous union shall only
4700     //   define non-static data members. [Note: nested types and
4701     //   functions cannot be declared within an anonymous union. ]
4702     for (auto *Mem : Record->decls()) {
4703       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4704         // C++ [class.union]p3:
4705         //   An anonymous union shall not have private or protected
4706         //   members (clause 11).
4707         assert(FD->getAccess() != AS_none);
4708         if (FD->getAccess() != AS_public) {
4709           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4710             << Record->isUnion() << (FD->getAccess() == AS_protected);
4711           Invalid = true;
4712         }
4713 
4714         // C++ [class.union]p1
4715         //   An object of a class with a non-trivial constructor, a non-trivial
4716         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4717         //   assignment operator cannot be a member of a union, nor can an
4718         //   array of such objects.
4719         if (CheckNontrivialField(FD))
4720           Invalid = true;
4721       } else if (Mem->isImplicit()) {
4722         // Any implicit members are fine.
4723       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4724         // This is a type that showed up in an
4725         // elaborated-type-specifier inside the anonymous struct or
4726         // union, but which actually declares a type outside of the
4727         // anonymous struct or union. It's okay.
4728       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4729         if (!MemRecord->isAnonymousStructOrUnion() &&
4730             MemRecord->getDeclName()) {
4731           // Visual C++ allows type definition in anonymous struct or union.
4732           if (getLangOpts().MicrosoftExt)
4733             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4734               << Record->isUnion();
4735           else {
4736             // This is a nested type declaration.
4737             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4738               << Record->isUnion();
4739             Invalid = true;
4740           }
4741         } else {
4742           // This is an anonymous type definition within another anonymous type.
4743           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4744           // not part of standard C++.
4745           Diag(MemRecord->getLocation(),
4746                diag::ext_anonymous_record_with_anonymous_type)
4747             << Record->isUnion();
4748         }
4749       } else if (isa<AccessSpecDecl>(Mem)) {
4750         // Any access specifier is fine.
4751       } else if (isa<StaticAssertDecl>(Mem)) {
4752         // In C++1z, static_assert declarations are also fine.
4753       } else {
4754         // We have something that isn't a non-static data
4755         // member. Complain about it.
4756         unsigned DK = diag::err_anonymous_record_bad_member;
4757         if (isa<TypeDecl>(Mem))
4758           DK = diag::err_anonymous_record_with_type;
4759         else if (isa<FunctionDecl>(Mem))
4760           DK = diag::err_anonymous_record_with_function;
4761         else if (isa<VarDecl>(Mem))
4762           DK = diag::err_anonymous_record_with_static;
4763 
4764         // Visual C++ allows type definition in anonymous struct or union.
4765         if (getLangOpts().MicrosoftExt &&
4766             DK == diag::err_anonymous_record_with_type)
4767           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4768             << Record->isUnion();
4769         else {
4770           Diag(Mem->getLocation(), DK) << Record->isUnion();
4771           Invalid = true;
4772         }
4773       }
4774     }
4775 
4776     // C++11 [class.union]p8 (DR1460):
4777     //   At most one variant member of a union may have a
4778     //   brace-or-equal-initializer.
4779     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4780         Owner->isRecord())
4781       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4782                                 cast<CXXRecordDecl>(Record));
4783   }
4784 
4785   if (!Record->isUnion() && !Owner->isRecord()) {
4786     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4787       << getLangOpts().CPlusPlus;
4788     Invalid = true;
4789   }
4790 
4791   // Mock up a declarator.
4792   Declarator Dc(DS, DeclaratorContext::MemberContext);
4793   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4794   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4795 
4796   // Create a declaration for this anonymous struct/union.
4797   NamedDecl *Anon = nullptr;
4798   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4799     Anon = FieldDecl::Create(Context, OwningClass,
4800                              DS.getLocStart(),
4801                              Record->getLocation(),
4802                              /*IdentifierInfo=*/nullptr,
4803                              Context.getTypeDeclType(Record),
4804                              TInfo,
4805                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4806                              /*InitStyle=*/ICIS_NoInit);
4807     Anon->setAccess(AS);
4808     if (getLangOpts().CPlusPlus)
4809       FieldCollector->Add(cast<FieldDecl>(Anon));
4810   } else {
4811     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4812     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4813     if (SCSpec == DeclSpec::SCS_mutable) {
4814       // mutable can only appear on non-static class members, so it's always
4815       // an error here
4816       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4817       Invalid = true;
4818       SC = SC_None;
4819     }
4820 
4821     Anon = VarDecl::Create(Context, Owner,
4822                            DS.getLocStart(),
4823                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4824                            Context.getTypeDeclType(Record),
4825                            TInfo, SC);
4826 
4827     // Default-initialize the implicit variable. This initialization will be
4828     // trivial in almost all cases, except if a union member has an in-class
4829     // initializer:
4830     //   union { int n = 0; };
4831     ActOnUninitializedDecl(Anon);
4832   }
4833   Anon->setImplicit();
4834 
4835   // Mark this as an anonymous struct/union type.
4836   Record->setAnonymousStructOrUnion(true);
4837 
4838   // Add the anonymous struct/union object to the current
4839   // context. We'll be referencing this object when we refer to one of
4840   // its members.
4841   Owner->addDecl(Anon);
4842 
4843   // Inject the members of the anonymous struct/union into the owning
4844   // context and into the identifier resolver chain for name lookup
4845   // purposes.
4846   SmallVector<NamedDecl*, 2> Chain;
4847   Chain.push_back(Anon);
4848 
4849   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4850     Invalid = true;
4851 
4852   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4853     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4854       Decl *ManglingContextDecl;
4855       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4856               NewVD->getDeclContext(), ManglingContextDecl)) {
4857         Context.setManglingNumber(
4858             NewVD, MCtx->getManglingNumber(
4859                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4860         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4861       }
4862     }
4863   }
4864 
4865   if (Invalid)
4866     Anon->setInvalidDecl();
4867 
4868   return Anon;
4869 }
4870 
4871 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4872 /// Microsoft C anonymous structure.
4873 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4874 /// Example:
4875 ///
4876 /// struct A { int a; };
4877 /// struct B { struct A; int b; };
4878 ///
4879 /// void foo() {
4880 ///   B var;
4881 ///   var.a = 3;
4882 /// }
4883 ///
4884 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4885                                            RecordDecl *Record) {
4886   assert(Record && "expected a record!");
4887 
4888   // Mock up a declarator.
4889   Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4890   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4891   assert(TInfo && "couldn't build declarator info for anonymous struct");
4892 
4893   auto *ParentDecl = cast<RecordDecl>(CurContext);
4894   QualType RecTy = Context.getTypeDeclType(Record);
4895 
4896   // Create a declaration for this anonymous struct.
4897   NamedDecl *Anon = FieldDecl::Create(Context,
4898                              ParentDecl,
4899                              DS.getLocStart(),
4900                              DS.getLocStart(),
4901                              /*IdentifierInfo=*/nullptr,
4902                              RecTy,
4903                              TInfo,
4904                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4905                              /*InitStyle=*/ICIS_NoInit);
4906   Anon->setImplicit();
4907 
4908   // Add the anonymous struct object to the current context.
4909   CurContext->addDecl(Anon);
4910 
4911   // Inject the members of the anonymous struct into the current
4912   // context and into the identifier resolver chain for name lookup
4913   // purposes.
4914   SmallVector<NamedDecl*, 2> Chain;
4915   Chain.push_back(Anon);
4916 
4917   RecordDecl *RecordDef = Record->getDefinition();
4918   if (RequireCompleteType(Anon->getLocation(), RecTy,
4919                           diag::err_field_incomplete) ||
4920       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4921                                           AS_none, Chain)) {
4922     Anon->setInvalidDecl();
4923     ParentDecl->setInvalidDecl();
4924   }
4925 
4926   return Anon;
4927 }
4928 
4929 /// GetNameForDeclarator - Determine the full declaration name for the
4930 /// given Declarator.
4931 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4932   return GetNameFromUnqualifiedId(D.getName());
4933 }
4934 
4935 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4936 DeclarationNameInfo
4937 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4938   DeclarationNameInfo NameInfo;
4939   NameInfo.setLoc(Name.StartLocation);
4940 
4941   switch (Name.getKind()) {
4942 
4943   case UnqualifiedIdKind::IK_ImplicitSelfParam:
4944   case UnqualifiedIdKind::IK_Identifier:
4945     NameInfo.setName(Name.Identifier);
4946     NameInfo.setLoc(Name.StartLocation);
4947     return NameInfo;
4948 
4949   case UnqualifiedIdKind::IK_DeductionGuideName: {
4950     // C++ [temp.deduct.guide]p3:
4951     //   The simple-template-id shall name a class template specialization.
4952     //   The template-name shall be the same identifier as the template-name
4953     //   of the simple-template-id.
4954     // These together intend to imply that the template-name shall name a
4955     // class template.
4956     // FIXME: template<typename T> struct X {};
4957     //        template<typename T> using Y = X<T>;
4958     //        Y(int) -> Y<int>;
4959     //   satisfies these rules but does not name a class template.
4960     TemplateName TN = Name.TemplateName.get().get();
4961     auto *Template = TN.getAsTemplateDecl();
4962     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4963       Diag(Name.StartLocation,
4964            diag::err_deduction_guide_name_not_class_template)
4965         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4966       if (Template)
4967         Diag(Template->getLocation(), diag::note_template_decl_here);
4968       return DeclarationNameInfo();
4969     }
4970 
4971     NameInfo.setName(
4972         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4973     NameInfo.setLoc(Name.StartLocation);
4974     return NameInfo;
4975   }
4976 
4977   case UnqualifiedIdKind::IK_OperatorFunctionId:
4978     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4979                                            Name.OperatorFunctionId.Operator));
4980     NameInfo.setLoc(Name.StartLocation);
4981     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4982       = Name.OperatorFunctionId.SymbolLocations[0];
4983     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4984       = Name.EndLocation.getRawEncoding();
4985     return NameInfo;
4986 
4987   case UnqualifiedIdKind::IK_LiteralOperatorId:
4988     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4989                                                            Name.Identifier));
4990     NameInfo.setLoc(Name.StartLocation);
4991     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4992     return NameInfo;
4993 
4994   case UnqualifiedIdKind::IK_ConversionFunctionId: {
4995     TypeSourceInfo *TInfo;
4996     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4997     if (Ty.isNull())
4998       return DeclarationNameInfo();
4999     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5000                                                Context.getCanonicalType(Ty)));
5001     NameInfo.setLoc(Name.StartLocation);
5002     NameInfo.setNamedTypeInfo(TInfo);
5003     return NameInfo;
5004   }
5005 
5006   case UnqualifiedIdKind::IK_ConstructorName: {
5007     TypeSourceInfo *TInfo;
5008     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5009     if (Ty.isNull())
5010       return DeclarationNameInfo();
5011     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5012                                               Context.getCanonicalType(Ty)));
5013     NameInfo.setLoc(Name.StartLocation);
5014     NameInfo.setNamedTypeInfo(TInfo);
5015     return NameInfo;
5016   }
5017 
5018   case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5019     // In well-formed code, we can only have a constructor
5020     // template-id that refers to the current context, so go there
5021     // to find the actual type being constructed.
5022     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5023     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5024       return DeclarationNameInfo();
5025 
5026     // Determine the type of the class being constructed.
5027     QualType CurClassType = Context.getTypeDeclType(CurClass);
5028 
5029     // FIXME: Check two things: that the template-id names the same type as
5030     // CurClassType, and that the template-id does not occur when the name
5031     // was qualified.
5032 
5033     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5034                                     Context.getCanonicalType(CurClassType)));
5035     NameInfo.setLoc(Name.StartLocation);
5036     // FIXME: should we retrieve TypeSourceInfo?
5037     NameInfo.setNamedTypeInfo(nullptr);
5038     return NameInfo;
5039   }
5040 
5041   case UnqualifiedIdKind::IK_DestructorName: {
5042     TypeSourceInfo *TInfo;
5043     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5044     if (Ty.isNull())
5045       return DeclarationNameInfo();
5046     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5047                                               Context.getCanonicalType(Ty)));
5048     NameInfo.setLoc(Name.StartLocation);
5049     NameInfo.setNamedTypeInfo(TInfo);
5050     return NameInfo;
5051   }
5052 
5053   case UnqualifiedIdKind::IK_TemplateId: {
5054     TemplateName TName = Name.TemplateId->Template.get();
5055     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5056     return Context.getNameForTemplate(TName, TNameLoc);
5057   }
5058 
5059   } // switch (Name.getKind())
5060 
5061   llvm_unreachable("Unknown name kind");
5062 }
5063 
5064 static QualType getCoreType(QualType Ty) {
5065   do {
5066     if (Ty->isPointerType() || Ty->isReferenceType())
5067       Ty = Ty->getPointeeType();
5068     else if (Ty->isArrayType())
5069       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5070     else
5071       return Ty.withoutLocalFastQualifiers();
5072   } while (true);
5073 }
5074 
5075 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5076 /// and Definition have "nearly" matching parameters. This heuristic is
5077 /// used to improve diagnostics in the case where an out-of-line function
5078 /// definition doesn't match any declaration within the class or namespace.
5079 /// Also sets Params to the list of indices to the parameters that differ
5080 /// between the declaration and the definition. If hasSimilarParameters
5081 /// returns true and Params is empty, then all of the parameters match.
5082 static bool hasSimilarParameters(ASTContext &Context,
5083                                      FunctionDecl *Declaration,
5084                                      FunctionDecl *Definition,
5085                                      SmallVectorImpl<unsigned> &Params) {
5086   Params.clear();
5087   if (Declaration->param_size() != Definition->param_size())
5088     return false;
5089   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5090     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5091     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5092 
5093     // The parameter types are identical
5094     if (Context.hasSameType(DefParamTy, DeclParamTy))
5095       continue;
5096 
5097     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5098     QualType DefParamBaseTy = getCoreType(DefParamTy);
5099     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5100     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5101 
5102     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5103         (DeclTyName && DeclTyName == DefTyName))
5104       Params.push_back(Idx);
5105     else  // The two parameters aren't even close
5106       return false;
5107   }
5108 
5109   return true;
5110 }
5111 
5112 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5113 /// declarator needs to be rebuilt in the current instantiation.
5114 /// Any bits of declarator which appear before the name are valid for
5115 /// consideration here.  That's specifically the type in the decl spec
5116 /// and the base type in any member-pointer chunks.
5117 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5118                                                     DeclarationName Name) {
5119   // The types we specifically need to rebuild are:
5120   //   - typenames, typeofs, and decltypes
5121   //   - types which will become injected class names
5122   // Of course, we also need to rebuild any type referencing such a
5123   // type.  It's safest to just say "dependent", but we call out a
5124   // few cases here.
5125 
5126   DeclSpec &DS = D.getMutableDeclSpec();
5127   switch (DS.getTypeSpecType()) {
5128   case DeclSpec::TST_typename:
5129   case DeclSpec::TST_typeofType:
5130   case DeclSpec::TST_underlyingType:
5131   case DeclSpec::TST_atomic: {
5132     // Grab the type from the parser.
5133     TypeSourceInfo *TSI = nullptr;
5134     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5135     if (T.isNull() || !T->isDependentType()) break;
5136 
5137     // Make sure there's a type source info.  This isn't really much
5138     // of a waste; most dependent types should have type source info
5139     // attached already.
5140     if (!TSI)
5141       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5142 
5143     // Rebuild the type in the current instantiation.
5144     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5145     if (!TSI) return true;
5146 
5147     // Store the new type back in the decl spec.
5148     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5149     DS.UpdateTypeRep(LocType);
5150     break;
5151   }
5152 
5153   case DeclSpec::TST_decltype:
5154   case DeclSpec::TST_typeofExpr: {
5155     Expr *E = DS.getRepAsExpr();
5156     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5157     if (Result.isInvalid()) return true;
5158     DS.UpdateExprRep(Result.get());
5159     break;
5160   }
5161 
5162   default:
5163     // Nothing to do for these decl specs.
5164     break;
5165   }
5166 
5167   // It doesn't matter what order we do this in.
5168   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5169     DeclaratorChunk &Chunk = D.getTypeObject(I);
5170 
5171     // The only type information in the declarator which can come
5172     // before the declaration name is the base type of a member
5173     // pointer.
5174     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5175       continue;
5176 
5177     // Rebuild the scope specifier in-place.
5178     CXXScopeSpec &SS = Chunk.Mem.Scope();
5179     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5180       return true;
5181   }
5182 
5183   return false;
5184 }
5185 
5186 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5187   D.setFunctionDefinitionKind(FDK_Declaration);
5188   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5189 
5190   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5191       Dcl && Dcl->getDeclContext()->isFileContext())
5192     Dcl->setTopLevelDeclInObjCContainer();
5193 
5194   if (getLangOpts().OpenCL)
5195     setCurrentOpenCLExtensionForDecl(Dcl);
5196 
5197   return Dcl;
5198 }
5199 
5200 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5201 ///   If T is the name of a class, then each of the following shall have a
5202 ///   name different from T:
5203 ///     - every static data member of class T;
5204 ///     - every member function of class T
5205 ///     - every member of class T that is itself a type;
5206 /// \returns true if the declaration name violates these rules.
5207 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5208                                    DeclarationNameInfo NameInfo) {
5209   DeclarationName Name = NameInfo.getName();
5210 
5211   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5212   while (Record && Record->isAnonymousStructOrUnion())
5213     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5214   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5215     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5216     return true;
5217   }
5218 
5219   return false;
5220 }
5221 
5222 /// \brief Diagnose a declaration whose declarator-id has the given
5223 /// nested-name-specifier.
5224 ///
5225 /// \param SS The nested-name-specifier of the declarator-id.
5226 ///
5227 /// \param DC The declaration context to which the nested-name-specifier
5228 /// resolves.
5229 ///
5230 /// \param Name The name of the entity being declared.
5231 ///
5232 /// \param Loc The location of the name of the entity being declared.
5233 ///
5234 /// \returns true if we cannot safely recover from this error, false otherwise.
5235 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5236                                         DeclarationName Name,
5237                                         SourceLocation Loc) {
5238   DeclContext *Cur = CurContext;
5239   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5240     Cur = Cur->getParent();
5241 
5242   // If the user provided a superfluous scope specifier that refers back to the
5243   // class in which the entity is already declared, diagnose and ignore it.
5244   //
5245   // class X {
5246   //   void X::f();
5247   // };
5248   //
5249   // Note, it was once ill-formed to give redundant qualification in all
5250   // contexts, but that rule was removed by DR482.
5251   if (Cur->Equals(DC)) {
5252     if (Cur->isRecord()) {
5253       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5254                                       : diag::err_member_extra_qualification)
5255         << Name << FixItHint::CreateRemoval(SS.getRange());
5256       SS.clear();
5257     } else {
5258       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5259     }
5260     return false;
5261   }
5262 
5263   // Check whether the qualifying scope encloses the scope of the original
5264   // declaration.
5265   if (!Cur->Encloses(DC)) {
5266     if (Cur->isRecord())
5267       Diag(Loc, diag::err_member_qualification)
5268         << Name << SS.getRange();
5269     else if (isa<TranslationUnitDecl>(DC))
5270       Diag(Loc, diag::err_invalid_declarator_global_scope)
5271         << Name << SS.getRange();
5272     else if (isa<FunctionDecl>(Cur))
5273       Diag(Loc, diag::err_invalid_declarator_in_function)
5274         << Name << SS.getRange();
5275     else if (isa<BlockDecl>(Cur))
5276       Diag(Loc, diag::err_invalid_declarator_in_block)
5277         << Name << SS.getRange();
5278     else
5279       Diag(Loc, diag::err_invalid_declarator_scope)
5280       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5281 
5282     return true;
5283   }
5284 
5285   if (Cur->isRecord()) {
5286     // Cannot qualify members within a class.
5287     Diag(Loc, diag::err_member_qualification)
5288       << Name << SS.getRange();
5289     SS.clear();
5290 
5291     // C++ constructors and destructors with incorrect scopes can break
5292     // our AST invariants by having the wrong underlying types. If
5293     // that's the case, then drop this declaration entirely.
5294     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5295          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5296         !Context.hasSameType(Name.getCXXNameType(),
5297                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5298       return true;
5299 
5300     return false;
5301   }
5302 
5303   // C++11 [dcl.meaning]p1:
5304   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5305   //   not begin with a decltype-specifer"
5306   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5307   while (SpecLoc.getPrefix())
5308     SpecLoc = SpecLoc.getPrefix();
5309   if (dyn_cast_or_null<DecltypeType>(
5310         SpecLoc.getNestedNameSpecifier()->getAsType()))
5311     Diag(Loc, diag::err_decltype_in_declarator)
5312       << SpecLoc.getTypeLoc().getSourceRange();
5313 
5314   return false;
5315 }
5316 
5317 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5318                                   MultiTemplateParamsArg TemplateParamLists) {
5319   // TODO: consider using NameInfo for diagnostic.
5320   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5321   DeclarationName Name = NameInfo.getName();
5322 
5323   // All of these full declarators require an identifier.  If it doesn't have
5324   // one, the ParsedFreeStandingDeclSpec action should be used.
5325   if (D.isDecompositionDeclarator()) {
5326     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5327   } else if (!Name) {
5328     if (!D.isInvalidType())  // Reject this if we think it is valid.
5329       Diag(D.getDeclSpec().getLocStart(),
5330            diag::err_declarator_need_ident)
5331         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5332     return nullptr;
5333   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5334     return nullptr;
5335 
5336   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5337   // we find one that is.
5338   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5339          (S->getFlags() & Scope::TemplateParamScope) != 0)
5340     S = S->getParent();
5341 
5342   DeclContext *DC = CurContext;
5343   if (D.getCXXScopeSpec().isInvalid())
5344     D.setInvalidType();
5345   else if (D.getCXXScopeSpec().isSet()) {
5346     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5347                                         UPPC_DeclarationQualifier))
5348       return nullptr;
5349 
5350     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5351     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5352     if (!DC || isa<EnumDecl>(DC)) {
5353       // If we could not compute the declaration context, it's because the
5354       // declaration context is dependent but does not refer to a class,
5355       // class template, or class template partial specialization. Complain
5356       // and return early, to avoid the coming semantic disaster.
5357       Diag(D.getIdentifierLoc(),
5358            diag::err_template_qualified_declarator_no_match)
5359         << D.getCXXScopeSpec().getScopeRep()
5360         << D.getCXXScopeSpec().getRange();
5361       return nullptr;
5362     }
5363     bool IsDependentContext = DC->isDependentContext();
5364 
5365     if (!IsDependentContext &&
5366         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5367       return nullptr;
5368 
5369     // If a class is incomplete, do not parse entities inside it.
5370     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5371       Diag(D.getIdentifierLoc(),
5372            diag::err_member_def_undefined_record)
5373         << Name << DC << D.getCXXScopeSpec().getRange();
5374       return nullptr;
5375     }
5376     if (!D.getDeclSpec().isFriendSpecified()) {
5377       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5378                                       Name, D.getIdentifierLoc())) {
5379         if (DC->isRecord())
5380           return nullptr;
5381 
5382         D.setInvalidType();
5383       }
5384     }
5385 
5386     // Check whether we need to rebuild the type of the given
5387     // declaration in the current instantiation.
5388     if (EnteringContext && IsDependentContext &&
5389         TemplateParamLists.size() != 0) {
5390       ContextRAII SavedContext(*this, DC);
5391       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5392         D.setInvalidType();
5393     }
5394   }
5395 
5396   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5397   QualType R = TInfo->getType();
5398 
5399   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5400                                       UPPC_DeclarationType))
5401     D.setInvalidType();
5402 
5403   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5404                         forRedeclarationInCurContext());
5405 
5406   // See if this is a redefinition of a variable in the same scope.
5407   if (!D.getCXXScopeSpec().isSet()) {
5408     bool IsLinkageLookup = false;
5409     bool CreateBuiltins = false;
5410 
5411     // If the declaration we're planning to build will be a function
5412     // or object with linkage, then look for another declaration with
5413     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5414     //
5415     // If the declaration we're planning to build will be declared with
5416     // external linkage in the translation unit, create any builtin with
5417     // the same name.
5418     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5419       /* Do nothing*/;
5420     else if (CurContext->isFunctionOrMethod() &&
5421              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5422               R->isFunctionType())) {
5423       IsLinkageLookup = true;
5424       CreateBuiltins =
5425           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5426     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5427                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5428       CreateBuiltins = true;
5429 
5430     if (IsLinkageLookup) {
5431       Previous.clear(LookupRedeclarationWithLinkage);
5432       Previous.setRedeclarationKind(ForExternalRedeclaration);
5433     }
5434 
5435     LookupName(Previous, S, CreateBuiltins);
5436   } else { // Something like "int foo::x;"
5437     LookupQualifiedName(Previous, DC);
5438 
5439     // C++ [dcl.meaning]p1:
5440     //   When the declarator-id is qualified, the declaration shall refer to a
5441     //  previously declared member of the class or namespace to which the
5442     //  qualifier refers (or, in the case of a namespace, of an element of the
5443     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5444     //  thereof; [...]
5445     //
5446     // Note that we already checked the context above, and that we do not have
5447     // enough information to make sure that Previous contains the declaration
5448     // we want to match. For example, given:
5449     //
5450     //   class X {
5451     //     void f();
5452     //     void f(float);
5453     //   };
5454     //
5455     //   void X::f(int) { } // ill-formed
5456     //
5457     // In this case, Previous will point to the overload set
5458     // containing the two f's declared in X, but neither of them
5459     // matches.
5460 
5461     // C++ [dcl.meaning]p1:
5462     //   [...] the member shall not merely have been introduced by a
5463     //   using-declaration in the scope of the class or namespace nominated by
5464     //   the nested-name-specifier of the declarator-id.
5465     RemoveUsingDecls(Previous);
5466   }
5467 
5468   if (Previous.isSingleResult() &&
5469       Previous.getFoundDecl()->isTemplateParameter()) {
5470     // Maybe we will complain about the shadowed template parameter.
5471     if (!D.isInvalidType())
5472       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5473                                       Previous.getFoundDecl());
5474 
5475     // Just pretend that we didn't see the previous declaration.
5476     Previous.clear();
5477   }
5478 
5479   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5480     // Forget that the previous declaration is the injected-class-name.
5481     Previous.clear();
5482 
5483   // In C++, the previous declaration we find might be a tag type
5484   // (class or enum). In this case, the new declaration will hide the
5485   // tag type. Note that this applies to functions, function templates, and
5486   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5487   if (Previous.isSingleTagDecl() &&
5488       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5489       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5490     Previous.clear();
5491 
5492   // Check that there are no default arguments other than in the parameters
5493   // of a function declaration (C++ only).
5494   if (getLangOpts().CPlusPlus)
5495     CheckExtraCXXDefaultArguments(D);
5496 
5497   NamedDecl *New;
5498 
5499   bool AddToScope = true;
5500   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5501     if (TemplateParamLists.size()) {
5502       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5503       return nullptr;
5504     }
5505 
5506     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5507   } else if (R->isFunctionType()) {
5508     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5509                                   TemplateParamLists,
5510                                   AddToScope);
5511   } else {
5512     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5513                                   AddToScope);
5514   }
5515 
5516   if (!New)
5517     return nullptr;
5518 
5519   // If this has an identifier and is not a function template specialization,
5520   // add it to the scope stack.
5521   if (New->getDeclName() && AddToScope) {
5522     // Only make a locally-scoped extern declaration visible if it is the first
5523     // declaration of this entity. Qualified lookup for such an entity should
5524     // only find this declaration if there is no visible declaration of it.
5525     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5526     PushOnScopeChains(New, S, AddToContext);
5527     if (!AddToContext)
5528       CurContext->addHiddenDecl(New);
5529   }
5530 
5531   if (isInOpenMPDeclareTargetContext())
5532     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5533 
5534   return New;
5535 }
5536 
5537 /// Helper method to turn variable array types into constant array
5538 /// types in certain situations which would otherwise be errors (for
5539 /// GCC compatibility).
5540 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5541                                                     ASTContext &Context,
5542                                                     bool &SizeIsNegative,
5543                                                     llvm::APSInt &Oversized) {
5544   // This method tries to turn a variable array into a constant
5545   // array even when the size isn't an ICE.  This is necessary
5546   // for compatibility with code that depends on gcc's buggy
5547   // constant expression folding, like struct {char x[(int)(char*)2];}
5548   SizeIsNegative = false;
5549   Oversized = 0;
5550 
5551   if (T->isDependentType())
5552     return QualType();
5553 
5554   QualifierCollector Qs;
5555   const Type *Ty = Qs.strip(T);
5556 
5557   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5558     QualType Pointee = PTy->getPointeeType();
5559     QualType FixedType =
5560         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5561                                             Oversized);
5562     if (FixedType.isNull()) return FixedType;
5563     FixedType = Context.getPointerType(FixedType);
5564     return Qs.apply(Context, FixedType);
5565   }
5566   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5567     QualType Inner = PTy->getInnerType();
5568     QualType FixedType =
5569         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5570                                             Oversized);
5571     if (FixedType.isNull()) return FixedType;
5572     FixedType = Context.getParenType(FixedType);
5573     return Qs.apply(Context, FixedType);
5574   }
5575 
5576   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5577   if (!VLATy)
5578     return QualType();
5579   // FIXME: We should probably handle this case
5580   if (VLATy->getElementType()->isVariablyModifiedType())
5581     return QualType();
5582 
5583   llvm::APSInt Res;
5584   if (!VLATy->getSizeExpr() ||
5585       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5586     return QualType();
5587 
5588   // Check whether the array size is negative.
5589   if (Res.isSigned() && Res.isNegative()) {
5590     SizeIsNegative = true;
5591     return QualType();
5592   }
5593 
5594   // Check whether the array is too large to be addressed.
5595   unsigned ActiveSizeBits
5596     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5597                                               Res);
5598   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5599     Oversized = Res;
5600     return QualType();
5601   }
5602 
5603   return Context.getConstantArrayType(VLATy->getElementType(),
5604                                       Res, ArrayType::Normal, 0);
5605 }
5606 
5607 static void
5608 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5609   SrcTL = SrcTL.getUnqualifiedLoc();
5610   DstTL = DstTL.getUnqualifiedLoc();
5611   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5612     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5613     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5614                                       DstPTL.getPointeeLoc());
5615     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5616     return;
5617   }
5618   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5619     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5620     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5621                                       DstPTL.getInnerLoc());
5622     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5623     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5624     return;
5625   }
5626   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5627   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5628   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5629   TypeLoc DstElemTL = DstATL.getElementLoc();
5630   DstElemTL.initializeFullCopy(SrcElemTL);
5631   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5632   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5633   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5634 }
5635 
5636 /// Helper method to turn variable array types into constant array
5637 /// types in certain situations which would otherwise be errors (for
5638 /// GCC compatibility).
5639 static TypeSourceInfo*
5640 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5641                                               ASTContext &Context,
5642                                               bool &SizeIsNegative,
5643                                               llvm::APSInt &Oversized) {
5644   QualType FixedTy
5645     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5646                                           SizeIsNegative, Oversized);
5647   if (FixedTy.isNull())
5648     return nullptr;
5649   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5650   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5651                                     FixedTInfo->getTypeLoc());
5652   return FixedTInfo;
5653 }
5654 
5655 /// \brief Register the given locally-scoped extern "C" declaration so
5656 /// that it can be found later for redeclarations. We include any extern "C"
5657 /// declaration that is not visible in the translation unit here, not just
5658 /// function-scope declarations.
5659 void
5660 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5661   if (!getLangOpts().CPlusPlus &&
5662       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5663     // Don't need to track declarations in the TU in C.
5664     return;
5665 
5666   // Note that we have a locally-scoped external with this name.
5667   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5668 }
5669 
5670 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5671   // FIXME: We can have multiple results via __attribute__((overloadable)).
5672   auto Result = Context.getExternCContextDecl()->lookup(Name);
5673   return Result.empty() ? nullptr : *Result.begin();
5674 }
5675 
5676 /// \brief Diagnose function specifiers on a declaration of an identifier that
5677 /// does not identify a function.
5678 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5679   // FIXME: We should probably indicate the identifier in question to avoid
5680   // confusion for constructs like "virtual int a(), b;"
5681   if (DS.isVirtualSpecified())
5682     Diag(DS.getVirtualSpecLoc(),
5683          diag::err_virtual_non_function);
5684 
5685   if (DS.isExplicitSpecified())
5686     Diag(DS.getExplicitSpecLoc(),
5687          diag::err_explicit_non_function);
5688 
5689   if (DS.isNoreturnSpecified())
5690     Diag(DS.getNoreturnSpecLoc(),
5691          diag::err_noreturn_non_function);
5692 }
5693 
5694 NamedDecl*
5695 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5696                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5697   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5698   if (D.getCXXScopeSpec().isSet()) {
5699     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5700       << D.getCXXScopeSpec().getRange();
5701     D.setInvalidType();
5702     // Pretend we didn't see the scope specifier.
5703     DC = CurContext;
5704     Previous.clear();
5705   }
5706 
5707   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5708 
5709   if (D.getDeclSpec().isInlineSpecified())
5710     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5711         << getLangOpts().CPlusPlus17;
5712   if (D.getDeclSpec().isConstexprSpecified())
5713     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5714       << 1;
5715 
5716   if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5717     if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5718       Diag(D.getName().StartLocation,
5719            diag::err_deduction_guide_invalid_specifier)
5720           << "typedef";
5721     else
5722       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5723           << D.getName().getSourceRange();
5724     return nullptr;
5725   }
5726 
5727   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5728   if (!NewTD) return nullptr;
5729 
5730   // Handle attributes prior to checking for duplicates in MergeVarDecl
5731   ProcessDeclAttributes(S, NewTD, D);
5732 
5733   CheckTypedefForVariablyModifiedType(S, NewTD);
5734 
5735   bool Redeclaration = D.isRedeclaration();
5736   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5737   D.setRedeclaration(Redeclaration);
5738   return ND;
5739 }
5740 
5741 void
5742 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5743   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5744   // then it shall have block scope.
5745   // Note that variably modified types must be fixed before merging the decl so
5746   // that redeclarations will match.
5747   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5748   QualType T = TInfo->getType();
5749   if (T->isVariablyModifiedType()) {
5750     getCurFunction()->setHasBranchProtectedScope();
5751 
5752     if (S->getFnParent() == nullptr) {
5753       bool SizeIsNegative;
5754       llvm::APSInt Oversized;
5755       TypeSourceInfo *FixedTInfo =
5756         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5757                                                       SizeIsNegative,
5758                                                       Oversized);
5759       if (FixedTInfo) {
5760         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5761         NewTD->setTypeSourceInfo(FixedTInfo);
5762       } else {
5763         if (SizeIsNegative)
5764           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5765         else if (T->isVariableArrayType())
5766           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5767         else if (Oversized.getBoolValue())
5768           Diag(NewTD->getLocation(), diag::err_array_too_large)
5769             << Oversized.toString(10);
5770         else
5771           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5772         NewTD->setInvalidDecl();
5773       }
5774     }
5775   }
5776 }
5777 
5778 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5779 /// declares a typedef-name, either using the 'typedef' type specifier or via
5780 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5781 NamedDecl*
5782 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5783                            LookupResult &Previous, bool &Redeclaration) {
5784 
5785   // Find the shadowed declaration before filtering for scope.
5786   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5787 
5788   // Merge the decl with the existing one if appropriate. If the decl is
5789   // in an outer scope, it isn't the same thing.
5790   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5791                        /*AllowInlineNamespace*/false);
5792   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5793   if (!Previous.empty()) {
5794     Redeclaration = true;
5795     MergeTypedefNameDecl(S, NewTD, Previous);
5796   }
5797 
5798   if (ShadowedDecl && !Redeclaration)
5799     CheckShadow(NewTD, ShadowedDecl, Previous);
5800 
5801   // If this is the C FILE type, notify the AST context.
5802   if (IdentifierInfo *II = NewTD->getIdentifier())
5803     if (!NewTD->isInvalidDecl() &&
5804         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5805       if (II->isStr("FILE"))
5806         Context.setFILEDecl(NewTD);
5807       else if (II->isStr("jmp_buf"))
5808         Context.setjmp_bufDecl(NewTD);
5809       else if (II->isStr("sigjmp_buf"))
5810         Context.setsigjmp_bufDecl(NewTD);
5811       else if (II->isStr("ucontext_t"))
5812         Context.setucontext_tDecl(NewTD);
5813     }
5814 
5815   return NewTD;
5816 }
5817 
5818 /// \brief Determines whether the given declaration is an out-of-scope
5819 /// previous declaration.
5820 ///
5821 /// This routine should be invoked when name lookup has found a
5822 /// previous declaration (PrevDecl) that is not in the scope where a
5823 /// new declaration by the same name is being introduced. If the new
5824 /// declaration occurs in a local scope, previous declarations with
5825 /// linkage may still be considered previous declarations (C99
5826 /// 6.2.2p4-5, C++ [basic.link]p6).
5827 ///
5828 /// \param PrevDecl the previous declaration found by name
5829 /// lookup
5830 ///
5831 /// \param DC the context in which the new declaration is being
5832 /// declared.
5833 ///
5834 /// \returns true if PrevDecl is an out-of-scope previous declaration
5835 /// for a new delcaration with the same name.
5836 static bool
5837 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5838                                 ASTContext &Context) {
5839   if (!PrevDecl)
5840     return false;
5841 
5842   if (!PrevDecl->hasLinkage())
5843     return false;
5844 
5845   if (Context.getLangOpts().CPlusPlus) {
5846     // C++ [basic.link]p6:
5847     //   If there is a visible declaration of an entity with linkage
5848     //   having the same name and type, ignoring entities declared
5849     //   outside the innermost enclosing namespace scope, the block
5850     //   scope declaration declares that same entity and receives the
5851     //   linkage of the previous declaration.
5852     DeclContext *OuterContext = DC->getRedeclContext();
5853     if (!OuterContext->isFunctionOrMethod())
5854       // This rule only applies to block-scope declarations.
5855       return false;
5856 
5857     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5858     if (PrevOuterContext->isRecord())
5859       // We found a member function: ignore it.
5860       return false;
5861 
5862     // Find the innermost enclosing namespace for the new and
5863     // previous declarations.
5864     OuterContext = OuterContext->getEnclosingNamespaceContext();
5865     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5866 
5867     // The previous declaration is in a different namespace, so it
5868     // isn't the same function.
5869     if (!OuterContext->Equals(PrevOuterContext))
5870       return false;
5871   }
5872 
5873   return true;
5874 }
5875 
5876 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5877   CXXScopeSpec &SS = D.getCXXScopeSpec();
5878   if (!SS.isSet()) return;
5879   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5880 }
5881 
5882 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5883   QualType type = decl->getType();
5884   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5885   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5886     // Various kinds of declaration aren't allowed to be __autoreleasing.
5887     unsigned kind = -1U;
5888     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5889       if (var->hasAttr<BlocksAttr>())
5890         kind = 0; // __block
5891       else if (!var->hasLocalStorage())
5892         kind = 1; // global
5893     } else if (isa<ObjCIvarDecl>(decl)) {
5894       kind = 3; // ivar
5895     } else if (isa<FieldDecl>(decl)) {
5896       kind = 2; // field
5897     }
5898 
5899     if (kind != -1U) {
5900       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5901         << kind;
5902     }
5903   } else if (lifetime == Qualifiers::OCL_None) {
5904     // Try to infer lifetime.
5905     if (!type->isObjCLifetimeType())
5906       return false;
5907 
5908     lifetime = type->getObjCARCImplicitLifetime();
5909     type = Context.getLifetimeQualifiedType(type, lifetime);
5910     decl->setType(type);
5911   }
5912 
5913   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5914     // Thread-local variables cannot have lifetime.
5915     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5916         var->getTLSKind()) {
5917       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5918         << var->getType();
5919       return true;
5920     }
5921   }
5922 
5923   return false;
5924 }
5925 
5926 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5927   // Ensure that an auto decl is deduced otherwise the checks below might cache
5928   // the wrong linkage.
5929   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5930 
5931   // 'weak' only applies to declarations with external linkage.
5932   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5933     if (!ND.isExternallyVisible()) {
5934       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5935       ND.dropAttr<WeakAttr>();
5936     }
5937   }
5938   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5939     if (ND.isExternallyVisible()) {
5940       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5941       ND.dropAttr<WeakRefAttr>();
5942       ND.dropAttr<AliasAttr>();
5943     }
5944   }
5945 
5946   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5947     if (VD->hasInit()) {
5948       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5949         assert(VD->isThisDeclarationADefinition() &&
5950                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5951         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5952         VD->dropAttr<AliasAttr>();
5953       }
5954     }
5955   }
5956 
5957   // 'selectany' only applies to externally visible variable declarations.
5958   // It does not apply to functions.
5959   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5960     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5961       S.Diag(Attr->getLocation(),
5962              diag::err_attribute_selectany_non_extern_data);
5963       ND.dropAttr<SelectAnyAttr>();
5964     }
5965   }
5966 
5967   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5968     // dll attributes require external linkage. Static locals may have external
5969     // linkage but still cannot be explicitly imported or exported.
5970     auto *VD = dyn_cast<VarDecl>(&ND);
5971     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5972       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5973         << &ND << Attr;
5974       ND.setInvalidDecl();
5975     }
5976   }
5977 
5978   // Virtual functions cannot be marked as 'notail'.
5979   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5980     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5981       if (MD->isVirtual()) {
5982         S.Diag(ND.getLocation(),
5983                diag::err_invalid_attribute_on_virtual_function)
5984             << Attr;
5985         ND.dropAttr<NotTailCalledAttr>();
5986       }
5987 }
5988 
5989 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5990                                            NamedDecl *NewDecl,
5991                                            bool IsSpecialization,
5992                                            bool IsDefinition) {
5993   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
5994     return;
5995 
5996   bool IsTemplate = false;
5997   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5998     OldDecl = OldTD->getTemplatedDecl();
5999     IsTemplate = true;
6000     if (!IsSpecialization)
6001       IsDefinition = false;
6002   }
6003   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6004     NewDecl = NewTD->getTemplatedDecl();
6005     IsTemplate = true;
6006   }
6007 
6008   if (!OldDecl || !NewDecl)
6009     return;
6010 
6011   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6012   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6013   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6014   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6015 
6016   // dllimport and dllexport are inheritable attributes so we have to exclude
6017   // inherited attribute instances.
6018   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6019                     (NewExportAttr && !NewExportAttr->isInherited());
6020 
6021   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6022   // the only exception being explicit specializations.
6023   // Implicitly generated declarations are also excluded for now because there
6024   // is no other way to switch these to use dllimport or dllexport.
6025   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6026 
6027   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6028     // Allow with a warning for free functions and global variables.
6029     bool JustWarn = false;
6030     if (!OldDecl->isCXXClassMember()) {
6031       auto *VD = dyn_cast<VarDecl>(OldDecl);
6032       if (VD && !VD->getDescribedVarTemplate())
6033         JustWarn = true;
6034       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6035       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6036         JustWarn = true;
6037     }
6038 
6039     // We cannot change a declaration that's been used because IR has already
6040     // been emitted. Dllimported functions will still work though (modulo
6041     // address equality) as they can use the thunk.
6042     if (OldDecl->isUsed())
6043       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6044         JustWarn = false;
6045 
6046     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6047                                : diag::err_attribute_dll_redeclaration;
6048     S.Diag(NewDecl->getLocation(), DiagID)
6049         << NewDecl
6050         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6051     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6052     if (!JustWarn) {
6053       NewDecl->setInvalidDecl();
6054       return;
6055     }
6056   }
6057 
6058   // A redeclaration is not allowed to drop a dllimport attribute, the only
6059   // exceptions being inline function definitions (except for function
6060   // templates), local extern declarations, qualified friend declarations or
6061   // special MSVC extension: in the last case, the declaration is treated as if
6062   // it were marked dllexport.
6063   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6064   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6065   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6066     // Ignore static data because out-of-line definitions are diagnosed
6067     // separately.
6068     IsStaticDataMember = VD->isStaticDataMember();
6069     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6070                    VarDecl::DeclarationOnly;
6071   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6072     IsInline = FD->isInlined();
6073     IsQualifiedFriend = FD->getQualifier() &&
6074                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6075   }
6076 
6077   if (OldImportAttr && !HasNewAttr &&
6078       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6079       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6080     if (IsMicrosoft && IsDefinition) {
6081       S.Diag(NewDecl->getLocation(),
6082              diag::warn_redeclaration_without_import_attribute)
6083           << NewDecl;
6084       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6085       NewDecl->dropAttr<DLLImportAttr>();
6086       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6087           NewImportAttr->getRange(), S.Context,
6088           NewImportAttr->getSpellingListIndex()));
6089     } else {
6090       S.Diag(NewDecl->getLocation(),
6091              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6092           << NewDecl << OldImportAttr;
6093       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6094       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6095       OldDecl->dropAttr<DLLImportAttr>();
6096       NewDecl->dropAttr<DLLImportAttr>();
6097     }
6098   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6099     // In MinGW, seeing a function declared inline drops the dllimport
6100     // attribute.
6101     OldDecl->dropAttr<DLLImportAttr>();
6102     NewDecl->dropAttr<DLLImportAttr>();
6103     S.Diag(NewDecl->getLocation(),
6104            diag::warn_dllimport_dropped_from_inline_function)
6105         << NewDecl << OldImportAttr;
6106   }
6107 
6108   // A specialization of a class template member function is processed here
6109   // since it's a redeclaration. If the parent class is dllexport, the
6110   // specialization inherits that attribute. This doesn't happen automatically
6111   // since the parent class isn't instantiated until later.
6112   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6113     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6114         !NewImportAttr && !NewExportAttr) {
6115       if (const DLLExportAttr *ParentExportAttr =
6116               MD->getParent()->getAttr<DLLExportAttr>()) {
6117         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6118         NewAttr->setInherited(true);
6119         NewDecl->addAttr(NewAttr);
6120       }
6121     }
6122   }
6123 }
6124 
6125 /// Given that we are within the definition of the given function,
6126 /// will that definition behave like C99's 'inline', where the
6127 /// definition is discarded except for optimization purposes?
6128 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6129   // Try to avoid calling GetGVALinkageForFunction.
6130 
6131   // All cases of this require the 'inline' keyword.
6132   if (!FD->isInlined()) return false;
6133 
6134   // This is only possible in C++ with the gnu_inline attribute.
6135   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6136     return false;
6137 
6138   // Okay, go ahead and call the relatively-more-expensive function.
6139   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6140 }
6141 
6142 /// Determine whether a variable is extern "C" prior to attaching
6143 /// an initializer. We can't just call isExternC() here, because that
6144 /// will also compute and cache whether the declaration is externally
6145 /// visible, which might change when we attach the initializer.
6146 ///
6147 /// This can only be used if the declaration is known to not be a
6148 /// redeclaration of an internal linkage declaration.
6149 ///
6150 /// For instance:
6151 ///
6152 ///   auto x = []{};
6153 ///
6154 /// Attaching the initializer here makes this declaration not externally
6155 /// visible, because its type has internal linkage.
6156 ///
6157 /// FIXME: This is a hack.
6158 template<typename T>
6159 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6160   if (S.getLangOpts().CPlusPlus) {
6161     // In C++, the overloadable attribute negates the effects of extern "C".
6162     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6163       return false;
6164 
6165     // So do CUDA's host/device attributes.
6166     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6167                                  D->template hasAttr<CUDAHostAttr>()))
6168       return false;
6169   }
6170   return D->isExternC();
6171 }
6172 
6173 static bool shouldConsiderLinkage(const VarDecl *VD) {
6174   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6175   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6176     return VD->hasExternalStorage();
6177   if (DC->isFileContext())
6178     return true;
6179   if (DC->isRecord())
6180     return false;
6181   llvm_unreachable("Unexpected context");
6182 }
6183 
6184 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6185   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6186   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6187       isa<OMPDeclareReductionDecl>(DC))
6188     return true;
6189   if (DC->isRecord())
6190     return false;
6191   llvm_unreachable("Unexpected context");
6192 }
6193 
6194 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6195                           AttributeList::Kind Kind) {
6196   for (const AttributeList *L = AttrList; L; L = L->getNext())
6197     if (L->getKind() == Kind)
6198       return true;
6199   return false;
6200 }
6201 
6202 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6203                           AttributeList::Kind Kind) {
6204   // Check decl attributes on the DeclSpec.
6205   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6206     return true;
6207 
6208   // Walk the declarator structure, checking decl attributes that were in a type
6209   // position to the decl itself.
6210   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6211     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6212       return true;
6213   }
6214 
6215   // Finally, check attributes on the decl itself.
6216   return hasParsedAttr(S, PD.getAttributes(), Kind);
6217 }
6218 
6219 /// Adjust the \c DeclContext for a function or variable that might be a
6220 /// function-local external declaration.
6221 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6222   if (!DC->isFunctionOrMethod())
6223     return false;
6224 
6225   // If this is a local extern function or variable declared within a function
6226   // template, don't add it into the enclosing namespace scope until it is
6227   // instantiated; it might have a dependent type right now.
6228   if (DC->isDependentContext())
6229     return true;
6230 
6231   // C++11 [basic.link]p7:
6232   //   When a block scope declaration of an entity with linkage is not found to
6233   //   refer to some other declaration, then that entity is a member of the
6234   //   innermost enclosing namespace.
6235   //
6236   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6237   // semantically-enclosing namespace, not a lexically-enclosing one.
6238   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6239     DC = DC->getParent();
6240   return true;
6241 }
6242 
6243 /// \brief Returns true if given declaration has external C language linkage.
6244 static bool isDeclExternC(const Decl *D) {
6245   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6246     return FD->isExternC();
6247   if (const auto *VD = dyn_cast<VarDecl>(D))
6248     return VD->isExternC();
6249 
6250   llvm_unreachable("Unknown type of decl!");
6251 }
6252 
6253 NamedDecl *Sema::ActOnVariableDeclarator(
6254     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6255     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6256     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6257   QualType R = TInfo->getType();
6258   DeclarationName Name = GetNameForDeclarator(D).getName();
6259 
6260   IdentifierInfo *II = Name.getAsIdentifierInfo();
6261 
6262   if (D.isDecompositionDeclarator()) {
6263     // Take the name of the first declarator as our name for diagnostic
6264     // purposes.
6265     auto &Decomp = D.getDecompositionDeclarator();
6266     if (!Decomp.bindings().empty()) {
6267       II = Decomp.bindings()[0].Name;
6268       Name = II;
6269     }
6270   } else if (!II) {
6271     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6272     return nullptr;
6273   }
6274 
6275   if (getLangOpts().OpenCL) {
6276     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6277     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6278     // argument.
6279     if (R->isImageType() || R->isPipeType()) {
6280       Diag(D.getIdentifierLoc(),
6281            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6282           << R;
6283       D.setInvalidType();
6284       return nullptr;
6285     }
6286 
6287     // OpenCL v1.2 s6.9.r:
6288     // The event type cannot be used to declare a program scope variable.
6289     // OpenCL v2.0 s6.9.q:
6290     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6291     if (NULL == S->getParent()) {
6292       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6293         Diag(D.getIdentifierLoc(),
6294              diag::err_invalid_type_for_program_scope_var) << R;
6295         D.setInvalidType();
6296         return nullptr;
6297       }
6298     }
6299 
6300     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6301     QualType NR = R;
6302     while (NR->isPointerType()) {
6303       if (NR->isFunctionPointerType()) {
6304         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6305         D.setInvalidType();
6306         break;
6307       }
6308       NR = NR->getPointeeType();
6309     }
6310 
6311     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6312       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6313       // half array type (unless the cl_khr_fp16 extension is enabled).
6314       if (Context.getBaseElementType(R)->isHalfType()) {
6315         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6316         D.setInvalidType();
6317       }
6318     }
6319 
6320     if (R->isSamplerT()) {
6321       // OpenCL v1.2 s6.9.b p4:
6322       // The sampler type cannot be used with the __local and __global address
6323       // space qualifiers.
6324       if (R.getAddressSpace() == LangAS::opencl_local ||
6325           R.getAddressSpace() == LangAS::opencl_global) {
6326         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6327       }
6328 
6329       // OpenCL v1.2 s6.12.14.1:
6330       // A global sampler must be declared with either the constant address
6331       // space qualifier or with the const qualifier.
6332       if (DC->isTranslationUnit() &&
6333           !(R.getAddressSpace() == LangAS::opencl_constant ||
6334           R.isConstQualified())) {
6335         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6336         D.setInvalidType();
6337       }
6338     }
6339 
6340     // OpenCL v1.2 s6.9.r:
6341     // The event type cannot be used with the __local, __constant and __global
6342     // address space qualifiers.
6343     if (R->isEventT()) {
6344       if (R.getAddressSpace() != LangAS::opencl_private) {
6345         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6346         D.setInvalidType();
6347       }
6348     }
6349   }
6350 
6351   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6352   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6353 
6354   // dllimport globals without explicit storage class are treated as extern. We
6355   // have to change the storage class this early to get the right DeclContext.
6356   if (SC == SC_None && !DC->isRecord() &&
6357       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6358       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6359     SC = SC_Extern;
6360 
6361   DeclContext *OriginalDC = DC;
6362   bool IsLocalExternDecl = SC == SC_Extern &&
6363                            adjustContextForLocalExternDecl(DC);
6364 
6365   if (SCSpec == DeclSpec::SCS_mutable) {
6366     // mutable can only appear on non-static class members, so it's always
6367     // an error here
6368     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6369     D.setInvalidType();
6370     SC = SC_None;
6371   }
6372 
6373   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6374       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6375                               D.getDeclSpec().getStorageClassSpecLoc())) {
6376     // In C++11, the 'register' storage class specifier is deprecated.
6377     // Suppress the warning in system macros, it's used in macros in some
6378     // popular C system headers, such as in glibc's htonl() macro.
6379     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6380          getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6381                                    : diag::warn_deprecated_register)
6382       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6383   }
6384 
6385   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6386 
6387   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6388     // C99 6.9p2: The storage-class specifiers auto and register shall not
6389     // appear in the declaration specifiers in an external declaration.
6390     // Global Register+Asm is a GNU extension we support.
6391     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6392       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6393       D.setInvalidType();
6394     }
6395   }
6396 
6397   bool IsMemberSpecialization = false;
6398   bool IsVariableTemplateSpecialization = false;
6399   bool IsPartialSpecialization = false;
6400   bool IsVariableTemplate = false;
6401   VarDecl *NewVD = nullptr;
6402   VarTemplateDecl *NewTemplate = nullptr;
6403   TemplateParameterList *TemplateParams = nullptr;
6404   if (!getLangOpts().CPlusPlus) {
6405     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6406                             D.getIdentifierLoc(), II,
6407                             R, TInfo, SC);
6408 
6409     if (R->getContainedDeducedType())
6410       ParsingInitForAutoVars.insert(NewVD);
6411 
6412     if (D.isInvalidType())
6413       NewVD->setInvalidDecl();
6414   } else {
6415     bool Invalid = false;
6416 
6417     if (DC->isRecord() && !CurContext->isRecord()) {
6418       // This is an out-of-line definition of a static data member.
6419       switch (SC) {
6420       case SC_None:
6421         break;
6422       case SC_Static:
6423         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6424              diag::err_static_out_of_line)
6425           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6426         break;
6427       case SC_Auto:
6428       case SC_Register:
6429       case SC_Extern:
6430         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6431         // to names of variables declared in a block or to function parameters.
6432         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6433         // of class members
6434 
6435         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6436              diag::err_storage_class_for_static_member)
6437           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6438         break;
6439       case SC_PrivateExtern:
6440         llvm_unreachable("C storage class in c++!");
6441       }
6442     }
6443 
6444     if (SC == SC_Static && CurContext->isRecord()) {
6445       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6446         if (RD->isLocalClass())
6447           Diag(D.getIdentifierLoc(),
6448                diag::err_static_data_member_not_allowed_in_local_class)
6449             << Name << RD->getDeclName();
6450 
6451         // C++98 [class.union]p1: If a union contains a static data member,
6452         // the program is ill-formed. C++11 drops this restriction.
6453         if (RD->isUnion())
6454           Diag(D.getIdentifierLoc(),
6455                getLangOpts().CPlusPlus11
6456                  ? diag::warn_cxx98_compat_static_data_member_in_union
6457                  : diag::ext_static_data_member_in_union) << Name;
6458         // We conservatively disallow static data members in anonymous structs.
6459         else if (!RD->getDeclName())
6460           Diag(D.getIdentifierLoc(),
6461                diag::err_static_data_member_not_allowed_in_anon_struct)
6462             << Name << RD->isUnion();
6463       }
6464     }
6465 
6466     // Match up the template parameter lists with the scope specifier, then
6467     // determine whether we have a template or a template specialization.
6468     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6469         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6470         D.getCXXScopeSpec(),
6471         D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6472             ? D.getName().TemplateId
6473             : nullptr,
6474         TemplateParamLists,
6475         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6476 
6477     if (TemplateParams) {
6478       if (!TemplateParams->size() &&
6479           D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6480         // There is an extraneous 'template<>' for this variable. Complain
6481         // about it, but allow the declaration of the variable.
6482         Diag(TemplateParams->getTemplateLoc(),
6483              diag::err_template_variable_noparams)
6484           << II
6485           << SourceRange(TemplateParams->getTemplateLoc(),
6486                          TemplateParams->getRAngleLoc());
6487         TemplateParams = nullptr;
6488       } else {
6489         if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6490           // This is an explicit specialization or a partial specialization.
6491           // FIXME: Check that we can declare a specialization here.
6492           IsVariableTemplateSpecialization = true;
6493           IsPartialSpecialization = TemplateParams->size() > 0;
6494         } else { // if (TemplateParams->size() > 0)
6495           // This is a template declaration.
6496           IsVariableTemplate = true;
6497 
6498           // Check that we can declare a template here.
6499           if (CheckTemplateDeclScope(S, TemplateParams))
6500             return nullptr;
6501 
6502           // Only C++1y supports variable templates (N3651).
6503           Diag(D.getIdentifierLoc(),
6504                getLangOpts().CPlusPlus14
6505                    ? diag::warn_cxx11_compat_variable_template
6506                    : diag::ext_variable_template);
6507         }
6508       }
6509     } else {
6510       assert((Invalid ||
6511               D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6512              "should have a 'template<>' for this decl");
6513     }
6514 
6515     if (IsVariableTemplateSpecialization) {
6516       SourceLocation TemplateKWLoc =
6517           TemplateParamLists.size() > 0
6518               ? TemplateParamLists[0]->getTemplateLoc()
6519               : SourceLocation();
6520       DeclResult Res = ActOnVarTemplateSpecialization(
6521           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6522           IsPartialSpecialization);
6523       if (Res.isInvalid())
6524         return nullptr;
6525       NewVD = cast<VarDecl>(Res.get());
6526       AddToScope = false;
6527     } else if (D.isDecompositionDeclarator()) {
6528       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6529                                         D.getIdentifierLoc(), R, TInfo, SC,
6530                                         Bindings);
6531     } else
6532       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6533                               D.getIdentifierLoc(), II, R, TInfo, SC);
6534 
6535     // If this is supposed to be a variable template, create it as such.
6536     if (IsVariableTemplate) {
6537       NewTemplate =
6538           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6539                                   TemplateParams, NewVD);
6540       NewVD->setDescribedVarTemplate(NewTemplate);
6541     }
6542 
6543     // If this decl has an auto type in need of deduction, make a note of the
6544     // Decl so we can diagnose uses of it in its own initializer.
6545     if (R->getContainedDeducedType())
6546       ParsingInitForAutoVars.insert(NewVD);
6547 
6548     if (D.isInvalidType() || Invalid) {
6549       NewVD->setInvalidDecl();
6550       if (NewTemplate)
6551         NewTemplate->setInvalidDecl();
6552     }
6553 
6554     SetNestedNameSpecifier(NewVD, D);
6555 
6556     // If we have any template parameter lists that don't directly belong to
6557     // the variable (matching the scope specifier), store them.
6558     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6559     if (TemplateParamLists.size() > VDTemplateParamLists)
6560       NewVD->setTemplateParameterListsInfo(
6561           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6562 
6563     if (D.getDeclSpec().isConstexprSpecified()) {
6564       NewVD->setConstexpr(true);
6565       // C++1z [dcl.spec.constexpr]p1:
6566       //   A static data member declared with the constexpr specifier is
6567       //   implicitly an inline variable.
6568       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6569         NewVD->setImplicitlyInline();
6570     }
6571   }
6572 
6573   if (D.getDeclSpec().isInlineSpecified()) {
6574     if (!getLangOpts().CPlusPlus) {
6575       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6576           << 0;
6577     } else if (CurContext->isFunctionOrMethod()) {
6578       // 'inline' is not allowed on block scope variable declaration.
6579       Diag(D.getDeclSpec().getInlineSpecLoc(),
6580            diag::err_inline_declaration_block_scope) << Name
6581         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6582     } else {
6583       Diag(D.getDeclSpec().getInlineSpecLoc(),
6584            getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6585                                      : diag::ext_inline_variable);
6586       NewVD->setInlineSpecified();
6587     }
6588   }
6589 
6590   // Set the lexical context. If the declarator has a C++ scope specifier, the
6591   // lexical context will be different from the semantic context.
6592   NewVD->setLexicalDeclContext(CurContext);
6593   if (NewTemplate)
6594     NewTemplate->setLexicalDeclContext(CurContext);
6595 
6596   if (IsLocalExternDecl) {
6597     if (D.isDecompositionDeclarator())
6598       for (auto *B : Bindings)
6599         B->setLocalExternDecl();
6600     else
6601       NewVD->setLocalExternDecl();
6602   }
6603 
6604   bool EmitTLSUnsupportedError = false;
6605   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6606     // C++11 [dcl.stc]p4:
6607     //   When thread_local is applied to a variable of block scope the
6608     //   storage-class-specifier static is implied if it does not appear
6609     //   explicitly.
6610     // Core issue: 'static' is not implied if the variable is declared
6611     //   'extern'.
6612     if (NewVD->hasLocalStorage() &&
6613         (SCSpec != DeclSpec::SCS_unspecified ||
6614          TSCS != DeclSpec::TSCS_thread_local ||
6615          !DC->isFunctionOrMethod()))
6616       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6617            diag::err_thread_non_global)
6618         << DeclSpec::getSpecifierName(TSCS);
6619     else if (!Context.getTargetInfo().isTLSSupported()) {
6620       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6621         // Postpone error emission until we've collected attributes required to
6622         // figure out whether it's a host or device variable and whether the
6623         // error should be ignored.
6624         EmitTLSUnsupportedError = true;
6625         // We still need to mark the variable as TLS so it shows up in AST with
6626         // proper storage class for other tools to use even if we're not going
6627         // to emit any code for it.
6628         NewVD->setTSCSpec(TSCS);
6629       } else
6630         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6631              diag::err_thread_unsupported);
6632     } else
6633       NewVD->setTSCSpec(TSCS);
6634   }
6635 
6636   // C99 6.7.4p3
6637   //   An inline definition of a function with external linkage shall
6638   //   not contain a definition of a modifiable object with static or
6639   //   thread storage duration...
6640   // We only apply this when the function is required to be defined
6641   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6642   // that a local variable with thread storage duration still has to
6643   // be marked 'static'.  Also note that it's possible to get these
6644   // semantics in C++ using __attribute__((gnu_inline)).
6645   if (SC == SC_Static && S->getFnParent() != nullptr &&
6646       !NewVD->getType().isConstQualified()) {
6647     FunctionDecl *CurFD = getCurFunctionDecl();
6648     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6649       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6650            diag::warn_static_local_in_extern_inline);
6651       MaybeSuggestAddingStaticToDecl(CurFD);
6652     }
6653   }
6654 
6655   if (D.getDeclSpec().isModulePrivateSpecified()) {
6656     if (IsVariableTemplateSpecialization)
6657       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6658           << (IsPartialSpecialization ? 1 : 0)
6659           << FixItHint::CreateRemoval(
6660                  D.getDeclSpec().getModulePrivateSpecLoc());
6661     else if (IsMemberSpecialization)
6662       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6663         << 2
6664         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6665     else if (NewVD->hasLocalStorage())
6666       Diag(NewVD->getLocation(), diag::err_module_private_local)
6667         << 0 << NewVD->getDeclName()
6668         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6669         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6670     else {
6671       NewVD->setModulePrivate();
6672       if (NewTemplate)
6673         NewTemplate->setModulePrivate();
6674       for (auto *B : Bindings)
6675         B->setModulePrivate();
6676     }
6677   }
6678 
6679   // Handle attributes prior to checking for duplicates in MergeVarDecl
6680   ProcessDeclAttributes(S, NewVD, D);
6681 
6682   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6683     if (EmitTLSUnsupportedError &&
6684         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6685          (getLangOpts().OpenMPIsDevice &&
6686           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6687       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6688            diag::err_thread_unsupported);
6689     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6690     // storage [duration]."
6691     if (SC == SC_None && S->getFnParent() != nullptr &&
6692         (NewVD->hasAttr<CUDASharedAttr>() ||
6693          NewVD->hasAttr<CUDAConstantAttr>())) {
6694       NewVD->setStorageClass(SC_Static);
6695     }
6696   }
6697 
6698   // Ensure that dllimport globals without explicit storage class are treated as
6699   // extern. The storage class is set above using parsed attributes. Now we can
6700   // check the VarDecl itself.
6701   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6702          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6703          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6704 
6705   // In auto-retain/release, infer strong retension for variables of
6706   // retainable type.
6707   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6708     NewVD->setInvalidDecl();
6709 
6710   // Handle GNU asm-label extension (encoded as an attribute).
6711   if (Expr *E = (Expr*)D.getAsmLabel()) {
6712     // The parser guarantees this is a string.
6713     StringLiteral *SE = cast<StringLiteral>(E);
6714     StringRef Label = SE->getString();
6715     if (S->getFnParent() != nullptr) {
6716       switch (SC) {
6717       case SC_None:
6718       case SC_Auto:
6719         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6720         break;
6721       case SC_Register:
6722         // Local Named register
6723         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6724             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6725           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6726         break;
6727       case SC_Static:
6728       case SC_Extern:
6729       case SC_PrivateExtern:
6730         break;
6731       }
6732     } else if (SC == SC_Register) {
6733       // Global Named register
6734       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6735         const auto &TI = Context.getTargetInfo();
6736         bool HasSizeMismatch;
6737 
6738         if (!TI.isValidGCCRegisterName(Label))
6739           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6740         else if (!TI.validateGlobalRegisterVariable(Label,
6741                                                     Context.getTypeSize(R),
6742                                                     HasSizeMismatch))
6743           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6744         else if (HasSizeMismatch)
6745           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6746       }
6747 
6748       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6749         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6750         NewVD->setInvalidDecl(true);
6751       }
6752     }
6753 
6754     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6755                                                 Context, Label, 0));
6756   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6757     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6758       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6759     if (I != ExtnameUndeclaredIdentifiers.end()) {
6760       if (isDeclExternC(NewVD)) {
6761         NewVD->addAttr(I->second);
6762         ExtnameUndeclaredIdentifiers.erase(I);
6763       } else
6764         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6765             << /*Variable*/1 << NewVD;
6766     }
6767   }
6768 
6769   // Find the shadowed declaration before filtering for scope.
6770   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6771                                 ? getShadowedDeclaration(NewVD, Previous)
6772                                 : nullptr;
6773 
6774   // Don't consider existing declarations that are in a different
6775   // scope and are out-of-semantic-context declarations (if the new
6776   // declaration has linkage).
6777   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6778                        D.getCXXScopeSpec().isNotEmpty() ||
6779                        IsMemberSpecialization ||
6780                        IsVariableTemplateSpecialization);
6781 
6782   // Check whether the previous declaration is in the same block scope. This
6783   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6784   if (getLangOpts().CPlusPlus &&
6785       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6786     NewVD->setPreviousDeclInSameBlockScope(
6787         Previous.isSingleResult() && !Previous.isShadowed() &&
6788         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6789 
6790   if (!getLangOpts().CPlusPlus) {
6791     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6792   } else {
6793     // If this is an explicit specialization of a static data member, check it.
6794     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6795         CheckMemberSpecialization(NewVD, Previous))
6796       NewVD->setInvalidDecl();
6797 
6798     // Merge the decl with the existing one if appropriate.
6799     if (!Previous.empty()) {
6800       if (Previous.isSingleResult() &&
6801           isa<FieldDecl>(Previous.getFoundDecl()) &&
6802           D.getCXXScopeSpec().isSet()) {
6803         // The user tried to define a non-static data member
6804         // out-of-line (C++ [dcl.meaning]p1).
6805         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6806           << D.getCXXScopeSpec().getRange();
6807         Previous.clear();
6808         NewVD->setInvalidDecl();
6809       }
6810     } else if (D.getCXXScopeSpec().isSet()) {
6811       // No previous declaration in the qualifying scope.
6812       Diag(D.getIdentifierLoc(), diag::err_no_member)
6813         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6814         << D.getCXXScopeSpec().getRange();
6815       NewVD->setInvalidDecl();
6816     }
6817 
6818     if (!IsVariableTemplateSpecialization)
6819       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6820 
6821     if (NewTemplate) {
6822       VarTemplateDecl *PrevVarTemplate =
6823           NewVD->getPreviousDecl()
6824               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6825               : nullptr;
6826 
6827       // Check the template parameter list of this declaration, possibly
6828       // merging in the template parameter list from the previous variable
6829       // template declaration.
6830       if (CheckTemplateParameterList(
6831               TemplateParams,
6832               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6833                               : nullptr,
6834               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6835                DC->isDependentContext())
6836                   ? TPC_ClassTemplateMember
6837                   : TPC_VarTemplate))
6838         NewVD->setInvalidDecl();
6839 
6840       // If we are providing an explicit specialization of a static variable
6841       // template, make a note of that.
6842       if (PrevVarTemplate &&
6843           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6844         PrevVarTemplate->setMemberSpecialization();
6845     }
6846   }
6847 
6848   // Diagnose shadowed variables iff this isn't a redeclaration.
6849   if (ShadowedDecl && !D.isRedeclaration())
6850     CheckShadow(NewVD, ShadowedDecl, Previous);
6851 
6852   ProcessPragmaWeak(S, NewVD);
6853 
6854   // If this is the first declaration of an extern C variable, update
6855   // the map of such variables.
6856   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6857       isIncompleteDeclExternC(*this, NewVD))
6858     RegisterLocallyScopedExternCDecl(NewVD, S);
6859 
6860   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6861     Decl *ManglingContextDecl;
6862     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6863             NewVD->getDeclContext(), ManglingContextDecl)) {
6864       Context.setManglingNumber(
6865           NewVD, MCtx->getManglingNumber(
6866                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6867       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6868     }
6869   }
6870 
6871   // Special handling of variable named 'main'.
6872   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6873       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6874       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6875 
6876     // C++ [basic.start.main]p3
6877     // A program that declares a variable main at global scope is ill-formed.
6878     if (getLangOpts().CPlusPlus)
6879       Diag(D.getLocStart(), diag::err_main_global_variable);
6880 
6881     // In C, and external-linkage variable named main results in undefined
6882     // behavior.
6883     else if (NewVD->hasExternalFormalLinkage())
6884       Diag(D.getLocStart(), diag::warn_main_redefined);
6885   }
6886 
6887   if (D.isRedeclaration() && !Previous.empty()) {
6888     checkDLLAttributeRedeclaration(
6889         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6890         IsMemberSpecialization, D.isFunctionDefinition());
6891   }
6892 
6893   if (NewTemplate) {
6894     if (NewVD->isInvalidDecl())
6895       NewTemplate->setInvalidDecl();
6896     ActOnDocumentableDecl(NewTemplate);
6897     return NewTemplate;
6898   }
6899 
6900   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6901     CompleteMemberSpecialization(NewVD, Previous);
6902 
6903   return NewVD;
6904 }
6905 
6906 /// Enum describing the %select options in diag::warn_decl_shadow.
6907 enum ShadowedDeclKind {
6908   SDK_Local,
6909   SDK_Global,
6910   SDK_StaticMember,
6911   SDK_Field,
6912   SDK_Typedef,
6913   SDK_Using
6914 };
6915 
6916 /// Determine what kind of declaration we're shadowing.
6917 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6918                                                 const DeclContext *OldDC) {
6919   if (isa<TypeAliasDecl>(ShadowedDecl))
6920     return SDK_Using;
6921   else if (isa<TypedefDecl>(ShadowedDecl))
6922     return SDK_Typedef;
6923   else if (isa<RecordDecl>(OldDC))
6924     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6925 
6926   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6927 }
6928 
6929 /// Return the location of the capture if the given lambda captures the given
6930 /// variable \p VD, or an invalid source location otherwise.
6931 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6932                                          const VarDecl *VD) {
6933   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6934     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6935       return Capture.getLocation();
6936   }
6937   return SourceLocation();
6938 }
6939 
6940 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6941                                      const LookupResult &R) {
6942   // Only diagnose if we're shadowing an unambiguous field or variable.
6943   if (R.getResultKind() != LookupResult::Found)
6944     return false;
6945 
6946   // Return false if warning is ignored.
6947   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6948 }
6949 
6950 /// \brief Return the declaration shadowed by the given variable \p D, or null
6951 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6952 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6953                                         const LookupResult &R) {
6954   if (!shouldWarnIfShadowedDecl(Diags, R))
6955     return nullptr;
6956 
6957   // Don't diagnose declarations at file scope.
6958   if (D->hasGlobalStorage())
6959     return nullptr;
6960 
6961   NamedDecl *ShadowedDecl = R.getFoundDecl();
6962   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6963              ? ShadowedDecl
6964              : nullptr;
6965 }
6966 
6967 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6968 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6969 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6970                                         const LookupResult &R) {
6971   // Don't warn if typedef declaration is part of a class
6972   if (D->getDeclContext()->isRecord())
6973     return nullptr;
6974 
6975   if (!shouldWarnIfShadowedDecl(Diags, R))
6976     return nullptr;
6977 
6978   NamedDecl *ShadowedDecl = R.getFoundDecl();
6979   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6980 }
6981 
6982 /// \brief Diagnose variable or built-in function shadowing.  Implements
6983 /// -Wshadow.
6984 ///
6985 /// This method is called whenever a VarDecl is added to a "useful"
6986 /// scope.
6987 ///
6988 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6989 /// \param R the lookup of the name
6990 ///
6991 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6992                        const LookupResult &R) {
6993   DeclContext *NewDC = D->getDeclContext();
6994 
6995   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6996     // Fields are not shadowed by variables in C++ static methods.
6997     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6998       if (MD->isStatic())
6999         return;
7000 
7001     // Fields shadowed by constructor parameters are a special case. Usually
7002     // the constructor initializes the field with the parameter.
7003     if (isa<CXXConstructorDecl>(NewDC))
7004       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7005         // Remember that this was shadowed so we can either warn about its
7006         // modification or its existence depending on warning settings.
7007         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7008         return;
7009       }
7010   }
7011 
7012   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7013     if (shadowedVar->isExternC()) {
7014       // For shadowing external vars, make sure that we point to the global
7015       // declaration, not a locally scoped extern declaration.
7016       for (auto I : shadowedVar->redecls())
7017         if (I->isFileVarDecl()) {
7018           ShadowedDecl = I;
7019           break;
7020         }
7021     }
7022 
7023   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7024 
7025   unsigned WarningDiag = diag::warn_decl_shadow;
7026   SourceLocation CaptureLoc;
7027   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7028       isa<CXXMethodDecl>(NewDC)) {
7029     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7030       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7031         if (RD->getLambdaCaptureDefault() == LCD_None) {
7032           // Try to avoid warnings for lambdas with an explicit capture list.
7033           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7034           // Warn only when the lambda captures the shadowed decl explicitly.
7035           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7036           if (CaptureLoc.isInvalid())
7037             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7038         } else {
7039           // Remember that this was shadowed so we can avoid the warning if the
7040           // shadowed decl isn't captured and the warning settings allow it.
7041           cast<LambdaScopeInfo>(getCurFunction())
7042               ->ShadowingDecls.push_back(
7043                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7044           return;
7045         }
7046       }
7047 
7048       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7049         // A variable can't shadow a local variable in an enclosing scope, if
7050         // they are separated by a non-capturing declaration context.
7051         for (DeclContext *ParentDC = NewDC;
7052              ParentDC && !ParentDC->Equals(OldDC);
7053              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7054           // Only block literals, captured statements, and lambda expressions
7055           // can capture; other scopes don't.
7056           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7057               !isLambdaCallOperator(ParentDC)) {
7058             return;
7059           }
7060         }
7061       }
7062     }
7063   }
7064 
7065   // Only warn about certain kinds of shadowing for class members.
7066   if (NewDC && NewDC->isRecord()) {
7067     // In particular, don't warn about shadowing non-class members.
7068     if (!OldDC->isRecord())
7069       return;
7070 
7071     // TODO: should we warn about static data members shadowing
7072     // static data members from base classes?
7073 
7074     // TODO: don't diagnose for inaccessible shadowed members.
7075     // This is hard to do perfectly because we might friend the
7076     // shadowing context, but that's just a false negative.
7077   }
7078 
7079 
7080   DeclarationName Name = R.getLookupName();
7081 
7082   // Emit warning and note.
7083   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7084     return;
7085   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7086   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7087   if (!CaptureLoc.isInvalid())
7088     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7089         << Name << /*explicitly*/ 1;
7090   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7091 }
7092 
7093 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7094 /// when these variables are captured by the lambda.
7095 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7096   for (const auto &Shadow : LSI->ShadowingDecls) {
7097     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7098     // Try to avoid the warning when the shadowed decl isn't captured.
7099     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7100     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7101     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7102                                        ? diag::warn_decl_shadow_uncaptured_local
7103                                        : diag::warn_decl_shadow)
7104         << Shadow.VD->getDeclName()
7105         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7106     if (!CaptureLoc.isInvalid())
7107       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7108           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7109     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7110   }
7111 }
7112 
7113 /// \brief Check -Wshadow without the advantage of a previous lookup.
7114 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7115   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7116     return;
7117 
7118   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7119                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7120   LookupName(R, S);
7121   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7122     CheckShadow(D, ShadowedDecl, R);
7123 }
7124 
7125 /// Check if 'E', which is an expression that is about to be modified, refers
7126 /// to a constructor parameter that shadows a field.
7127 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7128   // Quickly ignore expressions that can't be shadowing ctor parameters.
7129   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7130     return;
7131   E = E->IgnoreParenImpCasts();
7132   auto *DRE = dyn_cast<DeclRefExpr>(E);
7133   if (!DRE)
7134     return;
7135   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7136   auto I = ShadowingDecls.find(D);
7137   if (I == ShadowingDecls.end())
7138     return;
7139   const NamedDecl *ShadowedDecl = I->second;
7140   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7141   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7142   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7143   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7144 
7145   // Avoid issuing multiple warnings about the same decl.
7146   ShadowingDecls.erase(I);
7147 }
7148 
7149 /// Check for conflict between this global or extern "C" declaration and
7150 /// previous global or extern "C" declarations. This is only used in C++.
7151 template<typename T>
7152 static bool checkGlobalOrExternCConflict(
7153     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7154   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7155   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7156 
7157   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7158     // The common case: this global doesn't conflict with any extern "C"
7159     // declaration.
7160     return false;
7161   }
7162 
7163   if (Prev) {
7164     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7165       // Both the old and new declarations have C language linkage. This is a
7166       // redeclaration.
7167       Previous.clear();
7168       Previous.addDecl(Prev);
7169       return true;
7170     }
7171 
7172     // This is a global, non-extern "C" declaration, and there is a previous
7173     // non-global extern "C" declaration. Diagnose if this is a variable
7174     // declaration.
7175     if (!isa<VarDecl>(ND))
7176       return false;
7177   } else {
7178     // The declaration is extern "C". Check for any declaration in the
7179     // translation unit which might conflict.
7180     if (IsGlobal) {
7181       // We have already performed the lookup into the translation unit.
7182       IsGlobal = false;
7183       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7184            I != E; ++I) {
7185         if (isa<VarDecl>(*I)) {
7186           Prev = *I;
7187           break;
7188         }
7189       }
7190     } else {
7191       DeclContext::lookup_result R =
7192           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7193       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7194            I != E; ++I) {
7195         if (isa<VarDecl>(*I)) {
7196           Prev = *I;
7197           break;
7198         }
7199         // FIXME: If we have any other entity with this name in global scope,
7200         // the declaration is ill-formed, but that is a defect: it breaks the
7201         // 'stat' hack, for instance. Only variables can have mangled name
7202         // clashes with extern "C" declarations, so only they deserve a
7203         // diagnostic.
7204       }
7205     }
7206 
7207     if (!Prev)
7208       return false;
7209   }
7210 
7211   // Use the first declaration's location to ensure we point at something which
7212   // is lexically inside an extern "C" linkage-spec.
7213   assert(Prev && "should have found a previous declaration to diagnose");
7214   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7215     Prev = FD->getFirstDecl();
7216   else
7217     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7218 
7219   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7220     << IsGlobal << ND;
7221   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7222     << IsGlobal;
7223   return false;
7224 }
7225 
7226 /// Apply special rules for handling extern "C" declarations. Returns \c true
7227 /// if we have found that this is a redeclaration of some prior entity.
7228 ///
7229 /// Per C++ [dcl.link]p6:
7230 ///   Two declarations [for a function or variable] with C language linkage
7231 ///   with the same name that appear in different scopes refer to the same
7232 ///   [entity]. An entity with C language linkage shall not be declared with
7233 ///   the same name as an entity in global scope.
7234 template<typename T>
7235 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7236                                                   LookupResult &Previous) {
7237   if (!S.getLangOpts().CPlusPlus) {
7238     // In C, when declaring a global variable, look for a corresponding 'extern'
7239     // variable declared in function scope. We don't need this in C++, because
7240     // we find local extern decls in the surrounding file-scope DeclContext.
7241     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7242       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7243         Previous.clear();
7244         Previous.addDecl(Prev);
7245         return true;
7246       }
7247     }
7248     return false;
7249   }
7250 
7251   // A declaration in the translation unit can conflict with an extern "C"
7252   // declaration.
7253   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7254     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7255 
7256   // An extern "C" declaration can conflict with a declaration in the
7257   // translation unit or can be a redeclaration of an extern "C" declaration
7258   // in another scope.
7259   if (isIncompleteDeclExternC(S,ND))
7260     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7261 
7262   // Neither global nor extern "C": nothing to do.
7263   return false;
7264 }
7265 
7266 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7267   // If the decl is already known invalid, don't check it.
7268   if (NewVD->isInvalidDecl())
7269     return;
7270 
7271   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7272   QualType T = TInfo->getType();
7273 
7274   // Defer checking an 'auto' type until its initializer is attached.
7275   if (T->isUndeducedType())
7276     return;
7277 
7278   if (NewVD->hasAttrs())
7279     CheckAlignasUnderalignment(NewVD);
7280 
7281   if (T->isObjCObjectType()) {
7282     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7283       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7284     T = Context.getObjCObjectPointerType(T);
7285     NewVD->setType(T);
7286   }
7287 
7288   // Emit an error if an address space was applied to decl with local storage.
7289   // This includes arrays of objects with address space qualifiers, but not
7290   // automatic variables that point to other address spaces.
7291   // ISO/IEC TR 18037 S5.1.2
7292   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7293       T.getAddressSpace() != LangAS::Default) {
7294     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7295     NewVD->setInvalidDecl();
7296     return;
7297   }
7298 
7299   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7300   // scope.
7301   if (getLangOpts().OpenCLVersion == 120 &&
7302       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7303       NewVD->isStaticLocal()) {
7304     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7305     NewVD->setInvalidDecl();
7306     return;
7307   }
7308 
7309   if (getLangOpts().OpenCL) {
7310     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7311     if (NewVD->hasAttr<BlocksAttr>()) {
7312       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7313       return;
7314     }
7315 
7316     if (T->isBlockPointerType()) {
7317       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7318       // can't use 'extern' storage class.
7319       if (!T.isConstQualified()) {
7320         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7321             << 0 /*const*/;
7322         NewVD->setInvalidDecl();
7323         return;
7324       }
7325       if (NewVD->hasExternalStorage()) {
7326         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7327         NewVD->setInvalidDecl();
7328         return;
7329       }
7330     }
7331     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7332     // __constant address space.
7333     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7334     // variables inside a function can also be declared in the global
7335     // address space.
7336     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7337         NewVD->hasExternalStorage()) {
7338       if (!T->isSamplerT() &&
7339           !(T.getAddressSpace() == LangAS::opencl_constant ||
7340             (T.getAddressSpace() == LangAS::opencl_global &&
7341              getLangOpts().OpenCLVersion == 200))) {
7342         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7343         if (getLangOpts().OpenCLVersion == 200)
7344           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7345               << Scope << "global or constant";
7346         else
7347           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7348               << Scope << "constant";
7349         NewVD->setInvalidDecl();
7350         return;
7351       }
7352     } else {
7353       if (T.getAddressSpace() == LangAS::opencl_global) {
7354         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7355             << 1 /*is any function*/ << "global";
7356         NewVD->setInvalidDecl();
7357         return;
7358       }
7359       if (T.getAddressSpace() == LangAS::opencl_constant ||
7360           T.getAddressSpace() == LangAS::opencl_local) {
7361         FunctionDecl *FD = getCurFunctionDecl();
7362         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7363         // in functions.
7364         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7365           if (T.getAddressSpace() == LangAS::opencl_constant)
7366             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7367                 << 0 /*non-kernel only*/ << "constant";
7368           else
7369             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7370                 << 0 /*non-kernel only*/ << "local";
7371           NewVD->setInvalidDecl();
7372           return;
7373         }
7374         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7375         // in the outermost scope of a kernel function.
7376         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7377           if (!getCurScope()->isFunctionScope()) {
7378             if (T.getAddressSpace() == LangAS::opencl_constant)
7379               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7380                   << "constant";
7381             else
7382               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7383                   << "local";
7384             NewVD->setInvalidDecl();
7385             return;
7386           }
7387         }
7388       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7389         // Do not allow other address spaces on automatic variable.
7390         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7391         NewVD->setInvalidDecl();
7392         return;
7393       }
7394     }
7395   }
7396 
7397   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7398       && !NewVD->hasAttr<BlocksAttr>()) {
7399     if (getLangOpts().getGC() != LangOptions::NonGC)
7400       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7401     else {
7402       assert(!getLangOpts().ObjCAutoRefCount);
7403       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7404     }
7405   }
7406 
7407   bool isVM = T->isVariablyModifiedType();
7408   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7409       NewVD->hasAttr<BlocksAttr>())
7410     getCurFunction()->setHasBranchProtectedScope();
7411 
7412   if ((isVM && NewVD->hasLinkage()) ||
7413       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7414     bool SizeIsNegative;
7415     llvm::APSInt Oversized;
7416     TypeSourceInfo *FixedTInfo =
7417       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7418                                                     SizeIsNegative, Oversized);
7419     if (!FixedTInfo && T->isVariableArrayType()) {
7420       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7421       // FIXME: This won't give the correct result for
7422       // int a[10][n];
7423       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7424 
7425       if (NewVD->isFileVarDecl())
7426         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7427         << SizeRange;
7428       else if (NewVD->isStaticLocal())
7429         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7430         << SizeRange;
7431       else
7432         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7433         << SizeRange;
7434       NewVD->setInvalidDecl();
7435       return;
7436     }
7437 
7438     if (!FixedTInfo) {
7439       if (NewVD->isFileVarDecl())
7440         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7441       else
7442         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7443       NewVD->setInvalidDecl();
7444       return;
7445     }
7446 
7447     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7448     NewVD->setType(FixedTInfo->getType());
7449     NewVD->setTypeSourceInfo(FixedTInfo);
7450   }
7451 
7452   if (T->isVoidType()) {
7453     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7454     //                    of objects and functions.
7455     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7456       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7457         << T;
7458       NewVD->setInvalidDecl();
7459       return;
7460     }
7461   }
7462 
7463   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7464     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7465     NewVD->setInvalidDecl();
7466     return;
7467   }
7468 
7469   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7470     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7471     NewVD->setInvalidDecl();
7472     return;
7473   }
7474 
7475   if (NewVD->isConstexpr() && !T->isDependentType() &&
7476       RequireLiteralType(NewVD->getLocation(), T,
7477                          diag::err_constexpr_var_non_literal)) {
7478     NewVD->setInvalidDecl();
7479     return;
7480   }
7481 }
7482 
7483 /// \brief Perform semantic checking on a newly-created variable
7484 /// declaration.
7485 ///
7486 /// This routine performs all of the type-checking required for a
7487 /// variable declaration once it has been built. It is used both to
7488 /// check variables after they have been parsed and their declarators
7489 /// have been translated into a declaration, and to check variables
7490 /// that have been instantiated from a template.
7491 ///
7492 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7493 ///
7494 /// Returns true if the variable declaration is a redeclaration.
7495 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7496   CheckVariableDeclarationType(NewVD);
7497 
7498   // If the decl is already known invalid, don't check it.
7499   if (NewVD->isInvalidDecl())
7500     return false;
7501 
7502   // If we did not find anything by this name, look for a non-visible
7503   // extern "C" declaration with the same name.
7504   if (Previous.empty() &&
7505       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7506     Previous.setShadowed();
7507 
7508   if (!Previous.empty()) {
7509     MergeVarDecl(NewVD, Previous);
7510     return true;
7511   }
7512   return false;
7513 }
7514 
7515 namespace {
7516 struct FindOverriddenMethod {
7517   Sema *S;
7518   CXXMethodDecl *Method;
7519 
7520   /// Member lookup function that determines whether a given C++
7521   /// method overrides a method in a base class, to be used with
7522   /// CXXRecordDecl::lookupInBases().
7523   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7524     RecordDecl *BaseRecord =
7525         Specifier->getType()->getAs<RecordType>()->getDecl();
7526 
7527     DeclarationName Name = Method->getDeclName();
7528 
7529     // FIXME: Do we care about other names here too?
7530     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7531       // We really want to find the base class destructor here.
7532       QualType T = S->Context.getTypeDeclType(BaseRecord);
7533       CanQualType CT = S->Context.getCanonicalType(T);
7534 
7535       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7536     }
7537 
7538     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7539          Path.Decls = Path.Decls.slice(1)) {
7540       NamedDecl *D = Path.Decls.front();
7541       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7542         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7543           return true;
7544       }
7545     }
7546 
7547     return false;
7548   }
7549 };
7550 
7551 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7552 } // end anonymous namespace
7553 
7554 /// \brief Report an error regarding overriding, along with any relevant
7555 /// overriden methods.
7556 ///
7557 /// \param DiagID the primary error to report.
7558 /// \param MD the overriding method.
7559 /// \param OEK which overrides to include as notes.
7560 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7561                             OverrideErrorKind OEK = OEK_All) {
7562   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7563   for (const CXXMethodDecl *O : MD->overridden_methods()) {
7564     // This check (& the OEK parameter) could be replaced by a predicate, but
7565     // without lambdas that would be overkill. This is still nicer than writing
7566     // out the diag loop 3 times.
7567     if ((OEK == OEK_All) ||
7568         (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7569         (OEK == OEK_Deleted && O->isDeleted()))
7570       S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7571   }
7572 }
7573 
7574 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7575 /// and if so, check that it's a valid override and remember it.
7576 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7577   // Look for methods in base classes that this method might override.
7578   CXXBasePaths Paths;
7579   FindOverriddenMethod FOM;
7580   FOM.Method = MD;
7581   FOM.S = this;
7582   bool hasDeletedOverridenMethods = false;
7583   bool hasNonDeletedOverridenMethods = false;
7584   bool AddedAny = false;
7585   if (DC->lookupInBases(FOM, Paths)) {
7586     for (auto *I : Paths.found_decls()) {
7587       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7588         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7589         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7590             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7591             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7592             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7593           hasDeletedOverridenMethods |= OldMD->isDeleted();
7594           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7595           AddedAny = true;
7596         }
7597       }
7598     }
7599   }
7600 
7601   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7602     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7603   }
7604   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7605     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7606   }
7607 
7608   return AddedAny;
7609 }
7610 
7611 namespace {
7612   // Struct for holding all of the extra arguments needed by
7613   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7614   struct ActOnFDArgs {
7615     Scope *S;
7616     Declarator &D;
7617     MultiTemplateParamsArg TemplateParamLists;
7618     bool AddToScope;
7619   };
7620 } // end anonymous namespace
7621 
7622 namespace {
7623 
7624 // Callback to only accept typo corrections that have a non-zero edit distance.
7625 // Also only accept corrections that have the same parent decl.
7626 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7627  public:
7628   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7629                             CXXRecordDecl *Parent)
7630       : Context(Context), OriginalFD(TypoFD),
7631         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7632 
7633   bool ValidateCandidate(const TypoCorrection &candidate) override {
7634     if (candidate.getEditDistance() == 0)
7635       return false;
7636 
7637     SmallVector<unsigned, 1> MismatchedParams;
7638     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7639                                           CDeclEnd = candidate.end();
7640          CDecl != CDeclEnd; ++CDecl) {
7641       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7642 
7643       if (FD && !FD->hasBody() &&
7644           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7645         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7646           CXXRecordDecl *Parent = MD->getParent();
7647           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7648             return true;
7649         } else if (!ExpectedParent) {
7650           return true;
7651         }
7652       }
7653     }
7654 
7655     return false;
7656   }
7657 
7658  private:
7659   ASTContext &Context;
7660   FunctionDecl *OriginalFD;
7661   CXXRecordDecl *ExpectedParent;
7662 };
7663 
7664 } // end anonymous namespace
7665 
7666 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7667   TypoCorrectedFunctionDefinitions.insert(F);
7668 }
7669 
7670 /// \brief Generate diagnostics for an invalid function redeclaration.
7671 ///
7672 /// This routine handles generating the diagnostic messages for an invalid
7673 /// function redeclaration, including finding possible similar declarations
7674 /// or performing typo correction if there are no previous declarations with
7675 /// the same name.
7676 ///
7677 /// Returns a NamedDecl iff typo correction was performed and substituting in
7678 /// the new declaration name does not cause new errors.
7679 static NamedDecl *DiagnoseInvalidRedeclaration(
7680     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7681     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7682   DeclarationName Name = NewFD->getDeclName();
7683   DeclContext *NewDC = NewFD->getDeclContext();
7684   SmallVector<unsigned, 1> MismatchedParams;
7685   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7686   TypoCorrection Correction;
7687   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7688   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7689                                    : diag::err_member_decl_does_not_match;
7690   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7691                     IsLocalFriend ? Sema::LookupLocalFriendName
7692                                   : Sema::LookupOrdinaryName,
7693                     Sema::ForVisibleRedeclaration);
7694 
7695   NewFD->setInvalidDecl();
7696   if (IsLocalFriend)
7697     SemaRef.LookupName(Prev, S);
7698   else
7699     SemaRef.LookupQualifiedName(Prev, NewDC);
7700   assert(!Prev.isAmbiguous() &&
7701          "Cannot have an ambiguity in previous-declaration lookup");
7702   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7703   if (!Prev.empty()) {
7704     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7705          Func != FuncEnd; ++Func) {
7706       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7707       if (FD &&
7708           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7709         // Add 1 to the index so that 0 can mean the mismatch didn't
7710         // involve a parameter
7711         unsigned ParamNum =
7712             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7713         NearMatches.push_back(std::make_pair(FD, ParamNum));
7714       }
7715     }
7716   // If the qualified name lookup yielded nothing, try typo correction
7717   } else if ((Correction = SemaRef.CorrectTypo(
7718                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7719                   &ExtraArgs.D.getCXXScopeSpec(),
7720                   llvm::make_unique<DifferentNameValidatorCCC>(
7721                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7722                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7723     // Set up everything for the call to ActOnFunctionDeclarator
7724     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7725                               ExtraArgs.D.getIdentifierLoc());
7726     Previous.clear();
7727     Previous.setLookupName(Correction.getCorrection());
7728     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7729                                     CDeclEnd = Correction.end();
7730          CDecl != CDeclEnd; ++CDecl) {
7731       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7732       if (FD && !FD->hasBody() &&
7733           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7734         Previous.addDecl(FD);
7735       }
7736     }
7737     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7738 
7739     NamedDecl *Result;
7740     // Retry building the function declaration with the new previous
7741     // declarations, and with errors suppressed.
7742     {
7743       // Trap errors.
7744       Sema::SFINAETrap Trap(SemaRef);
7745 
7746       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7747       // pieces need to verify the typo-corrected C++ declaration and hopefully
7748       // eliminate the need for the parameter pack ExtraArgs.
7749       Result = SemaRef.ActOnFunctionDeclarator(
7750           ExtraArgs.S, ExtraArgs.D,
7751           Correction.getCorrectionDecl()->getDeclContext(),
7752           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7753           ExtraArgs.AddToScope);
7754 
7755       if (Trap.hasErrorOccurred())
7756         Result = nullptr;
7757     }
7758 
7759     if (Result) {
7760       // Determine which correction we picked.
7761       Decl *Canonical = Result->getCanonicalDecl();
7762       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7763            I != E; ++I)
7764         if ((*I)->getCanonicalDecl() == Canonical)
7765           Correction.setCorrectionDecl(*I);
7766 
7767       // Let Sema know about the correction.
7768       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7769       SemaRef.diagnoseTypo(
7770           Correction,
7771           SemaRef.PDiag(IsLocalFriend
7772                           ? diag::err_no_matching_local_friend_suggest
7773                           : diag::err_member_decl_does_not_match_suggest)
7774             << Name << NewDC << IsDefinition);
7775       return Result;
7776     }
7777 
7778     // Pretend the typo correction never occurred
7779     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7780                               ExtraArgs.D.getIdentifierLoc());
7781     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7782     Previous.clear();
7783     Previous.setLookupName(Name);
7784   }
7785 
7786   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7787       << Name << NewDC << IsDefinition << NewFD->getLocation();
7788 
7789   bool NewFDisConst = false;
7790   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7791     NewFDisConst = NewMD->isConst();
7792 
7793   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7794        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7795        NearMatch != NearMatchEnd; ++NearMatch) {
7796     FunctionDecl *FD = NearMatch->first;
7797     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7798     bool FDisConst = MD && MD->isConst();
7799     bool IsMember = MD || !IsLocalFriend;
7800 
7801     // FIXME: These notes are poorly worded for the local friend case.
7802     if (unsigned Idx = NearMatch->second) {
7803       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7804       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7805       if (Loc.isInvalid()) Loc = FD->getLocation();
7806       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7807                                  : diag::note_local_decl_close_param_match)
7808         << Idx << FDParam->getType()
7809         << NewFD->getParamDecl(Idx - 1)->getType();
7810     } else if (FDisConst != NewFDisConst) {
7811       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7812           << NewFDisConst << FD->getSourceRange().getEnd();
7813     } else
7814       SemaRef.Diag(FD->getLocation(),
7815                    IsMember ? diag::note_member_def_close_match
7816                             : diag::note_local_decl_close_match);
7817   }
7818   return nullptr;
7819 }
7820 
7821 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7822   switch (D.getDeclSpec().getStorageClassSpec()) {
7823   default: llvm_unreachable("Unknown storage class!");
7824   case DeclSpec::SCS_auto:
7825   case DeclSpec::SCS_register:
7826   case DeclSpec::SCS_mutable:
7827     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7828                  diag::err_typecheck_sclass_func);
7829     D.getMutableDeclSpec().ClearStorageClassSpecs();
7830     D.setInvalidType();
7831     break;
7832   case DeclSpec::SCS_unspecified: break;
7833   case DeclSpec::SCS_extern:
7834     if (D.getDeclSpec().isExternInLinkageSpec())
7835       return SC_None;
7836     return SC_Extern;
7837   case DeclSpec::SCS_static: {
7838     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7839       // C99 6.7.1p5:
7840       //   The declaration of an identifier for a function that has
7841       //   block scope shall have no explicit storage-class specifier
7842       //   other than extern
7843       // See also (C++ [dcl.stc]p4).
7844       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7845                    diag::err_static_block_func);
7846       break;
7847     } else
7848       return SC_Static;
7849   }
7850   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7851   }
7852 
7853   // No explicit storage class has already been returned
7854   return SC_None;
7855 }
7856 
7857 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7858                                            DeclContext *DC, QualType &R,
7859                                            TypeSourceInfo *TInfo,
7860                                            StorageClass SC,
7861                                            bool &IsVirtualOkay) {
7862   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7863   DeclarationName Name = NameInfo.getName();
7864 
7865   FunctionDecl *NewFD = nullptr;
7866   bool isInline = D.getDeclSpec().isInlineSpecified();
7867 
7868   if (!SemaRef.getLangOpts().CPlusPlus) {
7869     // Determine whether the function was written with a
7870     // prototype. This true when:
7871     //   - there is a prototype in the declarator, or
7872     //   - the type R of the function is some kind of typedef or other non-
7873     //     attributed reference to a type name (which eventually refers to a
7874     //     function type).
7875     bool HasPrototype =
7876       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7877       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7878 
7879     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7880                                  D.getLocStart(), NameInfo, R,
7881                                  TInfo, SC, isInline,
7882                                  HasPrototype, false);
7883     if (D.isInvalidType())
7884       NewFD->setInvalidDecl();
7885 
7886     return NewFD;
7887   }
7888 
7889   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7890   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7891 
7892   // Check that the return type is not an abstract class type.
7893   // For record types, this is done by the AbstractClassUsageDiagnoser once
7894   // the class has been completely parsed.
7895   if (!DC->isRecord() &&
7896       SemaRef.RequireNonAbstractType(
7897           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7898           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7899     D.setInvalidType();
7900 
7901   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7902     // This is a C++ constructor declaration.
7903     assert(DC->isRecord() &&
7904            "Constructors can only be declared in a member context");
7905 
7906     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7907     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7908                                       D.getLocStart(), NameInfo,
7909                                       R, TInfo, isExplicit, isInline,
7910                                       /*isImplicitlyDeclared=*/false,
7911                                       isConstexpr);
7912 
7913   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7914     // This is a C++ destructor declaration.
7915     if (DC->isRecord()) {
7916       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7917       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7918       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7919                                         SemaRef.Context, Record,
7920                                         D.getLocStart(),
7921                                         NameInfo, R, TInfo, isInline,
7922                                         /*isImplicitlyDeclared=*/false);
7923 
7924       // If the class is complete, then we now create the implicit exception
7925       // specification. If the class is incomplete or dependent, we can't do
7926       // it yet.
7927       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7928           Record->getDefinition() && !Record->isBeingDefined() &&
7929           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7930         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7931       }
7932 
7933       IsVirtualOkay = true;
7934       return NewDD;
7935 
7936     } else {
7937       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7938       D.setInvalidType();
7939 
7940       // Create a FunctionDecl to satisfy the function definition parsing
7941       // code path.
7942       return FunctionDecl::Create(SemaRef.Context, DC,
7943                                   D.getLocStart(),
7944                                   D.getIdentifierLoc(), Name, R, TInfo,
7945                                   SC, isInline,
7946                                   /*hasPrototype=*/true, isConstexpr);
7947     }
7948 
7949   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7950     if (!DC->isRecord()) {
7951       SemaRef.Diag(D.getIdentifierLoc(),
7952            diag::err_conv_function_not_member);
7953       return nullptr;
7954     }
7955 
7956     SemaRef.CheckConversionDeclarator(D, R, SC);
7957     IsVirtualOkay = true;
7958     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7959                                      D.getLocStart(), NameInfo,
7960                                      R, TInfo, isInline, isExplicit,
7961                                      isConstexpr, SourceLocation());
7962 
7963   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7964     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7965 
7966     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7967                                          isExplicit, NameInfo, R, TInfo,
7968                                          D.getLocEnd());
7969   } else if (DC->isRecord()) {
7970     // If the name of the function is the same as the name of the record,
7971     // then this must be an invalid constructor that has a return type.
7972     // (The parser checks for a return type and makes the declarator a
7973     // constructor if it has no return type).
7974     if (Name.getAsIdentifierInfo() &&
7975         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7976       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7977         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7978         << SourceRange(D.getIdentifierLoc());
7979       return nullptr;
7980     }
7981 
7982     // This is a C++ method declaration.
7983     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7984                                                cast<CXXRecordDecl>(DC),
7985                                                D.getLocStart(), NameInfo, R,
7986                                                TInfo, SC, isInline,
7987                                                isConstexpr, SourceLocation());
7988     IsVirtualOkay = !Ret->isStatic();
7989     return Ret;
7990   } else {
7991     bool isFriend =
7992         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7993     if (!isFriend && SemaRef.CurContext->isRecord())
7994       return nullptr;
7995 
7996     // Determine whether the function was written with a
7997     // prototype. This true when:
7998     //   - we're in C++ (where every function has a prototype),
7999     return FunctionDecl::Create(SemaRef.Context, DC,
8000                                 D.getLocStart(),
8001                                 NameInfo, R, TInfo, SC, isInline,
8002                                 true/*HasPrototype*/, isConstexpr);
8003   }
8004 }
8005 
8006 enum OpenCLParamType {
8007   ValidKernelParam,
8008   PtrPtrKernelParam,
8009   PtrKernelParam,
8010   InvalidAddrSpacePtrKernelParam,
8011   InvalidKernelParam,
8012   RecordKernelParam
8013 };
8014 
8015 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8016   if (PT->isPointerType()) {
8017     QualType PointeeType = PT->getPointeeType();
8018     if (PointeeType->isPointerType())
8019       return PtrPtrKernelParam;
8020     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8021         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8022         PointeeType.getAddressSpace() == LangAS::Default)
8023       return InvalidAddrSpacePtrKernelParam;
8024     return PtrKernelParam;
8025   }
8026 
8027   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8028   // be used as builtin types.
8029 
8030   if (PT->isImageType())
8031     return PtrKernelParam;
8032 
8033   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8034     return InvalidKernelParam;
8035 
8036   // OpenCL extension spec v1.2 s9.5:
8037   // This extension adds support for half scalar and vector types as built-in
8038   // types that can be used for arithmetic operations, conversions etc.
8039   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8040     return InvalidKernelParam;
8041 
8042   if (PT->isRecordType())
8043     return RecordKernelParam;
8044 
8045   return ValidKernelParam;
8046 }
8047 
8048 static void checkIsValidOpenCLKernelParameter(
8049   Sema &S,
8050   Declarator &D,
8051   ParmVarDecl *Param,
8052   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8053   QualType PT = Param->getType();
8054 
8055   // Cache the valid types we encounter to avoid rechecking structs that are
8056   // used again
8057   if (ValidTypes.count(PT.getTypePtr()))
8058     return;
8059 
8060   switch (getOpenCLKernelParameterType(S, PT)) {
8061   case PtrPtrKernelParam:
8062     // OpenCL v1.2 s6.9.a:
8063     // A kernel function argument cannot be declared as a
8064     // pointer to a pointer type.
8065     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8066     D.setInvalidType();
8067     return;
8068 
8069   case InvalidAddrSpacePtrKernelParam:
8070     // OpenCL v1.0 s6.5:
8071     // __kernel function arguments declared to be a pointer of a type can point
8072     // to one of the following address spaces only : __global, __local or
8073     // __constant.
8074     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8075     D.setInvalidType();
8076     return;
8077 
8078     // OpenCL v1.2 s6.9.k:
8079     // Arguments to kernel functions in a program cannot be declared with the
8080     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8081     // uintptr_t or a struct and/or union that contain fields declared to be
8082     // one of these built-in scalar types.
8083 
8084   case InvalidKernelParam:
8085     // OpenCL v1.2 s6.8 n:
8086     // A kernel function argument cannot be declared
8087     // of event_t type.
8088     // Do not diagnose half type since it is diagnosed as invalid argument
8089     // type for any function elsewhere.
8090     if (!PT->isHalfType())
8091       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8092     D.setInvalidType();
8093     return;
8094 
8095   case PtrKernelParam:
8096   case ValidKernelParam:
8097     ValidTypes.insert(PT.getTypePtr());
8098     return;
8099 
8100   case RecordKernelParam:
8101     break;
8102   }
8103 
8104   // Track nested structs we will inspect
8105   SmallVector<const Decl *, 4> VisitStack;
8106 
8107   // Track where we are in the nested structs. Items will migrate from
8108   // VisitStack to HistoryStack as we do the DFS for bad field.
8109   SmallVector<const FieldDecl *, 4> HistoryStack;
8110   HistoryStack.push_back(nullptr);
8111 
8112   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8113   VisitStack.push_back(PD);
8114 
8115   assert(VisitStack.back() && "First decl null?");
8116 
8117   do {
8118     const Decl *Next = VisitStack.pop_back_val();
8119     if (!Next) {
8120       assert(!HistoryStack.empty());
8121       // Found a marker, we have gone up a level
8122       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8123         ValidTypes.insert(Hist->getType().getTypePtr());
8124 
8125       continue;
8126     }
8127 
8128     // Adds everything except the original parameter declaration (which is not a
8129     // field itself) to the history stack.
8130     const RecordDecl *RD;
8131     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8132       HistoryStack.push_back(Field);
8133       RD = Field->getType()->castAs<RecordType>()->getDecl();
8134     } else {
8135       RD = cast<RecordDecl>(Next);
8136     }
8137 
8138     // Add a null marker so we know when we've gone back up a level
8139     VisitStack.push_back(nullptr);
8140 
8141     for (const auto *FD : RD->fields()) {
8142       QualType QT = FD->getType();
8143 
8144       if (ValidTypes.count(QT.getTypePtr()))
8145         continue;
8146 
8147       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8148       if (ParamType == ValidKernelParam)
8149         continue;
8150 
8151       if (ParamType == RecordKernelParam) {
8152         VisitStack.push_back(FD);
8153         continue;
8154       }
8155 
8156       // OpenCL v1.2 s6.9.p:
8157       // Arguments to kernel functions that are declared to be a struct or union
8158       // do not allow OpenCL objects to be passed as elements of the struct or
8159       // union.
8160       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8161           ParamType == InvalidAddrSpacePtrKernelParam) {
8162         S.Diag(Param->getLocation(),
8163                diag::err_record_with_pointers_kernel_param)
8164           << PT->isUnionType()
8165           << PT;
8166       } else {
8167         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8168       }
8169 
8170       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8171         << PD->getDeclName();
8172 
8173       // We have an error, now let's go back up through history and show where
8174       // the offending field came from
8175       for (ArrayRef<const FieldDecl *>::const_iterator
8176                I = HistoryStack.begin() + 1,
8177                E = HistoryStack.end();
8178            I != E; ++I) {
8179         const FieldDecl *OuterField = *I;
8180         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8181           << OuterField->getType();
8182       }
8183 
8184       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8185         << QT->isPointerType()
8186         << QT;
8187       D.setInvalidType();
8188       return;
8189     }
8190   } while (!VisitStack.empty());
8191 }
8192 
8193 /// Find the DeclContext in which a tag is implicitly declared if we see an
8194 /// elaborated type specifier in the specified context, and lookup finds
8195 /// nothing.
8196 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8197   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8198     DC = DC->getParent();
8199   return DC;
8200 }
8201 
8202 /// Find the Scope in which a tag is implicitly declared if we see an
8203 /// elaborated type specifier in the specified context, and lookup finds
8204 /// nothing.
8205 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8206   while (S->isClassScope() ||
8207          (LangOpts.CPlusPlus &&
8208           S->isFunctionPrototypeScope()) ||
8209          ((S->getFlags() & Scope::DeclScope) == 0) ||
8210          (S->getEntity() && S->getEntity()->isTransparentContext()))
8211     S = S->getParent();
8212   return S;
8213 }
8214 
8215 NamedDecl*
8216 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8217                               TypeSourceInfo *TInfo, LookupResult &Previous,
8218                               MultiTemplateParamsArg TemplateParamLists,
8219                               bool &AddToScope) {
8220   QualType R = TInfo->getType();
8221 
8222   assert(R.getTypePtr()->isFunctionType());
8223 
8224   // TODO: consider using NameInfo for diagnostic.
8225   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8226   DeclarationName Name = NameInfo.getName();
8227   StorageClass SC = getFunctionStorageClass(*this, D);
8228 
8229   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8230     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8231          diag::err_invalid_thread)
8232       << DeclSpec::getSpecifierName(TSCS);
8233 
8234   if (D.isFirstDeclarationOfMember())
8235     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8236                            D.getIdentifierLoc());
8237 
8238   bool isFriend = false;
8239   FunctionTemplateDecl *FunctionTemplate = nullptr;
8240   bool isMemberSpecialization = false;
8241   bool isFunctionTemplateSpecialization = false;
8242 
8243   bool isDependentClassScopeExplicitSpecialization = false;
8244   bool HasExplicitTemplateArgs = false;
8245   TemplateArgumentListInfo TemplateArgs;
8246 
8247   bool isVirtualOkay = false;
8248 
8249   DeclContext *OriginalDC = DC;
8250   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8251 
8252   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8253                                               isVirtualOkay);
8254   if (!NewFD) return nullptr;
8255 
8256   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8257     NewFD->setTopLevelDeclInObjCContainer();
8258 
8259   // Set the lexical context. If this is a function-scope declaration, or has a
8260   // C++ scope specifier, or is the object of a friend declaration, the lexical
8261   // context will be different from the semantic context.
8262   NewFD->setLexicalDeclContext(CurContext);
8263 
8264   if (IsLocalExternDecl)
8265     NewFD->setLocalExternDecl();
8266 
8267   if (getLangOpts().CPlusPlus) {
8268     bool isInline = D.getDeclSpec().isInlineSpecified();
8269     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8270     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8271     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8272     isFriend = D.getDeclSpec().isFriendSpecified();
8273     if (isFriend && !isInline && D.isFunctionDefinition()) {
8274       // C++ [class.friend]p5
8275       //   A function can be defined in a friend declaration of a
8276       //   class . . . . Such a function is implicitly inline.
8277       NewFD->setImplicitlyInline();
8278     }
8279 
8280     // If this is a method defined in an __interface, and is not a constructor
8281     // or an overloaded operator, then set the pure flag (isVirtual will already
8282     // return true).
8283     if (const CXXRecordDecl *Parent =
8284           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8285       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8286         NewFD->setPure(true);
8287 
8288       // C++ [class.union]p2
8289       //   A union can have member functions, but not virtual functions.
8290       if (isVirtual && Parent->isUnion())
8291         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8292     }
8293 
8294     SetNestedNameSpecifier(NewFD, D);
8295     isMemberSpecialization = false;
8296     isFunctionTemplateSpecialization = false;
8297     if (D.isInvalidType())
8298       NewFD->setInvalidDecl();
8299 
8300     // Match up the template parameter lists with the scope specifier, then
8301     // determine whether we have a template or a template specialization.
8302     bool Invalid = false;
8303     if (TemplateParameterList *TemplateParams =
8304             MatchTemplateParametersToScopeSpecifier(
8305                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8306                 D.getCXXScopeSpec(),
8307                 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8308                     ? D.getName().TemplateId
8309                     : nullptr,
8310                 TemplateParamLists, isFriend, isMemberSpecialization,
8311                 Invalid)) {
8312       if (TemplateParams->size() > 0) {
8313         // This is a function template
8314 
8315         // Check that we can declare a template here.
8316         if (CheckTemplateDeclScope(S, TemplateParams))
8317           NewFD->setInvalidDecl();
8318 
8319         // A destructor cannot be a template.
8320         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8321           Diag(NewFD->getLocation(), diag::err_destructor_template);
8322           NewFD->setInvalidDecl();
8323         }
8324 
8325         // If we're adding a template to a dependent context, we may need to
8326         // rebuilding some of the types used within the template parameter list,
8327         // now that we know what the current instantiation is.
8328         if (DC->isDependentContext()) {
8329           ContextRAII SavedContext(*this, DC);
8330           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8331             Invalid = true;
8332         }
8333 
8334         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8335                                                         NewFD->getLocation(),
8336                                                         Name, TemplateParams,
8337                                                         NewFD);
8338         FunctionTemplate->setLexicalDeclContext(CurContext);
8339         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8340 
8341         // For source fidelity, store the other template param lists.
8342         if (TemplateParamLists.size() > 1) {
8343           NewFD->setTemplateParameterListsInfo(Context,
8344                                                TemplateParamLists.drop_back(1));
8345         }
8346       } else {
8347         // This is a function template specialization.
8348         isFunctionTemplateSpecialization = true;
8349         // For source fidelity, store all the template param lists.
8350         if (TemplateParamLists.size() > 0)
8351           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8352 
8353         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8354         if (isFriend) {
8355           // We want to remove the "template<>", found here.
8356           SourceRange RemoveRange = TemplateParams->getSourceRange();
8357 
8358           // If we remove the template<> and the name is not a
8359           // template-id, we're actually silently creating a problem:
8360           // the friend declaration will refer to an untemplated decl,
8361           // and clearly the user wants a template specialization.  So
8362           // we need to insert '<>' after the name.
8363           SourceLocation InsertLoc;
8364           if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8365             InsertLoc = D.getName().getSourceRange().getEnd();
8366             InsertLoc = getLocForEndOfToken(InsertLoc);
8367           }
8368 
8369           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8370             << Name << RemoveRange
8371             << FixItHint::CreateRemoval(RemoveRange)
8372             << FixItHint::CreateInsertion(InsertLoc, "<>");
8373         }
8374       }
8375     }
8376     else {
8377       // All template param lists were matched against the scope specifier:
8378       // this is NOT (an explicit specialization of) a template.
8379       if (TemplateParamLists.size() > 0)
8380         // For source fidelity, store all the template param lists.
8381         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8382     }
8383 
8384     if (Invalid) {
8385       NewFD->setInvalidDecl();
8386       if (FunctionTemplate)
8387         FunctionTemplate->setInvalidDecl();
8388     }
8389 
8390     // C++ [dcl.fct.spec]p5:
8391     //   The virtual specifier shall only be used in declarations of
8392     //   nonstatic class member functions that appear within a
8393     //   member-specification of a class declaration; see 10.3.
8394     //
8395     if (isVirtual && !NewFD->isInvalidDecl()) {
8396       if (!isVirtualOkay) {
8397         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8398              diag::err_virtual_non_function);
8399       } else if (!CurContext->isRecord()) {
8400         // 'virtual' was specified outside of the class.
8401         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8402              diag::err_virtual_out_of_class)
8403           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8404       } else if (NewFD->getDescribedFunctionTemplate()) {
8405         // C++ [temp.mem]p3:
8406         //  A member function template shall not be virtual.
8407         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8408              diag::err_virtual_member_function_template)
8409           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8410       } else {
8411         // Okay: Add virtual to the method.
8412         NewFD->setVirtualAsWritten(true);
8413       }
8414 
8415       if (getLangOpts().CPlusPlus14 &&
8416           NewFD->getReturnType()->isUndeducedType())
8417         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8418     }
8419 
8420     if (getLangOpts().CPlusPlus14 &&
8421         (NewFD->isDependentContext() ||
8422          (isFriend && CurContext->isDependentContext())) &&
8423         NewFD->getReturnType()->isUndeducedType()) {
8424       // If the function template is referenced directly (for instance, as a
8425       // member of the current instantiation), pretend it has a dependent type.
8426       // This is not really justified by the standard, but is the only sane
8427       // thing to do.
8428       // FIXME: For a friend function, we have not marked the function as being
8429       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8430       const FunctionProtoType *FPT =
8431           NewFD->getType()->castAs<FunctionProtoType>();
8432       QualType Result =
8433           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8434       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8435                                              FPT->getExtProtoInfo()));
8436     }
8437 
8438     // C++ [dcl.fct.spec]p3:
8439     //  The inline specifier shall not appear on a block scope function
8440     //  declaration.
8441     if (isInline && !NewFD->isInvalidDecl()) {
8442       if (CurContext->isFunctionOrMethod()) {
8443         // 'inline' is not allowed on block scope function declaration.
8444         Diag(D.getDeclSpec().getInlineSpecLoc(),
8445              diag::err_inline_declaration_block_scope) << Name
8446           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8447       }
8448     }
8449 
8450     // C++ [dcl.fct.spec]p6:
8451     //  The explicit specifier shall be used only in the declaration of a
8452     //  constructor or conversion function within its class definition;
8453     //  see 12.3.1 and 12.3.2.
8454     if (isExplicit && !NewFD->isInvalidDecl() &&
8455         !isa<CXXDeductionGuideDecl>(NewFD)) {
8456       if (!CurContext->isRecord()) {
8457         // 'explicit' was specified outside of the class.
8458         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8459              diag::err_explicit_out_of_class)
8460           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8461       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8462                  !isa<CXXConversionDecl>(NewFD)) {
8463         // 'explicit' was specified on a function that wasn't a constructor
8464         // or conversion function.
8465         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8466              diag::err_explicit_non_ctor_or_conv_function)
8467           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8468       }
8469     }
8470 
8471     if (isConstexpr) {
8472       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8473       // are implicitly inline.
8474       NewFD->setImplicitlyInline();
8475 
8476       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8477       // be either constructors or to return a literal type. Therefore,
8478       // destructors cannot be declared constexpr.
8479       if (isa<CXXDestructorDecl>(NewFD))
8480         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8481     }
8482 
8483     // If __module_private__ was specified, mark the function accordingly.
8484     if (D.getDeclSpec().isModulePrivateSpecified()) {
8485       if (isFunctionTemplateSpecialization) {
8486         SourceLocation ModulePrivateLoc
8487           = D.getDeclSpec().getModulePrivateSpecLoc();
8488         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8489           << 0
8490           << FixItHint::CreateRemoval(ModulePrivateLoc);
8491       } else {
8492         NewFD->setModulePrivate();
8493         if (FunctionTemplate)
8494           FunctionTemplate->setModulePrivate();
8495       }
8496     }
8497 
8498     if (isFriend) {
8499       if (FunctionTemplate) {
8500         FunctionTemplate->setObjectOfFriendDecl();
8501         FunctionTemplate->setAccess(AS_public);
8502       }
8503       NewFD->setObjectOfFriendDecl();
8504       NewFD->setAccess(AS_public);
8505     }
8506 
8507     // If a function is defined as defaulted or deleted, mark it as such now.
8508     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8509     // definition kind to FDK_Definition.
8510     switch (D.getFunctionDefinitionKind()) {
8511       case FDK_Declaration:
8512       case FDK_Definition:
8513         break;
8514 
8515       case FDK_Defaulted:
8516         NewFD->setDefaulted();
8517         break;
8518 
8519       case FDK_Deleted:
8520         NewFD->setDeletedAsWritten();
8521         break;
8522     }
8523 
8524     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8525         D.isFunctionDefinition()) {
8526       // C++ [class.mfct]p2:
8527       //   A member function may be defined (8.4) in its class definition, in
8528       //   which case it is an inline member function (7.1.2)
8529       NewFD->setImplicitlyInline();
8530     }
8531 
8532     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8533         !CurContext->isRecord()) {
8534       // C++ [class.static]p1:
8535       //   A data or function member of a class may be declared static
8536       //   in a class definition, in which case it is a static member of
8537       //   the class.
8538 
8539       // Complain about the 'static' specifier if it's on an out-of-line
8540       // member function definition.
8541       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8542            diag::err_static_out_of_line)
8543         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8544     }
8545 
8546     // C++11 [except.spec]p15:
8547     //   A deallocation function with no exception-specification is treated
8548     //   as if it were specified with noexcept(true).
8549     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8550     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8551          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8552         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8553       NewFD->setType(Context.getFunctionType(
8554           FPT->getReturnType(), FPT->getParamTypes(),
8555           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8556   }
8557 
8558   // Filter out previous declarations that don't match the scope.
8559   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8560                        D.getCXXScopeSpec().isNotEmpty() ||
8561                        isMemberSpecialization ||
8562                        isFunctionTemplateSpecialization);
8563 
8564   // Handle GNU asm-label extension (encoded as an attribute).
8565   if (Expr *E = (Expr*) D.getAsmLabel()) {
8566     // The parser guarantees this is a string.
8567     StringLiteral *SE = cast<StringLiteral>(E);
8568     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8569                                                 SE->getString(), 0));
8570   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8571     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8572       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8573     if (I != ExtnameUndeclaredIdentifiers.end()) {
8574       if (isDeclExternC(NewFD)) {
8575         NewFD->addAttr(I->second);
8576         ExtnameUndeclaredIdentifiers.erase(I);
8577       } else
8578         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8579             << /*Variable*/0 << NewFD;
8580     }
8581   }
8582 
8583   // Copy the parameter declarations from the declarator D to the function
8584   // declaration NewFD, if they are available.  First scavenge them into Params.
8585   SmallVector<ParmVarDecl*, 16> Params;
8586   unsigned FTIIdx;
8587   if (D.isFunctionDeclarator(FTIIdx)) {
8588     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8589 
8590     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8591     // function that takes no arguments, not a function that takes a
8592     // single void argument.
8593     // We let through "const void" here because Sema::GetTypeForDeclarator
8594     // already checks for that case.
8595     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8596       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8597         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8598         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8599         Param->setDeclContext(NewFD);
8600         Params.push_back(Param);
8601 
8602         if (Param->isInvalidDecl())
8603           NewFD->setInvalidDecl();
8604       }
8605     }
8606 
8607     if (!getLangOpts().CPlusPlus) {
8608       // In C, find all the tag declarations from the prototype and move them
8609       // into the function DeclContext. Remove them from the surrounding tag
8610       // injection context of the function, which is typically but not always
8611       // the TU.
8612       DeclContext *PrototypeTagContext =
8613           getTagInjectionContext(NewFD->getLexicalDeclContext());
8614       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8615         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8616 
8617         // We don't want to reparent enumerators. Look at their parent enum
8618         // instead.
8619         if (!TD) {
8620           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8621             TD = cast<EnumDecl>(ECD->getDeclContext());
8622         }
8623         if (!TD)
8624           continue;
8625         DeclContext *TagDC = TD->getLexicalDeclContext();
8626         if (!TagDC->containsDecl(TD))
8627           continue;
8628         TagDC->removeDecl(TD);
8629         TD->setDeclContext(NewFD);
8630         NewFD->addDecl(TD);
8631 
8632         // Preserve the lexical DeclContext if it is not the surrounding tag
8633         // injection context of the FD. In this example, the semantic context of
8634         // E will be f and the lexical context will be S, while both the
8635         // semantic and lexical contexts of S will be f:
8636         //   void f(struct S { enum E { a } f; } s);
8637         if (TagDC != PrototypeTagContext)
8638           TD->setLexicalDeclContext(TagDC);
8639       }
8640     }
8641   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8642     // When we're declaring a function with a typedef, typeof, etc as in the
8643     // following example, we'll need to synthesize (unnamed)
8644     // parameters for use in the declaration.
8645     //
8646     // @code
8647     // typedef void fn(int);
8648     // fn f;
8649     // @endcode
8650 
8651     // Synthesize a parameter for each argument type.
8652     for (const auto &AI : FT->param_types()) {
8653       ParmVarDecl *Param =
8654           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8655       Param->setScopeInfo(0, Params.size());
8656       Params.push_back(Param);
8657     }
8658   } else {
8659     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8660            "Should not need args for typedef of non-prototype fn");
8661   }
8662 
8663   // Finally, we know we have the right number of parameters, install them.
8664   NewFD->setParams(Params);
8665 
8666   if (D.getDeclSpec().isNoreturnSpecified())
8667     NewFD->addAttr(
8668         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8669                                        Context, 0));
8670 
8671   // Functions returning a variably modified type violate C99 6.7.5.2p2
8672   // because all functions have linkage.
8673   if (!NewFD->isInvalidDecl() &&
8674       NewFD->getReturnType()->isVariablyModifiedType()) {
8675     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8676     NewFD->setInvalidDecl();
8677   }
8678 
8679   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8680   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8681       !NewFD->hasAttr<SectionAttr>()) {
8682     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8683                                                  PragmaClangTextSection.SectionName,
8684                                                  PragmaClangTextSection.PragmaLocation));
8685   }
8686 
8687   // Apply an implicit SectionAttr if #pragma code_seg is active.
8688   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8689       !NewFD->hasAttr<SectionAttr>()) {
8690     NewFD->addAttr(
8691         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8692                                     CodeSegStack.CurrentValue->getString(),
8693                                     CodeSegStack.CurrentPragmaLocation));
8694     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8695                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8696                          ASTContext::PSF_Read,
8697                      NewFD))
8698       NewFD->dropAttr<SectionAttr>();
8699   }
8700 
8701   // Handle attributes.
8702   ProcessDeclAttributes(S, NewFD, D);
8703 
8704   if (getLangOpts().OpenCL) {
8705     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8706     // type declaration will generate a compilation error.
8707     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8708     if (AddressSpace != LangAS::Default) {
8709       Diag(NewFD->getLocation(),
8710            diag::err_opencl_return_value_with_address_space);
8711       NewFD->setInvalidDecl();
8712     }
8713   }
8714 
8715   if (!getLangOpts().CPlusPlus) {
8716     // Perform semantic checking on the function declaration.
8717     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8718       CheckMain(NewFD, D.getDeclSpec());
8719 
8720     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8721       CheckMSVCRTEntryPoint(NewFD);
8722 
8723     if (!NewFD->isInvalidDecl())
8724       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8725                                                   isMemberSpecialization));
8726     else if (!Previous.empty())
8727       // Recover gracefully from an invalid redeclaration.
8728       D.setRedeclaration(true);
8729     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8730             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8731            "previous declaration set still overloaded");
8732 
8733     // Diagnose no-prototype function declarations with calling conventions that
8734     // don't support variadic calls. Only do this in C and do it after merging
8735     // possibly prototyped redeclarations.
8736     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8737     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8738       CallingConv CC = FT->getExtInfo().getCC();
8739       if (!supportsVariadicCall(CC)) {
8740         // Windows system headers sometimes accidentally use stdcall without
8741         // (void) parameters, so we relax this to a warning.
8742         int DiagID =
8743             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8744         Diag(NewFD->getLocation(), DiagID)
8745             << FunctionType::getNameForCallConv(CC);
8746       }
8747     }
8748   } else {
8749     // C++11 [replacement.functions]p3:
8750     //  The program's definitions shall not be specified as inline.
8751     //
8752     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8753     //
8754     // Suppress the diagnostic if the function is __attribute__((used)), since
8755     // that forces an external definition to be emitted.
8756     if (D.getDeclSpec().isInlineSpecified() &&
8757         NewFD->isReplaceableGlobalAllocationFunction() &&
8758         !NewFD->hasAttr<UsedAttr>())
8759       Diag(D.getDeclSpec().getInlineSpecLoc(),
8760            diag::ext_operator_new_delete_declared_inline)
8761         << NewFD->getDeclName();
8762 
8763     // If the declarator is a template-id, translate the parser's template
8764     // argument list into our AST format.
8765     if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8766       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8767       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8768       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8769       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8770                                          TemplateId->NumArgs);
8771       translateTemplateArguments(TemplateArgsPtr,
8772                                  TemplateArgs);
8773 
8774       HasExplicitTemplateArgs = true;
8775 
8776       if (NewFD->isInvalidDecl()) {
8777         HasExplicitTemplateArgs = false;
8778       } else if (FunctionTemplate) {
8779         // Function template with explicit template arguments.
8780         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8781           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8782 
8783         HasExplicitTemplateArgs = false;
8784       } else {
8785         assert((isFunctionTemplateSpecialization ||
8786                 D.getDeclSpec().isFriendSpecified()) &&
8787                "should have a 'template<>' for this decl");
8788         // "friend void foo<>(int);" is an implicit specialization decl.
8789         isFunctionTemplateSpecialization = true;
8790       }
8791     } else if (isFriend && isFunctionTemplateSpecialization) {
8792       // This combination is only possible in a recovery case;  the user
8793       // wrote something like:
8794       //   template <> friend void foo(int);
8795       // which we're recovering from as if the user had written:
8796       //   friend void foo<>(int);
8797       // Go ahead and fake up a template id.
8798       HasExplicitTemplateArgs = true;
8799       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8800       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8801     }
8802 
8803     // We do not add HD attributes to specializations here because
8804     // they may have different constexpr-ness compared to their
8805     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8806     // may end up with different effective targets. Instead, a
8807     // specialization inherits its target attributes from its template
8808     // in the CheckFunctionTemplateSpecialization() call below.
8809     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8810       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8811 
8812     // If it's a friend (and only if it's a friend), it's possible
8813     // that either the specialized function type or the specialized
8814     // template is dependent, and therefore matching will fail.  In
8815     // this case, don't check the specialization yet.
8816     bool InstantiationDependent = false;
8817     if (isFunctionTemplateSpecialization && isFriend &&
8818         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8819          TemplateSpecializationType::anyDependentTemplateArguments(
8820             TemplateArgs,
8821             InstantiationDependent))) {
8822       assert(HasExplicitTemplateArgs &&
8823              "friend function specialization without template args");
8824       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8825                                                        Previous))
8826         NewFD->setInvalidDecl();
8827     } else if (isFunctionTemplateSpecialization) {
8828       if (CurContext->isDependentContext() && CurContext->isRecord()
8829           && !isFriend) {
8830         isDependentClassScopeExplicitSpecialization = true;
8831         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8832           diag::ext_function_specialization_in_class :
8833           diag::err_function_specialization_in_class)
8834           << NewFD->getDeclName();
8835       } else if (!NewFD->isInvalidDecl() &&
8836                  CheckFunctionTemplateSpecialization(
8837                      NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8838                      Previous))
8839         NewFD->setInvalidDecl();
8840 
8841       // C++ [dcl.stc]p1:
8842       //   A storage-class-specifier shall not be specified in an explicit
8843       //   specialization (14.7.3)
8844       FunctionTemplateSpecializationInfo *Info =
8845           NewFD->getTemplateSpecializationInfo();
8846       if (Info && SC != SC_None) {
8847         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8848           Diag(NewFD->getLocation(),
8849                diag::err_explicit_specialization_inconsistent_storage_class)
8850             << SC
8851             << FixItHint::CreateRemoval(
8852                                       D.getDeclSpec().getStorageClassSpecLoc());
8853 
8854         else
8855           Diag(NewFD->getLocation(),
8856                diag::ext_explicit_specialization_storage_class)
8857             << FixItHint::CreateRemoval(
8858                                       D.getDeclSpec().getStorageClassSpecLoc());
8859       }
8860     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8861       if (CheckMemberSpecialization(NewFD, Previous))
8862           NewFD->setInvalidDecl();
8863     }
8864 
8865     // Perform semantic checking on the function declaration.
8866     if (!isDependentClassScopeExplicitSpecialization) {
8867       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8868         CheckMain(NewFD, D.getDeclSpec());
8869 
8870       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8871         CheckMSVCRTEntryPoint(NewFD);
8872 
8873       if (!NewFD->isInvalidDecl())
8874         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8875                                                     isMemberSpecialization));
8876       else if (!Previous.empty())
8877         // Recover gracefully from an invalid redeclaration.
8878         D.setRedeclaration(true);
8879     }
8880 
8881     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8882             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8883            "previous declaration set still overloaded");
8884 
8885     NamedDecl *PrincipalDecl = (FunctionTemplate
8886                                 ? cast<NamedDecl>(FunctionTemplate)
8887                                 : NewFD);
8888 
8889     if (isFriend && NewFD->getPreviousDecl()) {
8890       AccessSpecifier Access = AS_public;
8891       if (!NewFD->isInvalidDecl())
8892         Access = NewFD->getPreviousDecl()->getAccess();
8893 
8894       NewFD->setAccess(Access);
8895       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8896     }
8897 
8898     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8899         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8900       PrincipalDecl->setNonMemberOperator();
8901 
8902     // If we have a function template, check the template parameter
8903     // list. This will check and merge default template arguments.
8904     if (FunctionTemplate) {
8905       FunctionTemplateDecl *PrevTemplate =
8906                                      FunctionTemplate->getPreviousDecl();
8907       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8908                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8909                                     : nullptr,
8910                             D.getDeclSpec().isFriendSpecified()
8911                               ? (D.isFunctionDefinition()
8912                                    ? TPC_FriendFunctionTemplateDefinition
8913                                    : TPC_FriendFunctionTemplate)
8914                               : (D.getCXXScopeSpec().isSet() &&
8915                                  DC && DC->isRecord() &&
8916                                  DC->isDependentContext())
8917                                   ? TPC_ClassTemplateMember
8918                                   : TPC_FunctionTemplate);
8919     }
8920 
8921     if (NewFD->isInvalidDecl()) {
8922       // Ignore all the rest of this.
8923     } else if (!D.isRedeclaration()) {
8924       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8925                                        AddToScope };
8926       // Fake up an access specifier if it's supposed to be a class member.
8927       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8928         NewFD->setAccess(AS_public);
8929 
8930       // Qualified decls generally require a previous declaration.
8931       if (D.getCXXScopeSpec().isSet()) {
8932         // ...with the major exception of templated-scope or
8933         // dependent-scope friend declarations.
8934 
8935         // TODO: we currently also suppress this check in dependent
8936         // contexts because (1) the parameter depth will be off when
8937         // matching friend templates and (2) we might actually be
8938         // selecting a friend based on a dependent factor.  But there
8939         // are situations where these conditions don't apply and we
8940         // can actually do this check immediately.
8941         if (isFriend &&
8942             (TemplateParamLists.size() ||
8943              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8944              CurContext->isDependentContext())) {
8945           // ignore these
8946         } else {
8947           // The user tried to provide an out-of-line definition for a
8948           // function that is a member of a class or namespace, but there
8949           // was no such member function declared (C++ [class.mfct]p2,
8950           // C++ [namespace.memdef]p2). For example:
8951           //
8952           // class X {
8953           //   void f() const;
8954           // };
8955           //
8956           // void X::f() { } // ill-formed
8957           //
8958           // Complain about this problem, and attempt to suggest close
8959           // matches (e.g., those that differ only in cv-qualifiers and
8960           // whether the parameter types are references).
8961 
8962           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8963                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8964             AddToScope = ExtraArgs.AddToScope;
8965             return Result;
8966           }
8967         }
8968 
8969         // Unqualified local friend declarations are required to resolve
8970         // to something.
8971       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8972         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8973                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8974           AddToScope = ExtraArgs.AddToScope;
8975           return Result;
8976         }
8977       }
8978     } else if (!D.isFunctionDefinition() &&
8979                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8980                !isFriend && !isFunctionTemplateSpecialization &&
8981                !isMemberSpecialization) {
8982       // An out-of-line member function declaration must also be a
8983       // definition (C++ [class.mfct]p2).
8984       // Note that this is not the case for explicit specializations of
8985       // function templates or member functions of class templates, per
8986       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8987       // extension for compatibility with old SWIG code which likes to
8988       // generate them.
8989       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8990         << D.getCXXScopeSpec().getRange();
8991     }
8992   }
8993 
8994   ProcessPragmaWeak(S, NewFD);
8995   checkAttributesAfterMerging(*this, *NewFD);
8996 
8997   AddKnownFunctionAttributes(NewFD);
8998 
8999   if (NewFD->hasAttr<OverloadableAttr>() &&
9000       !NewFD->getType()->getAs<FunctionProtoType>()) {
9001     Diag(NewFD->getLocation(),
9002          diag::err_attribute_overloadable_no_prototype)
9003       << NewFD;
9004 
9005     // Turn this into a variadic function with no parameters.
9006     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9007     FunctionProtoType::ExtProtoInfo EPI(
9008         Context.getDefaultCallingConvention(true, false));
9009     EPI.Variadic = true;
9010     EPI.ExtInfo = FT->getExtInfo();
9011 
9012     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9013     NewFD->setType(R);
9014   }
9015 
9016   // If there's a #pragma GCC visibility in scope, and this isn't a class
9017   // member, set the visibility of this function.
9018   if (!DC->isRecord() && NewFD->isExternallyVisible())
9019     AddPushedVisibilityAttribute(NewFD);
9020 
9021   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9022   // marking the function.
9023   AddCFAuditedAttribute(NewFD);
9024 
9025   // If this is a function definition, check if we have to apply optnone due to
9026   // a pragma.
9027   if(D.isFunctionDefinition())
9028     AddRangeBasedOptnone(NewFD);
9029 
9030   // If this is the first declaration of an extern C variable, update
9031   // the map of such variables.
9032   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9033       isIncompleteDeclExternC(*this, NewFD))
9034     RegisterLocallyScopedExternCDecl(NewFD, S);
9035 
9036   // Set this FunctionDecl's range up to the right paren.
9037   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9038 
9039   if (D.isRedeclaration() && !Previous.empty()) {
9040     checkDLLAttributeRedeclaration(
9041         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9042         isMemberSpecialization || isFunctionTemplateSpecialization,
9043         D.isFunctionDefinition());
9044   }
9045 
9046   if (getLangOpts().CUDA) {
9047     IdentifierInfo *II = NewFD->getIdentifier();
9048     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9049         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9050       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9051         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9052 
9053       Context.setcudaConfigureCallDecl(NewFD);
9054     }
9055 
9056     // Variadic functions, other than a *declaration* of printf, are not allowed
9057     // in device-side CUDA code, unless someone passed
9058     // -fcuda-allow-variadic-functions.
9059     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9060         (NewFD->hasAttr<CUDADeviceAttr>() ||
9061          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9062         !(II && II->isStr("printf") && NewFD->isExternC() &&
9063           !D.isFunctionDefinition())) {
9064       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9065     }
9066   }
9067 
9068   MarkUnusedFileScopedDecl(NewFD);
9069 
9070   if (getLangOpts().CPlusPlus) {
9071     if (FunctionTemplate) {
9072       if (NewFD->isInvalidDecl())
9073         FunctionTemplate->setInvalidDecl();
9074       return FunctionTemplate;
9075     }
9076 
9077     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9078       CompleteMemberSpecialization(NewFD, Previous);
9079   }
9080 
9081   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9082     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9083     if ((getLangOpts().OpenCLVersion >= 120)
9084         && (SC == SC_Static)) {
9085       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9086       D.setInvalidType();
9087     }
9088 
9089     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9090     if (!NewFD->getReturnType()->isVoidType()) {
9091       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9092       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9093           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9094                                 : FixItHint());
9095       D.setInvalidType();
9096     }
9097 
9098     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9099     for (auto Param : NewFD->parameters())
9100       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9101   }
9102   for (const ParmVarDecl *Param : NewFD->parameters()) {
9103     QualType PT = Param->getType();
9104 
9105     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9106     // types.
9107     if (getLangOpts().OpenCLVersion >= 200) {
9108       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9109         QualType ElemTy = PipeTy->getElementType();
9110           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9111             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9112             D.setInvalidType();
9113           }
9114       }
9115     }
9116   }
9117 
9118   // Here we have an function template explicit specialization at class scope.
9119   // The actually specialization will be postponed to template instatiation
9120   // time via the ClassScopeFunctionSpecializationDecl node.
9121   if (isDependentClassScopeExplicitSpecialization) {
9122     ClassScopeFunctionSpecializationDecl *NewSpec =
9123                          ClassScopeFunctionSpecializationDecl::Create(
9124                                 Context, CurContext, SourceLocation(),
9125                                 cast<CXXMethodDecl>(NewFD),
9126                                 HasExplicitTemplateArgs, TemplateArgs);
9127     CurContext->addDecl(NewSpec);
9128     AddToScope = false;
9129   }
9130 
9131   return NewFD;
9132 }
9133 
9134 /// \brief Checks if the new declaration declared in dependent context must be
9135 /// put in the same redeclaration chain as the specified declaration.
9136 ///
9137 /// \param D Declaration that is checked.
9138 /// \param PrevDecl Previous declaration found with proper lookup method for the
9139 ///                 same declaration name.
9140 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9141 ///          belongs to.
9142 ///
9143 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9144   // Any declarations should be put into redeclaration chains except for
9145   // friend declaration in a dependent context that names a function in
9146   // namespace scope.
9147   //
9148   // This allows to compile code like:
9149   //
9150   //       void func();
9151   //       template<typename T> class C1 { friend void func() { } };
9152   //       template<typename T> class C2 { friend void func() { } };
9153   //
9154   // This code snippet is a valid code unless both templates are instantiated.
9155   return !(D->getLexicalDeclContext()->isDependentContext() &&
9156            D->getDeclContext()->isFileContext() &&
9157            D->getFriendObjectKind() != Decl::FOK_None);
9158 }
9159 
9160 /// \brief Check the target attribute of the function for MultiVersion
9161 /// validity.
9162 ///
9163 /// Returns true if there was an error, false otherwise.
9164 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9165   const auto *TA = FD->getAttr<TargetAttr>();
9166   assert(TA && "MultiVersion Candidate requires a target attribute");
9167   TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9168   const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9169   enum ErrType { Feature = 0, Architecture = 1 };
9170 
9171   if (!ParseInfo.Architecture.empty() &&
9172       !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9173     S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9174         << Architecture << ParseInfo.Architecture;
9175     return true;
9176   }
9177 
9178   for (const auto &Feat : ParseInfo.Features) {
9179     auto BareFeat = StringRef{Feat}.substr(1);
9180     if (Feat[0] == '-') {
9181       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9182           << Feature << ("no-" + BareFeat).str();
9183       return true;
9184     }
9185 
9186     if (!TargetInfo.validateCpuSupports(BareFeat) ||
9187         !TargetInfo.isValidFeatureName(BareFeat)) {
9188       S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9189           << Feature << BareFeat;
9190       return true;
9191     }
9192   }
9193   return false;
9194 }
9195 
9196 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9197                                              const FunctionDecl *NewFD,
9198                                              bool CausesMV) {
9199   enum DoesntSupport {
9200     FuncTemplates = 0,
9201     VirtFuncs = 1,
9202     DeducedReturn = 2,
9203     Constructors = 3,
9204     Destructors = 4,
9205     DeletedFuncs = 5,
9206     DefaultedFuncs = 6
9207   };
9208   enum Different {
9209     CallingConv = 0,
9210     ReturnType = 1,
9211     ConstexprSpec = 2,
9212     InlineSpec = 3,
9213     StorageClass = 4,
9214     Linkage = 5
9215   };
9216 
9217   // For now, disallow all other attributes.  These should be opt-in, but
9218   // an analysis of all of them is a future FIXME.
9219   if (CausesMV && OldFD &&
9220       std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9221     S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs);
9222     S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9223     return true;
9224   }
9225 
9226   if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) {
9227     S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs);
9228     return true;
9229   }
9230 
9231   if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) {
9232     S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9233         << FuncTemplates;
9234     return true;
9235   }
9236 
9237 
9238   if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9239     if (NewCXXFD->isVirtual()) {
9240       S.Diag(NewCXXFD->getLocation(), diag::err_multiversion_doesnt_support)
9241           << VirtFuncs;
9242       return true;
9243     }
9244 
9245     if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9246       S.Diag(NewCXXCtor->getLocation(), diag::err_multiversion_doesnt_support)
9247           << Constructors;
9248       return true;
9249     }
9250 
9251     if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
9252       S.Diag(NewCXXDtor->getLocation(), diag::err_multiversion_doesnt_support)
9253           << Destructors;
9254       return true;
9255     }
9256   }
9257 
9258   if (NewFD->isDeleted()) {
9259     S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9260       << DeletedFuncs;
9261   }
9262   if (NewFD->isDefaulted()) {
9263     S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9264       << DefaultedFuncs;
9265   }
9266 
9267   QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9268   const auto *NewType = cast<FunctionType>(NewQType);
9269   QualType NewReturnType = NewType->getReturnType();
9270 
9271   if (NewReturnType->isUndeducedType()) {
9272     S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9273         << DeducedReturn;
9274     return true;
9275   }
9276 
9277   // Only allow transition to MultiVersion if it hasn't been used.
9278   if (OldFD && CausesMV && OldFD->isUsed(false)) {
9279     S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9280     return true;
9281   }
9282 
9283   // Ensure the return type is identical.
9284   if (OldFD) {
9285     QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9286     const auto *OldType = cast<FunctionType>(OldQType);
9287     FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9288     FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9289 
9290     if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
9291       S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) << CallingConv;
9292       return true;
9293     }
9294 
9295     QualType OldReturnType = OldType->getReturnType();
9296 
9297     if (OldReturnType != NewReturnType) {
9298       S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) << ReturnType;
9299       return true;
9300     }
9301 
9302     if (OldFD->isConstexpr() != NewFD->isConstexpr()) {
9303       S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9304           << ConstexprSpec;
9305       return true;
9306     }
9307 
9308     if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) {
9309       S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) << InlineSpec;
9310       return true;
9311     }
9312 
9313     if (OldFD->getStorageClass() != NewFD->getStorageClass()) {
9314       S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) << StorageClass;
9315       return true;
9316     }
9317 
9318     if (OldFD->isExternC() != NewFD->isExternC()) {
9319       S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) << Linkage;
9320       return true;
9321     }
9322 
9323     if (S.CheckEquivalentExceptionSpec(
9324             OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9325             NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9326       return true;
9327   }
9328   return false;
9329 }
9330 
9331 /// \brief Check the validity of a mulitversion function declaration.
9332 /// Also sets the multiversion'ness' of the function itself.
9333 ///
9334 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9335 ///
9336 /// Returns true if there was an error, false otherwise.
9337 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9338                                       bool &Redeclaration, NamedDecl *&OldDecl,
9339                                       bool &MergeTypeWithPrevious,
9340                                       LookupResult &Previous) {
9341   const auto *NewTA = NewFD->getAttr<TargetAttr>();
9342   if (NewFD->isMain()) {
9343     if (NewTA && NewTA->isDefaultVersion()) {
9344       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9345       NewFD->isInvalidDecl();
9346       return true;
9347     }
9348     return false;
9349   }
9350 
9351   // If there is no matching previous decl, only 'default' can
9352   // cause MultiVersioning.
9353   if (!OldDecl) {
9354     if (NewTA && NewTA->isDefaultVersion()) {
9355       if (!NewFD->getType()->getAs<FunctionProtoType>()) {
9356         S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9357         NewFD->setInvalidDecl();
9358         return true;
9359       }
9360       if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) {
9361         NewFD->setInvalidDecl();
9362         return true;
9363       }
9364       if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9365         S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9366         return true;
9367       }
9368 
9369       NewFD->setIsMultiVersion();
9370     }
9371     return false;
9372   }
9373 
9374   if (OldDecl->getDeclContext()->getRedeclContext() !=
9375       NewFD->getDeclContext()->getRedeclContext())
9376     return false;
9377 
9378   FunctionDecl *OldFD = OldDecl->getAsFunction();
9379   // Unresolved 'using' statements (the other way OldDecl can be not a function)
9380   // likely cannot cause a problem here.
9381   if (!OldFD)
9382     return false;
9383 
9384   if (!OldFD->isMultiVersion() && !NewTA)
9385     return false;
9386 
9387   if (OldFD->isMultiVersion() && !NewTA) {
9388     S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl);
9389     NewFD->setInvalidDecl();
9390     return true;
9391   }
9392 
9393   TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9394   // Sort order doesn't matter, it just needs to be consistent.
9395   std::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9396 
9397   const auto *OldTA = OldFD->getAttr<TargetAttr>();
9398   if (!OldFD->isMultiVersion()) {
9399     // If the old decl is NOT MultiVersioned yet, and we don't cause that
9400     // to change, this is a simple redeclaration.
9401     if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9402       return false;
9403 
9404     // Otherwise, this decl causes MultiVersioning.
9405     if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9406       S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9407       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9408       return true;
9409     }
9410 
9411     if (!OldFD->getType()->getAs<FunctionProtoType>()) {
9412       S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9413       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9414       NewFD->setInvalidDecl();
9415       return true;
9416     }
9417 
9418     if (CheckMultiVersionValue(S, NewFD)) {
9419       NewFD->setInvalidDecl();
9420       return true;
9421     }
9422 
9423     if (CheckMultiVersionValue(S, OldFD)) {
9424       S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9425       NewFD->setInvalidDecl();
9426       return true;
9427     }
9428 
9429     TargetAttr::ParsedTargetAttr OldParsed =
9430         OldTA->parse(std::less<std::string>());
9431 
9432     if (OldParsed == NewParsed) {
9433       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9434       S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9435       NewFD->setInvalidDecl();
9436       return true;
9437     }
9438 
9439     for (const auto *FD : OldFD->redecls()) {
9440       const auto *CurTA = FD->getAttr<TargetAttr>();
9441       if (!CurTA || CurTA->isInherited()) {
9442         S.Diag(FD->getLocation(), diag::err_target_required_in_redecl);
9443         S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9444         NewFD->setInvalidDecl();
9445         return true;
9446       }
9447     }
9448 
9449     if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) {
9450       NewFD->setInvalidDecl();
9451       return true;
9452     }
9453 
9454     OldFD->setIsMultiVersion();
9455     NewFD->setIsMultiVersion();
9456     Redeclaration = false;
9457     MergeTypeWithPrevious = false;
9458     OldDecl = nullptr;
9459     Previous.clear();
9460     return false;
9461   }
9462 
9463   bool UseMemberUsingDeclRules =
9464       S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9465 
9466   // Next, check ALL non-overloads to see if this is a redeclaration of a
9467   // previous member of the MultiVersion set.
9468   for (NamedDecl *ND : Previous) {
9469     FunctionDecl *CurFD = ND->getAsFunction();
9470     if (!CurFD)
9471       continue;
9472     if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9473       continue;
9474 
9475     const auto *CurTA = CurFD->getAttr<TargetAttr>();
9476     if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9477       NewFD->setIsMultiVersion();
9478       Redeclaration = true;
9479       OldDecl = ND;
9480       return false;
9481     }
9482 
9483     TargetAttr::ParsedTargetAttr CurParsed =
9484         CurTA->parse(std::less<std::string>());
9485 
9486     if (CurParsed == NewParsed) {
9487       S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9488       S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9489       NewFD->setInvalidDecl();
9490       return true;
9491     }
9492   }
9493 
9494   // Else, this is simply a non-redecl case.
9495   if (CheckMultiVersionValue(S, NewFD)) {
9496     NewFD->setInvalidDecl();
9497     return true;
9498   }
9499 
9500   if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) {
9501     NewFD->setInvalidDecl();
9502     return true;
9503   }
9504 
9505   NewFD->setIsMultiVersion();
9506   Redeclaration = false;
9507   MergeTypeWithPrevious = false;
9508   OldDecl = nullptr;
9509   Previous.clear();
9510   return false;
9511 }
9512 
9513 /// \brief Perform semantic checking of a new function declaration.
9514 ///
9515 /// Performs semantic analysis of the new function declaration
9516 /// NewFD. This routine performs all semantic checking that does not
9517 /// require the actual declarator involved in the declaration, and is
9518 /// used both for the declaration of functions as they are parsed
9519 /// (called via ActOnDeclarator) and for the declaration of functions
9520 /// that have been instantiated via C++ template instantiation (called
9521 /// via InstantiateDecl).
9522 ///
9523 /// \param IsMemberSpecialization whether this new function declaration is
9524 /// a member specialization (that replaces any definition provided by the
9525 /// previous declaration).
9526 ///
9527 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9528 ///
9529 /// \returns true if the function declaration is a redeclaration.
9530 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9531                                     LookupResult &Previous,
9532                                     bool IsMemberSpecialization) {
9533   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9534          "Variably modified return types are not handled here");
9535 
9536   // Determine whether the type of this function should be merged with
9537   // a previous visible declaration. This never happens for functions in C++,
9538   // and always happens in C if the previous declaration was visible.
9539   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9540                                !Previous.isShadowed();
9541 
9542   bool Redeclaration = false;
9543   NamedDecl *OldDecl = nullptr;
9544   bool MayNeedOverloadableChecks = false;
9545 
9546   // Merge or overload the declaration with an existing declaration of
9547   // the same name, if appropriate.
9548   if (!Previous.empty()) {
9549     // Determine whether NewFD is an overload of PrevDecl or
9550     // a declaration that requires merging. If it's an overload,
9551     // there's no more work to do here; we'll just add the new
9552     // function to the scope.
9553     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9554       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9555       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9556         Redeclaration = true;
9557         OldDecl = Candidate;
9558       }
9559     } else {
9560       MayNeedOverloadableChecks = true;
9561       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9562                             /*NewIsUsingDecl*/ false)) {
9563       case Ovl_Match:
9564         Redeclaration = true;
9565         break;
9566 
9567       case Ovl_NonFunction:
9568         Redeclaration = true;
9569         break;
9570 
9571       case Ovl_Overload:
9572         Redeclaration = false;
9573         break;
9574       }
9575     }
9576   }
9577 
9578   // Check for a previous extern "C" declaration with this name.
9579   if (!Redeclaration &&
9580       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9581     if (!Previous.empty()) {
9582       // This is an extern "C" declaration with the same name as a previous
9583       // declaration, and thus redeclares that entity...
9584       Redeclaration = true;
9585       OldDecl = Previous.getFoundDecl();
9586       MergeTypeWithPrevious = false;
9587 
9588       // ... except in the presence of __attribute__((overloadable)).
9589       if (OldDecl->hasAttr<OverloadableAttr>() ||
9590           NewFD->hasAttr<OverloadableAttr>()) {
9591         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9592           MayNeedOverloadableChecks = true;
9593           Redeclaration = false;
9594           OldDecl = nullptr;
9595         }
9596       }
9597     }
9598   }
9599 
9600   if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9601                                 MergeTypeWithPrevious, Previous))
9602     return Redeclaration;
9603 
9604   // C++11 [dcl.constexpr]p8:
9605   //   A constexpr specifier for a non-static member function that is not
9606   //   a constructor declares that member function to be const.
9607   //
9608   // This needs to be delayed until we know whether this is an out-of-line
9609   // definition of a static member function.
9610   //
9611   // This rule is not present in C++1y, so we produce a backwards
9612   // compatibility warning whenever it happens in C++11.
9613   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9614   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9615       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9616       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9617     CXXMethodDecl *OldMD = nullptr;
9618     if (OldDecl)
9619       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9620     if (!OldMD || !OldMD->isStatic()) {
9621       const FunctionProtoType *FPT =
9622         MD->getType()->castAs<FunctionProtoType>();
9623       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9624       EPI.TypeQuals |= Qualifiers::Const;
9625       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9626                                           FPT->getParamTypes(), EPI));
9627 
9628       // Warn that we did this, if we're not performing template instantiation.
9629       // In that case, we'll have warned already when the template was defined.
9630       if (!inTemplateInstantiation()) {
9631         SourceLocation AddConstLoc;
9632         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9633                 .IgnoreParens().getAs<FunctionTypeLoc>())
9634           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9635 
9636         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9637           << FixItHint::CreateInsertion(AddConstLoc, " const");
9638       }
9639     }
9640   }
9641 
9642   if (Redeclaration) {
9643     // NewFD and OldDecl represent declarations that need to be
9644     // merged.
9645     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9646       NewFD->setInvalidDecl();
9647       return Redeclaration;
9648     }
9649 
9650     Previous.clear();
9651     Previous.addDecl(OldDecl);
9652 
9653     if (FunctionTemplateDecl *OldTemplateDecl
9654                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9655       auto *OldFD = OldTemplateDecl->getTemplatedDecl();
9656       NewFD->setPreviousDeclaration(OldFD);
9657       adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9658       FunctionTemplateDecl *NewTemplateDecl
9659         = NewFD->getDescribedFunctionTemplate();
9660       assert(NewTemplateDecl && "Template/non-template mismatch");
9661       if (auto *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9662         Method->setAccess(OldTemplateDecl->getAccess());
9663         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9664       }
9665 
9666       // If this is an explicit specialization of a member that is a function
9667       // template, mark it as a member specialization.
9668       if (IsMemberSpecialization &&
9669           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9670         NewTemplateDecl->setMemberSpecialization();
9671         assert(OldTemplateDecl->isMemberSpecialization());
9672         // Explicit specializations of a member template do not inherit deleted
9673         // status from the parent member template that they are specializing.
9674         if (OldFD->isDeleted()) {
9675           // FIXME: This assert will not hold in the presence of modules.
9676           assert(OldFD->getCanonicalDecl() == OldFD);
9677           // FIXME: We need an update record for this AST mutation.
9678           OldFD->setDeletedAsWritten(false);
9679         }
9680       }
9681 
9682     } else {
9683       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9684         auto *OldFD = cast<FunctionDecl>(OldDecl);
9685         // This needs to happen first so that 'inline' propagates.
9686         NewFD->setPreviousDeclaration(OldFD);
9687         adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9688         if (isa<CXXMethodDecl>(NewFD))
9689           NewFD->setAccess(OldFD->getAccess());
9690       }
9691     }
9692   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9693              !NewFD->getAttr<OverloadableAttr>()) {
9694     assert((Previous.empty() ||
9695             llvm::any_of(Previous,
9696                          [](const NamedDecl *ND) {
9697                            return ND->hasAttr<OverloadableAttr>();
9698                          })) &&
9699            "Non-redecls shouldn't happen without overloadable present");
9700 
9701     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9702       const auto *FD = dyn_cast<FunctionDecl>(ND);
9703       return FD && !FD->hasAttr<OverloadableAttr>();
9704     });
9705 
9706     if (OtherUnmarkedIter != Previous.end()) {
9707       Diag(NewFD->getLocation(),
9708            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9709       Diag((*OtherUnmarkedIter)->getLocation(),
9710            diag::note_attribute_overloadable_prev_overload)
9711           << false;
9712 
9713       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9714     }
9715   }
9716 
9717   // Semantic checking for this function declaration (in isolation).
9718 
9719   if (getLangOpts().CPlusPlus) {
9720     // C++-specific checks.
9721     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9722       CheckConstructor(Constructor);
9723     } else if (CXXDestructorDecl *Destructor =
9724                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9725       CXXRecordDecl *Record = Destructor->getParent();
9726       QualType ClassType = Context.getTypeDeclType(Record);
9727 
9728       // FIXME: Shouldn't we be able to perform this check even when the class
9729       // type is dependent? Both gcc and edg can handle that.
9730       if (!ClassType->isDependentType()) {
9731         DeclarationName Name
9732           = Context.DeclarationNames.getCXXDestructorName(
9733                                         Context.getCanonicalType(ClassType));
9734         if (NewFD->getDeclName() != Name) {
9735           Diag(NewFD->getLocation(), diag::err_destructor_name);
9736           NewFD->setInvalidDecl();
9737           return Redeclaration;
9738         }
9739       }
9740     } else if (CXXConversionDecl *Conversion
9741                = dyn_cast<CXXConversionDecl>(NewFD)) {
9742       ActOnConversionDeclarator(Conversion);
9743     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9744       if (auto *TD = Guide->getDescribedFunctionTemplate())
9745         CheckDeductionGuideTemplate(TD);
9746 
9747       // A deduction guide is not on the list of entities that can be
9748       // explicitly specialized.
9749       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9750         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9751             << /*explicit specialization*/ 1;
9752     }
9753 
9754     // Find any virtual functions that this function overrides.
9755     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9756       if (!Method->isFunctionTemplateSpecialization() &&
9757           !Method->getDescribedFunctionTemplate() &&
9758           Method->isCanonicalDecl()) {
9759         if (AddOverriddenMethods(Method->getParent(), Method)) {
9760           // If the function was marked as "static", we have a problem.
9761           if (NewFD->getStorageClass() == SC_Static) {
9762             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9763           }
9764         }
9765       }
9766 
9767       if (Method->isStatic())
9768         checkThisInStaticMemberFunctionType(Method);
9769     }
9770 
9771     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9772     if (NewFD->isOverloadedOperator() &&
9773         CheckOverloadedOperatorDeclaration(NewFD)) {
9774       NewFD->setInvalidDecl();
9775       return Redeclaration;
9776     }
9777 
9778     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9779     if (NewFD->getLiteralIdentifier() &&
9780         CheckLiteralOperatorDeclaration(NewFD)) {
9781       NewFD->setInvalidDecl();
9782       return Redeclaration;
9783     }
9784 
9785     // In C++, check default arguments now that we have merged decls. Unless
9786     // the lexical context is the class, because in this case this is done
9787     // during delayed parsing anyway.
9788     if (!CurContext->isRecord())
9789       CheckCXXDefaultArguments(NewFD);
9790 
9791     // If this function declares a builtin function, check the type of this
9792     // declaration against the expected type for the builtin.
9793     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9794       ASTContext::GetBuiltinTypeError Error;
9795       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9796       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9797       // If the type of the builtin differs only in its exception
9798       // specification, that's OK.
9799       // FIXME: If the types do differ in this way, it would be better to
9800       // retain the 'noexcept' form of the type.
9801       if (!T.isNull() &&
9802           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9803                                                             NewFD->getType()))
9804         // The type of this function differs from the type of the builtin,
9805         // so forget about the builtin entirely.
9806         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9807     }
9808 
9809     // If this function is declared as being extern "C", then check to see if
9810     // the function returns a UDT (class, struct, or union type) that is not C
9811     // compatible, and if it does, warn the user.
9812     // But, issue any diagnostic on the first declaration only.
9813     if (Previous.empty() && NewFD->isExternC()) {
9814       QualType R = NewFD->getReturnType();
9815       if (R->isIncompleteType() && !R->isVoidType())
9816         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9817             << NewFD << R;
9818       else if (!R.isPODType(Context) && !R->isVoidType() &&
9819                !R->isObjCObjectPointerType())
9820         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9821     }
9822 
9823     // C++1z [dcl.fct]p6:
9824     //   [...] whether the function has a non-throwing exception-specification
9825     //   [is] part of the function type
9826     //
9827     // This results in an ABI break between C++14 and C++17 for functions whose
9828     // declared type includes an exception-specification in a parameter or
9829     // return type. (Exception specifications on the function itself are OK in
9830     // most cases, and exception specifications are not permitted in most other
9831     // contexts where they could make it into a mangling.)
9832     if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
9833       auto HasNoexcept = [&](QualType T) -> bool {
9834         // Strip off declarator chunks that could be between us and a function
9835         // type. We don't need to look far, exception specifications are very
9836         // restricted prior to C++17.
9837         if (auto *RT = T->getAs<ReferenceType>())
9838           T = RT->getPointeeType();
9839         else if (T->isAnyPointerType())
9840           T = T->getPointeeType();
9841         else if (auto *MPT = T->getAs<MemberPointerType>())
9842           T = MPT->getPointeeType();
9843         if (auto *FPT = T->getAs<FunctionProtoType>())
9844           if (FPT->isNothrow(Context))
9845             return true;
9846         return false;
9847       };
9848 
9849       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9850       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9851       for (QualType T : FPT->param_types())
9852         AnyNoexcept |= HasNoexcept(T);
9853       if (AnyNoexcept)
9854         Diag(NewFD->getLocation(),
9855              diag::warn_cxx17_compat_exception_spec_in_signature)
9856             << NewFD;
9857     }
9858 
9859     if (!Redeclaration && LangOpts.CUDA)
9860       checkCUDATargetOverload(NewFD, Previous);
9861   }
9862   return Redeclaration;
9863 }
9864 
9865 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9866   // C++11 [basic.start.main]p3:
9867   //   A program that [...] declares main to be inline, static or
9868   //   constexpr is ill-formed.
9869   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9870   //   appear in a declaration of main.
9871   // static main is not an error under C99, but we should warn about it.
9872   // We accept _Noreturn main as an extension.
9873   if (FD->getStorageClass() == SC_Static)
9874     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9875          ? diag::err_static_main : diag::warn_static_main)
9876       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9877   if (FD->isInlineSpecified())
9878     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9879       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9880   if (DS.isNoreturnSpecified()) {
9881     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9882     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9883     Diag(NoreturnLoc, diag::ext_noreturn_main);
9884     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9885       << FixItHint::CreateRemoval(NoreturnRange);
9886   }
9887   if (FD->isConstexpr()) {
9888     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9889       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9890     FD->setConstexpr(false);
9891   }
9892 
9893   if (getLangOpts().OpenCL) {
9894     Diag(FD->getLocation(), diag::err_opencl_no_main)
9895         << FD->hasAttr<OpenCLKernelAttr>();
9896     FD->setInvalidDecl();
9897     return;
9898   }
9899 
9900   QualType T = FD->getType();
9901   assert(T->isFunctionType() && "function decl is not of function type");
9902   const FunctionType* FT = T->castAs<FunctionType>();
9903 
9904   // Set default calling convention for main()
9905   if (FT->getCallConv() != CC_C) {
9906     FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
9907     FD->setType(QualType(FT, 0));
9908     T = Context.getCanonicalType(FD->getType());
9909   }
9910 
9911   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9912     // In C with GNU extensions we allow main() to have non-integer return
9913     // type, but we should warn about the extension, and we disable the
9914     // implicit-return-zero rule.
9915 
9916     // GCC in C mode accepts qualified 'int'.
9917     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9918       FD->setHasImplicitReturnZero(true);
9919     else {
9920       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9921       SourceRange RTRange = FD->getReturnTypeSourceRange();
9922       if (RTRange.isValid())
9923         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9924             << FixItHint::CreateReplacement(RTRange, "int");
9925     }
9926   } else {
9927     // In C and C++, main magically returns 0 if you fall off the end;
9928     // set the flag which tells us that.
9929     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9930 
9931     // All the standards say that main() should return 'int'.
9932     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9933       FD->setHasImplicitReturnZero(true);
9934     else {
9935       // Otherwise, this is just a flat-out error.
9936       SourceRange RTRange = FD->getReturnTypeSourceRange();
9937       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9938           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9939                                 : FixItHint());
9940       FD->setInvalidDecl(true);
9941     }
9942   }
9943 
9944   // Treat protoless main() as nullary.
9945   if (isa<FunctionNoProtoType>(FT)) return;
9946 
9947   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9948   unsigned nparams = FTP->getNumParams();
9949   assert(FD->getNumParams() == nparams);
9950 
9951   bool HasExtraParameters = (nparams > 3);
9952 
9953   if (FTP->isVariadic()) {
9954     Diag(FD->getLocation(), diag::ext_variadic_main);
9955     // FIXME: if we had information about the location of the ellipsis, we
9956     // could add a FixIt hint to remove it as a parameter.
9957   }
9958 
9959   // Darwin passes an undocumented fourth argument of type char**.  If
9960   // other platforms start sprouting these, the logic below will start
9961   // getting shifty.
9962   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9963     HasExtraParameters = false;
9964 
9965   if (HasExtraParameters) {
9966     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9967     FD->setInvalidDecl(true);
9968     nparams = 3;
9969   }
9970 
9971   // FIXME: a lot of the following diagnostics would be improved
9972   // if we had some location information about types.
9973 
9974   QualType CharPP =
9975     Context.getPointerType(Context.getPointerType(Context.CharTy));
9976   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9977 
9978   for (unsigned i = 0; i < nparams; ++i) {
9979     QualType AT = FTP->getParamType(i);
9980 
9981     bool mismatch = true;
9982 
9983     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9984       mismatch = false;
9985     else if (Expected[i] == CharPP) {
9986       // As an extension, the following forms are okay:
9987       //   char const **
9988       //   char const * const *
9989       //   char * const *
9990 
9991       QualifierCollector qs;
9992       const PointerType* PT;
9993       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9994           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9995           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9996                               Context.CharTy)) {
9997         qs.removeConst();
9998         mismatch = !qs.empty();
9999       }
10000     }
10001 
10002     if (mismatch) {
10003       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10004       // TODO: suggest replacing given type with expected type
10005       FD->setInvalidDecl(true);
10006     }
10007   }
10008 
10009   if (nparams == 1 && !FD->isInvalidDecl()) {
10010     Diag(FD->getLocation(), diag::warn_main_one_arg);
10011   }
10012 
10013   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10014     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10015     FD->setInvalidDecl();
10016   }
10017 }
10018 
10019 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10020   QualType T = FD->getType();
10021   assert(T->isFunctionType() && "function decl is not of function type");
10022   const FunctionType *FT = T->castAs<FunctionType>();
10023 
10024   // Set an implicit return of 'zero' if the function can return some integral,
10025   // enumeration, pointer or nullptr type.
10026   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10027       FT->getReturnType()->isAnyPointerType() ||
10028       FT->getReturnType()->isNullPtrType())
10029     // DllMain is exempt because a return value of zero means it failed.
10030     if (FD->getName() != "DllMain")
10031       FD->setHasImplicitReturnZero(true);
10032 
10033   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10034     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10035     FD->setInvalidDecl();
10036   }
10037 }
10038 
10039 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10040   // FIXME: Need strict checking.  In C89, we need to check for
10041   // any assignment, increment, decrement, function-calls, or
10042   // commas outside of a sizeof.  In C99, it's the same list,
10043   // except that the aforementioned are allowed in unevaluated
10044   // expressions.  Everything else falls under the
10045   // "may accept other forms of constant expressions" exception.
10046   // (We never end up here for C++, so the constant expression
10047   // rules there don't matter.)
10048   const Expr *Culprit;
10049   if (Init->isConstantInitializer(Context, false, &Culprit))
10050     return false;
10051   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10052     << Culprit->getSourceRange();
10053   return true;
10054 }
10055 
10056 namespace {
10057   // Visits an initialization expression to see if OrigDecl is evaluated in
10058   // its own initialization and throws a warning if it does.
10059   class SelfReferenceChecker
10060       : public EvaluatedExprVisitor<SelfReferenceChecker> {
10061     Sema &S;
10062     Decl *OrigDecl;
10063     bool isRecordType;
10064     bool isPODType;
10065     bool isReferenceType;
10066 
10067     bool isInitList;
10068     llvm::SmallVector<unsigned, 4> InitFieldIndex;
10069 
10070   public:
10071     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10072 
10073     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10074                                                     S(S), OrigDecl(OrigDecl) {
10075       isPODType = false;
10076       isRecordType = false;
10077       isReferenceType = false;
10078       isInitList = false;
10079       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10080         isPODType = VD->getType().isPODType(S.Context);
10081         isRecordType = VD->getType()->isRecordType();
10082         isReferenceType = VD->getType()->isReferenceType();
10083       }
10084     }
10085 
10086     // For most expressions, just call the visitor.  For initializer lists,
10087     // track the index of the field being initialized since fields are
10088     // initialized in order allowing use of previously initialized fields.
10089     void CheckExpr(Expr *E) {
10090       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10091       if (!InitList) {
10092         Visit(E);
10093         return;
10094       }
10095 
10096       // Track and increment the index here.
10097       isInitList = true;
10098       InitFieldIndex.push_back(0);
10099       for (auto Child : InitList->children()) {
10100         CheckExpr(cast<Expr>(Child));
10101         ++InitFieldIndex.back();
10102       }
10103       InitFieldIndex.pop_back();
10104     }
10105 
10106     // Returns true if MemberExpr is checked and no further checking is needed.
10107     // Returns false if additional checking is required.
10108     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10109       llvm::SmallVector<FieldDecl*, 4> Fields;
10110       Expr *Base = E;
10111       bool ReferenceField = false;
10112 
10113       // Get the field memebers used.
10114       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10115         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10116         if (!FD)
10117           return false;
10118         Fields.push_back(FD);
10119         if (FD->getType()->isReferenceType())
10120           ReferenceField = true;
10121         Base = ME->getBase()->IgnoreParenImpCasts();
10122       }
10123 
10124       // Keep checking only if the base Decl is the same.
10125       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10126       if (!DRE || DRE->getDecl() != OrigDecl)
10127         return false;
10128 
10129       // A reference field can be bound to an unininitialized field.
10130       if (CheckReference && !ReferenceField)
10131         return true;
10132 
10133       // Convert FieldDecls to their index number.
10134       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10135       for (const FieldDecl *I : llvm::reverse(Fields))
10136         UsedFieldIndex.push_back(I->getFieldIndex());
10137 
10138       // See if a warning is needed by checking the first difference in index
10139       // numbers.  If field being used has index less than the field being
10140       // initialized, then the use is safe.
10141       for (auto UsedIter = UsedFieldIndex.begin(),
10142                 UsedEnd = UsedFieldIndex.end(),
10143                 OrigIter = InitFieldIndex.begin(),
10144                 OrigEnd = InitFieldIndex.end();
10145            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10146         if (*UsedIter < *OrigIter)
10147           return true;
10148         if (*UsedIter > *OrigIter)
10149           break;
10150       }
10151 
10152       // TODO: Add a different warning which will print the field names.
10153       HandleDeclRefExpr(DRE);
10154       return true;
10155     }
10156 
10157     // For most expressions, the cast is directly above the DeclRefExpr.
10158     // For conditional operators, the cast can be outside the conditional
10159     // operator if both expressions are DeclRefExpr's.
10160     void HandleValue(Expr *E) {
10161       E = E->IgnoreParens();
10162       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10163         HandleDeclRefExpr(DRE);
10164         return;
10165       }
10166 
10167       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10168         Visit(CO->getCond());
10169         HandleValue(CO->getTrueExpr());
10170         HandleValue(CO->getFalseExpr());
10171         return;
10172       }
10173 
10174       if (BinaryConditionalOperator *BCO =
10175               dyn_cast<BinaryConditionalOperator>(E)) {
10176         Visit(BCO->getCond());
10177         HandleValue(BCO->getFalseExpr());
10178         return;
10179       }
10180 
10181       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10182         HandleValue(OVE->getSourceExpr());
10183         return;
10184       }
10185 
10186       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10187         if (BO->getOpcode() == BO_Comma) {
10188           Visit(BO->getLHS());
10189           HandleValue(BO->getRHS());
10190           return;
10191         }
10192       }
10193 
10194       if (isa<MemberExpr>(E)) {
10195         if (isInitList) {
10196           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10197                                       false /*CheckReference*/))
10198             return;
10199         }
10200 
10201         Expr *Base = E->IgnoreParenImpCasts();
10202         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10203           // Check for static member variables and don't warn on them.
10204           if (!isa<FieldDecl>(ME->getMemberDecl()))
10205             return;
10206           Base = ME->getBase()->IgnoreParenImpCasts();
10207         }
10208         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10209           HandleDeclRefExpr(DRE);
10210         return;
10211       }
10212 
10213       Visit(E);
10214     }
10215 
10216     // Reference types not handled in HandleValue are handled here since all
10217     // uses of references are bad, not just r-value uses.
10218     void VisitDeclRefExpr(DeclRefExpr *E) {
10219       if (isReferenceType)
10220         HandleDeclRefExpr(E);
10221     }
10222 
10223     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10224       if (E->getCastKind() == CK_LValueToRValue) {
10225         HandleValue(E->getSubExpr());
10226         return;
10227       }
10228 
10229       Inherited::VisitImplicitCastExpr(E);
10230     }
10231 
10232     void VisitMemberExpr(MemberExpr *E) {
10233       if (isInitList) {
10234         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10235           return;
10236       }
10237 
10238       // Don't warn on arrays since they can be treated as pointers.
10239       if (E->getType()->canDecayToPointerType()) return;
10240 
10241       // Warn when a non-static method call is followed by non-static member
10242       // field accesses, which is followed by a DeclRefExpr.
10243       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10244       bool Warn = (MD && !MD->isStatic());
10245       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10246       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10247         if (!isa<FieldDecl>(ME->getMemberDecl()))
10248           Warn = false;
10249         Base = ME->getBase()->IgnoreParenImpCasts();
10250       }
10251 
10252       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10253         if (Warn)
10254           HandleDeclRefExpr(DRE);
10255         return;
10256       }
10257 
10258       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10259       // Visit that expression.
10260       Visit(Base);
10261     }
10262 
10263     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10264       Expr *Callee = E->getCallee();
10265 
10266       if (isa<UnresolvedLookupExpr>(Callee))
10267         return Inherited::VisitCXXOperatorCallExpr(E);
10268 
10269       Visit(Callee);
10270       for (auto Arg: E->arguments())
10271         HandleValue(Arg->IgnoreParenImpCasts());
10272     }
10273 
10274     void VisitUnaryOperator(UnaryOperator *E) {
10275       // For POD record types, addresses of its own members are well-defined.
10276       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10277           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10278         if (!isPODType)
10279           HandleValue(E->getSubExpr());
10280         return;
10281       }
10282 
10283       if (E->isIncrementDecrementOp()) {
10284         HandleValue(E->getSubExpr());
10285         return;
10286       }
10287 
10288       Inherited::VisitUnaryOperator(E);
10289     }
10290 
10291     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10292 
10293     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10294       if (E->getConstructor()->isCopyConstructor()) {
10295         Expr *ArgExpr = E->getArg(0);
10296         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10297           if (ILE->getNumInits() == 1)
10298             ArgExpr = ILE->getInit(0);
10299         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10300           if (ICE->getCastKind() == CK_NoOp)
10301             ArgExpr = ICE->getSubExpr();
10302         HandleValue(ArgExpr);
10303         return;
10304       }
10305       Inherited::VisitCXXConstructExpr(E);
10306     }
10307 
10308     void VisitCallExpr(CallExpr *E) {
10309       // Treat std::move as a use.
10310       if (E->isCallToStdMove()) {
10311         HandleValue(E->getArg(0));
10312         return;
10313       }
10314 
10315       Inherited::VisitCallExpr(E);
10316     }
10317 
10318     void VisitBinaryOperator(BinaryOperator *E) {
10319       if (E->isCompoundAssignmentOp()) {
10320         HandleValue(E->getLHS());
10321         Visit(E->getRHS());
10322         return;
10323       }
10324 
10325       Inherited::VisitBinaryOperator(E);
10326     }
10327 
10328     // A custom visitor for BinaryConditionalOperator is needed because the
10329     // regular visitor would check the condition and true expression separately
10330     // but both point to the same place giving duplicate diagnostics.
10331     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10332       Visit(E->getCond());
10333       Visit(E->getFalseExpr());
10334     }
10335 
10336     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10337       Decl* ReferenceDecl = DRE->getDecl();
10338       if (OrigDecl != ReferenceDecl) return;
10339       unsigned diag;
10340       if (isReferenceType) {
10341         diag = diag::warn_uninit_self_reference_in_reference_init;
10342       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10343         diag = diag::warn_static_self_reference_in_init;
10344       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10345                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10346                  DRE->getDecl()->getType()->isRecordType()) {
10347         diag = diag::warn_uninit_self_reference_in_init;
10348       } else {
10349         // Local variables will be handled by the CFG analysis.
10350         return;
10351       }
10352 
10353       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10354                             S.PDiag(diag)
10355                               << DRE->getNameInfo().getName()
10356                               << OrigDecl->getLocation()
10357                               << DRE->getSourceRange());
10358     }
10359   };
10360 
10361   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10362   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10363                                  bool DirectInit) {
10364     // Parameters arguments are occassionially constructed with itself,
10365     // for instance, in recursive functions.  Skip them.
10366     if (isa<ParmVarDecl>(OrigDecl))
10367       return;
10368 
10369     E = E->IgnoreParens();
10370 
10371     // Skip checking T a = a where T is not a record or reference type.
10372     // Doing so is a way to silence uninitialized warnings.
10373     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10374       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10375         if (ICE->getCastKind() == CK_LValueToRValue)
10376           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10377             if (DRE->getDecl() == OrigDecl)
10378               return;
10379 
10380     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10381   }
10382 } // end anonymous namespace
10383 
10384 namespace {
10385   // Simple wrapper to add the name of a variable or (if no variable is
10386   // available) a DeclarationName into a diagnostic.
10387   struct VarDeclOrName {
10388     VarDecl *VDecl;
10389     DeclarationName Name;
10390 
10391     friend const Sema::SemaDiagnosticBuilder &
10392     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10393       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10394     }
10395   };
10396 } // end anonymous namespace
10397 
10398 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10399                                             DeclarationName Name, QualType Type,
10400                                             TypeSourceInfo *TSI,
10401                                             SourceRange Range, bool DirectInit,
10402                                             Expr *Init) {
10403   bool IsInitCapture = !VDecl;
10404   assert((!VDecl || !VDecl->isInitCapture()) &&
10405          "init captures are expected to be deduced prior to initialization");
10406 
10407   VarDeclOrName VN{VDecl, Name};
10408 
10409   DeducedType *Deduced = Type->getContainedDeducedType();
10410   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10411 
10412   // C++11 [dcl.spec.auto]p3
10413   if (!Init) {
10414     assert(VDecl && "no init for init capture deduction?");
10415     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10416       << VDecl->getDeclName() << Type;
10417     return QualType();
10418   }
10419 
10420   ArrayRef<Expr*> DeduceInits = Init;
10421   if (DirectInit) {
10422     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10423       DeduceInits = PL->exprs();
10424   }
10425 
10426   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10427     assert(VDecl && "non-auto type for init capture deduction?");
10428     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10429     InitializationKind Kind = InitializationKind::CreateForInit(
10430         VDecl->getLocation(), DirectInit, Init);
10431     // FIXME: Initialization should not be taking a mutable list of inits.
10432     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10433     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10434                                                        InitsCopy);
10435   }
10436 
10437   if (DirectInit) {
10438     if (auto *IL = dyn_cast<InitListExpr>(Init))
10439       DeduceInits = IL->inits();
10440   }
10441 
10442   // Deduction only works if we have exactly one source expression.
10443   if (DeduceInits.empty()) {
10444     // It isn't possible to write this directly, but it is possible to
10445     // end up in this situation with "auto x(some_pack...);"
10446     Diag(Init->getLocStart(), IsInitCapture
10447                                   ? diag::err_init_capture_no_expression
10448                                   : diag::err_auto_var_init_no_expression)
10449         << VN << Type << Range;
10450     return QualType();
10451   }
10452 
10453   if (DeduceInits.size() > 1) {
10454     Diag(DeduceInits[1]->getLocStart(),
10455          IsInitCapture ? diag::err_init_capture_multiple_expressions
10456                        : diag::err_auto_var_init_multiple_expressions)
10457         << VN << Type << Range;
10458     return QualType();
10459   }
10460 
10461   Expr *DeduceInit = DeduceInits[0];
10462   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10463     Diag(Init->getLocStart(), IsInitCapture
10464                                   ? diag::err_init_capture_paren_braces
10465                                   : diag::err_auto_var_init_paren_braces)
10466         << isa<InitListExpr>(Init) << VN << Type << Range;
10467     return QualType();
10468   }
10469 
10470   // Expressions default to 'id' when we're in a debugger.
10471   bool DefaultedAnyToId = false;
10472   if (getLangOpts().DebuggerCastResultToId &&
10473       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10474     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10475     if (Result.isInvalid()) {
10476       return QualType();
10477     }
10478     Init = Result.get();
10479     DefaultedAnyToId = true;
10480   }
10481 
10482   // C++ [dcl.decomp]p1:
10483   //   If the assignment-expression [...] has array type A and no ref-qualifier
10484   //   is present, e has type cv A
10485   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10486       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10487       DeduceInit->getType()->isConstantArrayType())
10488     return Context.getQualifiedType(DeduceInit->getType(),
10489                                     Type.getQualifiers());
10490 
10491   QualType DeducedType;
10492   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10493     if (!IsInitCapture)
10494       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10495     else if (isa<InitListExpr>(Init))
10496       Diag(Range.getBegin(),
10497            diag::err_init_capture_deduction_failure_from_init_list)
10498           << VN
10499           << (DeduceInit->getType().isNull() ? TSI->getType()
10500                                              : DeduceInit->getType())
10501           << DeduceInit->getSourceRange();
10502     else
10503       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10504           << VN << TSI->getType()
10505           << (DeduceInit->getType().isNull() ? TSI->getType()
10506                                              : DeduceInit->getType())
10507           << DeduceInit->getSourceRange();
10508   }
10509 
10510   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10511   // 'id' instead of a specific object type prevents most of our usual
10512   // checks.
10513   // We only want to warn outside of template instantiations, though:
10514   // inside a template, the 'id' could have come from a parameter.
10515   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10516       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10517     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10518     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10519   }
10520 
10521   return DeducedType;
10522 }
10523 
10524 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10525                                          Expr *Init) {
10526   QualType DeducedType = deduceVarTypeFromInitializer(
10527       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10528       VDecl->getSourceRange(), DirectInit, Init);
10529   if (DeducedType.isNull()) {
10530     VDecl->setInvalidDecl();
10531     return true;
10532   }
10533 
10534   VDecl->setType(DeducedType);
10535   assert(VDecl->isLinkageValid());
10536 
10537   // In ARC, infer lifetime.
10538   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10539     VDecl->setInvalidDecl();
10540 
10541   // If this is a redeclaration, check that the type we just deduced matches
10542   // the previously declared type.
10543   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10544     // We never need to merge the type, because we cannot form an incomplete
10545     // array of auto, nor deduce such a type.
10546     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10547   }
10548 
10549   // Check the deduced type is valid for a variable declaration.
10550   CheckVariableDeclarationType(VDecl);
10551   return VDecl->isInvalidDecl();
10552 }
10553 
10554 /// AddInitializerToDecl - Adds the initializer Init to the
10555 /// declaration dcl. If DirectInit is true, this is C++ direct
10556 /// initialization rather than copy initialization.
10557 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10558   // If there is no declaration, there was an error parsing it.  Just ignore
10559   // the initializer.
10560   if (!RealDecl || RealDecl->isInvalidDecl()) {
10561     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10562     return;
10563   }
10564 
10565   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10566     // Pure-specifiers are handled in ActOnPureSpecifier.
10567     Diag(Method->getLocation(), diag::err_member_function_initialization)
10568       << Method->getDeclName() << Init->getSourceRange();
10569     Method->setInvalidDecl();
10570     return;
10571   }
10572 
10573   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10574   if (!VDecl) {
10575     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10576     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10577     RealDecl->setInvalidDecl();
10578     return;
10579   }
10580 
10581   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10582   if (VDecl->getType()->isUndeducedType()) {
10583     // Attempt typo correction early so that the type of the init expression can
10584     // be deduced based on the chosen correction if the original init contains a
10585     // TypoExpr.
10586     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10587     if (!Res.isUsable()) {
10588       RealDecl->setInvalidDecl();
10589       return;
10590     }
10591     Init = Res.get();
10592 
10593     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10594       return;
10595   }
10596 
10597   // dllimport cannot be used on variable definitions.
10598   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10599     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10600     VDecl->setInvalidDecl();
10601     return;
10602   }
10603 
10604   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10605     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10606     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10607     VDecl->setInvalidDecl();
10608     return;
10609   }
10610 
10611   if (!VDecl->getType()->isDependentType()) {
10612     // A definition must end up with a complete type, which means it must be
10613     // complete with the restriction that an array type might be completed by
10614     // the initializer; note that later code assumes this restriction.
10615     QualType BaseDeclType = VDecl->getType();
10616     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10617       BaseDeclType = Array->getElementType();
10618     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10619                             diag::err_typecheck_decl_incomplete_type)) {
10620       RealDecl->setInvalidDecl();
10621       return;
10622     }
10623 
10624     // The variable can not have an abstract class type.
10625     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10626                                diag::err_abstract_type_in_decl,
10627                                AbstractVariableType))
10628       VDecl->setInvalidDecl();
10629   }
10630 
10631   // If adding the initializer will turn this declaration into a definition,
10632   // and we already have a definition for this variable, diagnose or otherwise
10633   // handle the situation.
10634   VarDecl *Def;
10635   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10636       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10637       !VDecl->isThisDeclarationADemotedDefinition() &&
10638       checkVarDeclRedefinition(Def, VDecl))
10639     return;
10640 
10641   if (getLangOpts().CPlusPlus) {
10642     // C++ [class.static.data]p4
10643     //   If a static data member is of const integral or const
10644     //   enumeration type, its declaration in the class definition can
10645     //   specify a constant-initializer which shall be an integral
10646     //   constant expression (5.19). In that case, the member can appear
10647     //   in integral constant expressions. The member shall still be
10648     //   defined in a namespace scope if it is used in the program and the
10649     //   namespace scope definition shall not contain an initializer.
10650     //
10651     // We already performed a redefinition check above, but for static
10652     // data members we also need to check whether there was an in-class
10653     // declaration with an initializer.
10654     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10655       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10656           << VDecl->getDeclName();
10657       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10658            diag::note_previous_initializer)
10659           << 0;
10660       return;
10661     }
10662 
10663     if (VDecl->hasLocalStorage())
10664       getCurFunction()->setHasBranchProtectedScope();
10665 
10666     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10667       VDecl->setInvalidDecl();
10668       return;
10669     }
10670   }
10671 
10672   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10673   // a kernel function cannot be initialized."
10674   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10675     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10676     VDecl->setInvalidDecl();
10677     return;
10678   }
10679 
10680   // Get the decls type and save a reference for later, since
10681   // CheckInitializerTypes may change it.
10682   QualType DclT = VDecl->getType(), SavT = DclT;
10683 
10684   // Expressions default to 'id' when we're in a debugger
10685   // and we are assigning it to a variable of Objective-C pointer type.
10686   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10687       Init->getType() == Context.UnknownAnyTy) {
10688     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10689     if (Result.isInvalid()) {
10690       VDecl->setInvalidDecl();
10691       return;
10692     }
10693     Init = Result.get();
10694   }
10695 
10696   // Perform the initialization.
10697   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10698   if (!VDecl->isInvalidDecl()) {
10699     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10700     InitializationKind Kind = InitializationKind::CreateForInit(
10701         VDecl->getLocation(), DirectInit, Init);
10702 
10703     MultiExprArg Args = Init;
10704     if (CXXDirectInit)
10705       Args = MultiExprArg(CXXDirectInit->getExprs(),
10706                           CXXDirectInit->getNumExprs());
10707 
10708     // Try to correct any TypoExprs in the initialization arguments.
10709     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10710       ExprResult Res = CorrectDelayedTyposInExpr(
10711           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10712             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10713             return Init.Failed() ? ExprError() : E;
10714           });
10715       if (Res.isInvalid()) {
10716         VDecl->setInvalidDecl();
10717       } else if (Res.get() != Args[Idx]) {
10718         Args[Idx] = Res.get();
10719       }
10720     }
10721     if (VDecl->isInvalidDecl())
10722       return;
10723 
10724     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10725                                    /*TopLevelOfInitList=*/false,
10726                                    /*TreatUnavailableAsInvalid=*/false);
10727     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10728     if (Result.isInvalid()) {
10729       VDecl->setInvalidDecl();
10730       return;
10731     }
10732 
10733     Init = Result.getAs<Expr>();
10734   }
10735 
10736   // Check for self-references within variable initializers.
10737   // Variables declared within a function/method body (except for references)
10738   // are handled by a dataflow analysis.
10739   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10740       VDecl->getType()->isReferenceType()) {
10741     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10742   }
10743 
10744   // If the type changed, it means we had an incomplete type that was
10745   // completed by the initializer. For example:
10746   //   int ary[] = { 1, 3, 5 };
10747   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10748   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10749     VDecl->setType(DclT);
10750 
10751   if (!VDecl->isInvalidDecl()) {
10752     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10753 
10754     if (VDecl->hasAttr<BlocksAttr>())
10755       checkRetainCycles(VDecl, Init);
10756 
10757     // It is safe to assign a weak reference into a strong variable.
10758     // Although this code can still have problems:
10759     //   id x = self.weakProp;
10760     //   id y = self.weakProp;
10761     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10762     // paths through the function. This should be revisited if
10763     // -Wrepeated-use-of-weak is made flow-sensitive.
10764     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10765          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10766         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10767                          Init->getLocStart()))
10768       getCurFunction()->markSafeWeakUse(Init);
10769   }
10770 
10771   // The initialization is usually a full-expression.
10772   //
10773   // FIXME: If this is a braced initialization of an aggregate, it is not
10774   // an expression, and each individual field initializer is a separate
10775   // full-expression. For instance, in:
10776   //
10777   //   struct Temp { ~Temp(); };
10778   //   struct S { S(Temp); };
10779   //   struct T { S a, b; } t = { Temp(), Temp() }
10780   //
10781   // we should destroy the first Temp before constructing the second.
10782   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10783                                           false,
10784                                           VDecl->isConstexpr());
10785   if (Result.isInvalid()) {
10786     VDecl->setInvalidDecl();
10787     return;
10788   }
10789   Init = Result.get();
10790 
10791   // Attach the initializer to the decl.
10792   VDecl->setInit(Init);
10793 
10794   if (VDecl->isLocalVarDecl()) {
10795     // Don't check the initializer if the declaration is malformed.
10796     if (VDecl->isInvalidDecl()) {
10797       // do nothing
10798 
10799     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10800     // This is true even in OpenCL C++.
10801     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10802       CheckForConstantInitializer(Init, DclT);
10803 
10804     // Otherwise, C++ does not restrict the initializer.
10805     } else if (getLangOpts().CPlusPlus) {
10806       // do nothing
10807 
10808     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10809     // static storage duration shall be constant expressions or string literals.
10810     } else if (VDecl->getStorageClass() == SC_Static) {
10811       CheckForConstantInitializer(Init, DclT);
10812 
10813     // C89 is stricter than C99 for aggregate initializers.
10814     // C89 6.5.7p3: All the expressions [...] in an initializer list
10815     // for an object that has aggregate or union type shall be
10816     // constant expressions.
10817     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10818                isa<InitListExpr>(Init)) {
10819       const Expr *Culprit;
10820       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10821         Diag(Culprit->getExprLoc(),
10822              diag::ext_aggregate_init_not_constant)
10823           << Culprit->getSourceRange();
10824       }
10825     }
10826   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10827              VDecl->getLexicalDeclContext()->isRecord()) {
10828     // This is an in-class initialization for a static data member, e.g.,
10829     //
10830     // struct S {
10831     //   static const int value = 17;
10832     // };
10833 
10834     // C++ [class.mem]p4:
10835     //   A member-declarator can contain a constant-initializer only
10836     //   if it declares a static member (9.4) of const integral or
10837     //   const enumeration type, see 9.4.2.
10838     //
10839     // C++11 [class.static.data]p3:
10840     //   If a non-volatile non-inline const static data member is of integral
10841     //   or enumeration type, its declaration in the class definition can
10842     //   specify a brace-or-equal-initializer in which every initializer-clause
10843     //   that is an assignment-expression is a constant expression. A static
10844     //   data member of literal type can be declared in the class definition
10845     //   with the constexpr specifier; if so, its declaration shall specify a
10846     //   brace-or-equal-initializer in which every initializer-clause that is
10847     //   an assignment-expression is a constant expression.
10848 
10849     // Do nothing on dependent types.
10850     if (DclT->isDependentType()) {
10851 
10852     // Allow any 'static constexpr' members, whether or not they are of literal
10853     // type. We separately check that every constexpr variable is of literal
10854     // type.
10855     } else if (VDecl->isConstexpr()) {
10856 
10857     // Require constness.
10858     } else if (!DclT.isConstQualified()) {
10859       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10860         << Init->getSourceRange();
10861       VDecl->setInvalidDecl();
10862 
10863     // We allow integer constant expressions in all cases.
10864     } else if (DclT->isIntegralOrEnumerationType()) {
10865       // Check whether the expression is a constant expression.
10866       SourceLocation Loc;
10867       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10868         // In C++11, a non-constexpr const static data member with an
10869         // in-class initializer cannot be volatile.
10870         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10871       else if (Init->isValueDependent())
10872         ; // Nothing to check.
10873       else if (Init->isIntegerConstantExpr(Context, &Loc))
10874         ; // Ok, it's an ICE!
10875       else if (Init->isEvaluatable(Context)) {
10876         // If we can constant fold the initializer through heroics, accept it,
10877         // but report this as a use of an extension for -pedantic.
10878         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10879           << Init->getSourceRange();
10880       } else {
10881         // Otherwise, this is some crazy unknown case.  Report the issue at the
10882         // location provided by the isIntegerConstantExpr failed check.
10883         Diag(Loc, diag::err_in_class_initializer_non_constant)
10884           << Init->getSourceRange();
10885         VDecl->setInvalidDecl();
10886       }
10887 
10888     // We allow foldable floating-point constants as an extension.
10889     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10890       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10891       // it anyway and provide a fixit to add the 'constexpr'.
10892       if (getLangOpts().CPlusPlus11) {
10893         Diag(VDecl->getLocation(),
10894              diag::ext_in_class_initializer_float_type_cxx11)
10895             << DclT << Init->getSourceRange();
10896         Diag(VDecl->getLocStart(),
10897              diag::note_in_class_initializer_float_type_cxx11)
10898             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10899       } else {
10900         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10901           << DclT << Init->getSourceRange();
10902 
10903         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10904           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10905             << Init->getSourceRange();
10906           VDecl->setInvalidDecl();
10907         }
10908       }
10909 
10910     // Suggest adding 'constexpr' in C++11 for literal types.
10911     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10912       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10913         << DclT << Init->getSourceRange()
10914         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10915       VDecl->setConstexpr(true);
10916 
10917     } else {
10918       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10919         << DclT << Init->getSourceRange();
10920       VDecl->setInvalidDecl();
10921     }
10922   } else if (VDecl->isFileVarDecl()) {
10923     // In C, extern is typically used to avoid tentative definitions when
10924     // declaring variables in headers, but adding an intializer makes it a
10925     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10926     // In C++, extern is often used to give implictly static const variables
10927     // external linkage, so don't warn in that case. If selectany is present,
10928     // this might be header code intended for C and C++ inclusion, so apply the
10929     // C++ rules.
10930     if (VDecl->getStorageClass() == SC_Extern &&
10931         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10932          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10933         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10934         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10935       Diag(VDecl->getLocation(), diag::warn_extern_init);
10936 
10937     // C99 6.7.8p4. All file scoped initializers need to be constant.
10938     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10939       CheckForConstantInitializer(Init, DclT);
10940   }
10941 
10942   // We will represent direct-initialization similarly to copy-initialization:
10943   //    int x(1);  -as-> int x = 1;
10944   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10945   //
10946   // Clients that want to distinguish between the two forms, can check for
10947   // direct initializer using VarDecl::getInitStyle().
10948   // A major benefit is that clients that don't particularly care about which
10949   // exactly form was it (like the CodeGen) can handle both cases without
10950   // special case code.
10951 
10952   // C++ 8.5p11:
10953   // The form of initialization (using parentheses or '=') is generally
10954   // insignificant, but does matter when the entity being initialized has a
10955   // class type.
10956   if (CXXDirectInit) {
10957     assert(DirectInit && "Call-style initializer must be direct init.");
10958     VDecl->setInitStyle(VarDecl::CallInit);
10959   } else if (DirectInit) {
10960     // This must be list-initialization. No other way is direct-initialization.
10961     VDecl->setInitStyle(VarDecl::ListInit);
10962   }
10963 
10964   CheckCompleteVariableDeclaration(VDecl);
10965 }
10966 
10967 /// ActOnInitializerError - Given that there was an error parsing an
10968 /// initializer for the given declaration, try to return to some form
10969 /// of sanity.
10970 void Sema::ActOnInitializerError(Decl *D) {
10971   // Our main concern here is re-establishing invariants like "a
10972   // variable's type is either dependent or complete".
10973   if (!D || D->isInvalidDecl()) return;
10974 
10975   VarDecl *VD = dyn_cast<VarDecl>(D);
10976   if (!VD) return;
10977 
10978   // Bindings are not usable if we can't make sense of the initializer.
10979   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10980     for (auto *BD : DD->bindings())
10981       BD->setInvalidDecl();
10982 
10983   // Auto types are meaningless if we can't make sense of the initializer.
10984   if (ParsingInitForAutoVars.count(D)) {
10985     D->setInvalidDecl();
10986     return;
10987   }
10988 
10989   QualType Ty = VD->getType();
10990   if (Ty->isDependentType()) return;
10991 
10992   // Require a complete type.
10993   if (RequireCompleteType(VD->getLocation(),
10994                           Context.getBaseElementType(Ty),
10995                           diag::err_typecheck_decl_incomplete_type)) {
10996     VD->setInvalidDecl();
10997     return;
10998   }
10999 
11000   // Require a non-abstract type.
11001   if (RequireNonAbstractType(VD->getLocation(), Ty,
11002                              diag::err_abstract_type_in_decl,
11003                              AbstractVariableType)) {
11004     VD->setInvalidDecl();
11005     return;
11006   }
11007 
11008   // Don't bother complaining about constructors or destructors,
11009   // though.
11010 }
11011 
11012 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11013   // If there is no declaration, there was an error parsing it. Just ignore it.
11014   if (!RealDecl)
11015     return;
11016 
11017   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11018     QualType Type = Var->getType();
11019 
11020     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11021     if (isa<DecompositionDecl>(RealDecl)) {
11022       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11023       Var->setInvalidDecl();
11024       return;
11025     }
11026 
11027     if (Type->isUndeducedType() &&
11028         DeduceVariableDeclarationType(Var, false, nullptr))
11029       return;
11030 
11031     // C++11 [class.static.data]p3: A static data member can be declared with
11032     // the constexpr specifier; if so, its declaration shall specify
11033     // a brace-or-equal-initializer.
11034     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11035     // the definition of a variable [...] or the declaration of a static data
11036     // member.
11037     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11038         !Var->isThisDeclarationADemotedDefinition()) {
11039       if (Var->isStaticDataMember()) {
11040         // C++1z removes the relevant rule; the in-class declaration is always
11041         // a definition there.
11042         if (!getLangOpts().CPlusPlus17) {
11043           Diag(Var->getLocation(),
11044                diag::err_constexpr_static_mem_var_requires_init)
11045             << Var->getDeclName();
11046           Var->setInvalidDecl();
11047           return;
11048         }
11049       } else {
11050         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11051         Var->setInvalidDecl();
11052         return;
11053       }
11054     }
11055 
11056     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11057     // be initialized.
11058     if (!Var->isInvalidDecl() &&
11059         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11060         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11061       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11062       Var->setInvalidDecl();
11063       return;
11064     }
11065 
11066     switch (Var->isThisDeclarationADefinition()) {
11067     case VarDecl::Definition:
11068       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11069         break;
11070 
11071       // We have an out-of-line definition of a static data member
11072       // that has an in-class initializer, so we type-check this like
11073       // a declaration.
11074       //
11075       LLVM_FALLTHROUGH;
11076 
11077     case VarDecl::DeclarationOnly:
11078       // It's only a declaration.
11079 
11080       // Block scope. C99 6.7p7: If an identifier for an object is
11081       // declared with no linkage (C99 6.2.2p6), the type for the
11082       // object shall be complete.
11083       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11084           !Var->hasLinkage() && !Var->isInvalidDecl() &&
11085           RequireCompleteType(Var->getLocation(), Type,
11086                               diag::err_typecheck_decl_incomplete_type))
11087         Var->setInvalidDecl();
11088 
11089       // Make sure that the type is not abstract.
11090       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11091           RequireNonAbstractType(Var->getLocation(), Type,
11092                                  diag::err_abstract_type_in_decl,
11093                                  AbstractVariableType))
11094         Var->setInvalidDecl();
11095       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11096           Var->getStorageClass() == SC_PrivateExtern) {
11097         Diag(Var->getLocation(), diag::warn_private_extern);
11098         Diag(Var->getLocation(), diag::note_private_extern);
11099       }
11100 
11101       return;
11102 
11103     case VarDecl::TentativeDefinition:
11104       // File scope. C99 6.9.2p2: A declaration of an identifier for an
11105       // object that has file scope without an initializer, and without a
11106       // storage-class specifier or with the storage-class specifier "static",
11107       // constitutes a tentative definition. Note: A tentative definition with
11108       // external linkage is valid (C99 6.2.2p5).
11109       if (!Var->isInvalidDecl()) {
11110         if (const IncompleteArrayType *ArrayT
11111                                     = Context.getAsIncompleteArrayType(Type)) {
11112           if (RequireCompleteType(Var->getLocation(),
11113                                   ArrayT->getElementType(),
11114                                   diag::err_illegal_decl_array_incomplete_type))
11115             Var->setInvalidDecl();
11116         } else if (Var->getStorageClass() == SC_Static) {
11117           // C99 6.9.2p3: If the declaration of an identifier for an object is
11118           // a tentative definition and has internal linkage (C99 6.2.2p3), the
11119           // declared type shall not be an incomplete type.
11120           // NOTE: code such as the following
11121           //     static struct s;
11122           //     struct s { int a; };
11123           // is accepted by gcc. Hence here we issue a warning instead of
11124           // an error and we do not invalidate the static declaration.
11125           // NOTE: to avoid multiple warnings, only check the first declaration.
11126           if (Var->isFirstDecl())
11127             RequireCompleteType(Var->getLocation(), Type,
11128                                 diag::ext_typecheck_decl_incomplete_type);
11129         }
11130       }
11131 
11132       // Record the tentative definition; we're done.
11133       if (!Var->isInvalidDecl())
11134         TentativeDefinitions.push_back(Var);
11135       return;
11136     }
11137 
11138     // Provide a specific diagnostic for uninitialized variable
11139     // definitions with incomplete array type.
11140     if (Type->isIncompleteArrayType()) {
11141       Diag(Var->getLocation(),
11142            diag::err_typecheck_incomplete_array_needs_initializer);
11143       Var->setInvalidDecl();
11144       return;
11145     }
11146 
11147     // Provide a specific diagnostic for uninitialized variable
11148     // definitions with reference type.
11149     if (Type->isReferenceType()) {
11150       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11151         << Var->getDeclName()
11152         << SourceRange(Var->getLocation(), Var->getLocation());
11153       Var->setInvalidDecl();
11154       return;
11155     }
11156 
11157     // Do not attempt to type-check the default initializer for a
11158     // variable with dependent type.
11159     if (Type->isDependentType())
11160       return;
11161 
11162     if (Var->isInvalidDecl())
11163       return;
11164 
11165     if (!Var->hasAttr<AliasAttr>()) {
11166       if (RequireCompleteType(Var->getLocation(),
11167                               Context.getBaseElementType(Type),
11168                               diag::err_typecheck_decl_incomplete_type)) {
11169         Var->setInvalidDecl();
11170         return;
11171       }
11172     } else {
11173       return;
11174     }
11175 
11176     // The variable can not have an abstract class type.
11177     if (RequireNonAbstractType(Var->getLocation(), Type,
11178                                diag::err_abstract_type_in_decl,
11179                                AbstractVariableType)) {
11180       Var->setInvalidDecl();
11181       return;
11182     }
11183 
11184     // Check for jumps past the implicit initializer.  C++0x
11185     // clarifies that this applies to a "variable with automatic
11186     // storage duration", not a "local variable".
11187     // C++11 [stmt.dcl]p3
11188     //   A program that jumps from a point where a variable with automatic
11189     //   storage duration is not in scope to a point where it is in scope is
11190     //   ill-formed unless the variable has scalar type, class type with a
11191     //   trivial default constructor and a trivial destructor, a cv-qualified
11192     //   version of one of these types, or an array of one of the preceding
11193     //   types and is declared without an initializer.
11194     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11195       if (const RecordType *Record
11196             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11197         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11198         // Mark the function for further checking even if the looser rules of
11199         // C++11 do not require such checks, so that we can diagnose
11200         // incompatibilities with C++98.
11201         if (!CXXRecord->isPOD())
11202           getCurFunction()->setHasBranchProtectedScope();
11203       }
11204     }
11205 
11206     // C++03 [dcl.init]p9:
11207     //   If no initializer is specified for an object, and the
11208     //   object is of (possibly cv-qualified) non-POD class type (or
11209     //   array thereof), the object shall be default-initialized; if
11210     //   the object is of const-qualified type, the underlying class
11211     //   type shall have a user-declared default
11212     //   constructor. Otherwise, if no initializer is specified for
11213     //   a non- static object, the object and its subobjects, if
11214     //   any, have an indeterminate initial value); if the object
11215     //   or any of its subobjects are of const-qualified type, the
11216     //   program is ill-formed.
11217     // C++0x [dcl.init]p11:
11218     //   If no initializer is specified for an object, the object is
11219     //   default-initialized; [...].
11220     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11221     InitializationKind Kind
11222       = InitializationKind::CreateDefault(Var->getLocation());
11223 
11224     InitializationSequence InitSeq(*this, Entity, Kind, None);
11225     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11226     if (Init.isInvalid())
11227       Var->setInvalidDecl();
11228     else if (Init.get()) {
11229       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11230       // This is important for template substitution.
11231       Var->setInitStyle(VarDecl::CallInit);
11232     }
11233 
11234     CheckCompleteVariableDeclaration(Var);
11235   }
11236 }
11237 
11238 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11239   // If there is no declaration, there was an error parsing it. Ignore it.
11240   if (!D)
11241     return;
11242 
11243   VarDecl *VD = dyn_cast<VarDecl>(D);
11244   if (!VD) {
11245     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11246     D->setInvalidDecl();
11247     return;
11248   }
11249 
11250   VD->setCXXForRangeDecl(true);
11251 
11252   // for-range-declaration cannot be given a storage class specifier.
11253   int Error = -1;
11254   switch (VD->getStorageClass()) {
11255   case SC_None:
11256     break;
11257   case SC_Extern:
11258     Error = 0;
11259     break;
11260   case SC_Static:
11261     Error = 1;
11262     break;
11263   case SC_PrivateExtern:
11264     Error = 2;
11265     break;
11266   case SC_Auto:
11267     Error = 3;
11268     break;
11269   case SC_Register:
11270     Error = 4;
11271     break;
11272   }
11273   if (Error != -1) {
11274     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11275       << VD->getDeclName() << Error;
11276     D->setInvalidDecl();
11277   }
11278 }
11279 
11280 StmtResult
11281 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11282                                  IdentifierInfo *Ident,
11283                                  ParsedAttributes &Attrs,
11284                                  SourceLocation AttrEnd) {
11285   // C++1y [stmt.iter]p1:
11286   //   A range-based for statement of the form
11287   //      for ( for-range-identifier : for-range-initializer ) statement
11288   //   is equivalent to
11289   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11290   DeclSpec DS(Attrs.getPool().getFactory());
11291 
11292   const char *PrevSpec;
11293   unsigned DiagID;
11294   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11295                      getPrintingPolicy());
11296 
11297   Declarator D(DS, DeclaratorContext::ForContext);
11298   D.SetIdentifier(Ident, IdentLoc);
11299   D.takeAttributes(Attrs, AttrEnd);
11300 
11301   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11302   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11303                 EmptyAttrs, IdentLoc);
11304   Decl *Var = ActOnDeclarator(S, D);
11305   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11306   FinalizeDeclaration(Var);
11307   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11308                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11309 }
11310 
11311 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11312   if (var->isInvalidDecl()) return;
11313 
11314   if (getLangOpts().OpenCL) {
11315     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11316     // initialiser
11317     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11318         !var->hasInit()) {
11319       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11320           << 1 /*Init*/;
11321       var->setInvalidDecl();
11322       return;
11323     }
11324   }
11325 
11326   // In Objective-C, don't allow jumps past the implicit initialization of a
11327   // local retaining variable.
11328   if (getLangOpts().ObjC1 &&
11329       var->hasLocalStorage()) {
11330     switch (var->getType().getObjCLifetime()) {
11331     case Qualifiers::OCL_None:
11332     case Qualifiers::OCL_ExplicitNone:
11333     case Qualifiers::OCL_Autoreleasing:
11334       break;
11335 
11336     case Qualifiers::OCL_Weak:
11337     case Qualifiers::OCL_Strong:
11338       getCurFunction()->setHasBranchProtectedScope();
11339       break;
11340     }
11341   }
11342 
11343   // Warn about externally-visible variables being defined without a
11344   // prior declaration.  We only want to do this for global
11345   // declarations, but we also specifically need to avoid doing it for
11346   // class members because the linkage of an anonymous class can
11347   // change if it's later given a typedef name.
11348   if (var->isThisDeclarationADefinition() &&
11349       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11350       var->isExternallyVisible() && var->hasLinkage() &&
11351       !var->isInline() && !var->getDescribedVarTemplate() &&
11352       !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11353       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11354                                   var->getLocation())) {
11355     // Find a previous declaration that's not a definition.
11356     VarDecl *prev = var->getPreviousDecl();
11357     while (prev && prev->isThisDeclarationADefinition())
11358       prev = prev->getPreviousDecl();
11359 
11360     if (!prev)
11361       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11362   }
11363 
11364   // Cache the result of checking for constant initialization.
11365   Optional<bool> CacheHasConstInit;
11366   const Expr *CacheCulprit;
11367   auto checkConstInit = [&]() mutable {
11368     if (!CacheHasConstInit)
11369       CacheHasConstInit = var->getInit()->isConstantInitializer(
11370             Context, var->getType()->isReferenceType(), &CacheCulprit);
11371     return *CacheHasConstInit;
11372   };
11373 
11374   if (var->getTLSKind() == VarDecl::TLS_Static) {
11375     if (var->getType().isDestructedType()) {
11376       // GNU C++98 edits for __thread, [basic.start.term]p3:
11377       //   The type of an object with thread storage duration shall not
11378       //   have a non-trivial destructor.
11379       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11380       if (getLangOpts().CPlusPlus11)
11381         Diag(var->getLocation(), diag::note_use_thread_local);
11382     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11383       if (!checkConstInit()) {
11384         // GNU C++98 edits for __thread, [basic.start.init]p4:
11385         //   An object of thread storage duration shall not require dynamic
11386         //   initialization.
11387         // FIXME: Need strict checking here.
11388         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11389           << CacheCulprit->getSourceRange();
11390         if (getLangOpts().CPlusPlus11)
11391           Diag(var->getLocation(), diag::note_use_thread_local);
11392       }
11393     }
11394   }
11395 
11396   // Apply section attributes and pragmas to global variables.
11397   bool GlobalStorage = var->hasGlobalStorage();
11398   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11399       !inTemplateInstantiation()) {
11400     PragmaStack<StringLiteral *> *Stack = nullptr;
11401     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11402     if (var->getType().isConstQualified())
11403       Stack = &ConstSegStack;
11404     else if (!var->getInit()) {
11405       Stack = &BSSSegStack;
11406       SectionFlags |= ASTContext::PSF_Write;
11407     } else {
11408       Stack = &DataSegStack;
11409       SectionFlags |= ASTContext::PSF_Write;
11410     }
11411     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11412       var->addAttr(SectionAttr::CreateImplicit(
11413           Context, SectionAttr::Declspec_allocate,
11414           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11415     }
11416     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11417       if (UnifySection(SA->getName(), SectionFlags, var))
11418         var->dropAttr<SectionAttr>();
11419 
11420     // Apply the init_seg attribute if this has an initializer.  If the
11421     // initializer turns out to not be dynamic, we'll end up ignoring this
11422     // attribute.
11423     if (CurInitSeg && var->getInit())
11424       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11425                                                CurInitSegLoc));
11426   }
11427 
11428   // All the following checks are C++ only.
11429   if (!getLangOpts().CPlusPlus) {
11430       // If this variable must be emitted, add it as an initializer for the
11431       // current module.
11432      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11433        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11434      return;
11435   }
11436 
11437   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11438     CheckCompleteDecompositionDeclaration(DD);
11439 
11440   QualType type = var->getType();
11441   if (type->isDependentType()) return;
11442 
11443   // __block variables might require us to capture a copy-initializer.
11444   if (var->hasAttr<BlocksAttr>()) {
11445     // It's currently invalid to ever have a __block variable with an
11446     // array type; should we diagnose that here?
11447 
11448     // Regardless, we don't want to ignore array nesting when
11449     // constructing this copy.
11450     if (type->isStructureOrClassType()) {
11451       EnterExpressionEvaluationContext scope(
11452           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11453       SourceLocation poi = var->getLocation();
11454       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11455       ExprResult result
11456         = PerformMoveOrCopyInitialization(
11457             InitializedEntity::InitializeBlock(poi, type, false),
11458             var, var->getType(), varRef, /*AllowNRVO=*/true);
11459       if (!result.isInvalid()) {
11460         result = MaybeCreateExprWithCleanups(result);
11461         Expr *init = result.getAs<Expr>();
11462         Context.setBlockVarCopyInits(var, init);
11463       }
11464     }
11465   }
11466 
11467   Expr *Init = var->getInit();
11468   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11469   QualType baseType = Context.getBaseElementType(type);
11470 
11471   if (Init && !Init->isValueDependent()) {
11472     if (var->isConstexpr()) {
11473       SmallVector<PartialDiagnosticAt, 8> Notes;
11474       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11475         SourceLocation DiagLoc = var->getLocation();
11476         // If the note doesn't add any useful information other than a source
11477         // location, fold it into the primary diagnostic.
11478         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11479               diag::note_invalid_subexpr_in_const_expr) {
11480           DiagLoc = Notes[0].first;
11481           Notes.clear();
11482         }
11483         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11484           << var << Init->getSourceRange();
11485         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11486           Diag(Notes[I].first, Notes[I].second);
11487       }
11488     } else if (var->isUsableInConstantExpressions(Context)) {
11489       // Check whether the initializer of a const variable of integral or
11490       // enumeration type is an ICE now, since we can't tell whether it was
11491       // initialized by a constant expression if we check later.
11492       var->checkInitIsICE();
11493     }
11494 
11495     // Don't emit further diagnostics about constexpr globals since they
11496     // were just diagnosed.
11497     if (!var->isConstexpr() && GlobalStorage &&
11498             var->hasAttr<RequireConstantInitAttr>()) {
11499       // FIXME: Need strict checking in C++03 here.
11500       bool DiagErr = getLangOpts().CPlusPlus11
11501           ? !var->checkInitIsICE() : !checkConstInit();
11502       if (DiagErr) {
11503         auto attr = var->getAttr<RequireConstantInitAttr>();
11504         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11505           << Init->getSourceRange();
11506         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11507           << attr->getRange();
11508         if (getLangOpts().CPlusPlus11) {
11509           APValue Value;
11510           SmallVector<PartialDiagnosticAt, 8> Notes;
11511           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11512           for (auto &it : Notes)
11513             Diag(it.first, it.second);
11514         } else {
11515           Diag(CacheCulprit->getExprLoc(),
11516                diag::note_invalid_subexpr_in_const_expr)
11517               << CacheCulprit->getSourceRange();
11518         }
11519       }
11520     }
11521     else if (!var->isConstexpr() && IsGlobal &&
11522              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11523                                     var->getLocation())) {
11524       // Warn about globals which don't have a constant initializer.  Don't
11525       // warn about globals with a non-trivial destructor because we already
11526       // warned about them.
11527       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11528       if (!(RD && !RD->hasTrivialDestructor())) {
11529         if (!checkConstInit())
11530           Diag(var->getLocation(), diag::warn_global_constructor)
11531             << Init->getSourceRange();
11532       }
11533     }
11534   }
11535 
11536   // Require the destructor.
11537   if (const RecordType *recordType = baseType->getAs<RecordType>())
11538     FinalizeVarWithDestructor(var, recordType);
11539 
11540   // If this variable must be emitted, add it as an initializer for the current
11541   // module.
11542   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11543     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11544 }
11545 
11546 /// \brief Determines if a variable's alignment is dependent.
11547 static bool hasDependentAlignment(VarDecl *VD) {
11548   if (VD->getType()->isDependentType())
11549     return true;
11550   for (auto *I : VD->specific_attrs<AlignedAttr>())
11551     if (I->isAlignmentDependent())
11552       return true;
11553   return false;
11554 }
11555 
11556 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11557 /// any semantic actions necessary after any initializer has been attached.
11558 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11559   // Note that we are no longer parsing the initializer for this declaration.
11560   ParsingInitForAutoVars.erase(ThisDecl);
11561 
11562   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11563   if (!VD)
11564     return;
11565 
11566   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11567   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11568       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11569     if (PragmaClangBSSSection.Valid)
11570       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11571                                                             PragmaClangBSSSection.SectionName,
11572                                                             PragmaClangBSSSection.PragmaLocation));
11573     if (PragmaClangDataSection.Valid)
11574       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11575                                                              PragmaClangDataSection.SectionName,
11576                                                              PragmaClangDataSection.PragmaLocation));
11577     if (PragmaClangRodataSection.Valid)
11578       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11579                                                                PragmaClangRodataSection.SectionName,
11580                                                                PragmaClangRodataSection.PragmaLocation));
11581   }
11582 
11583   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11584     for (auto *BD : DD->bindings()) {
11585       FinalizeDeclaration(BD);
11586     }
11587   }
11588 
11589   checkAttributesAfterMerging(*this, *VD);
11590 
11591   // Perform TLS alignment check here after attributes attached to the variable
11592   // which may affect the alignment have been processed. Only perform the check
11593   // if the target has a maximum TLS alignment (zero means no constraints).
11594   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11595     // Protect the check so that it's not performed on dependent types and
11596     // dependent alignments (we can't determine the alignment in that case).
11597     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11598         !VD->isInvalidDecl()) {
11599       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11600       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11601         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11602           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11603           << (unsigned)MaxAlignChars.getQuantity();
11604       }
11605     }
11606   }
11607 
11608   if (VD->isStaticLocal()) {
11609     if (FunctionDecl *FD =
11610             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11611       // Static locals inherit dll attributes from their function.
11612       if (Attr *A = getDLLAttr(FD)) {
11613         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11614         NewAttr->setInherited(true);
11615         VD->addAttr(NewAttr);
11616       }
11617       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11618       // function, only __shared__ variables may be declared with
11619       // static storage class.
11620       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11621           CUDADiagIfDeviceCode(VD->getLocation(),
11622                                diag::err_device_static_local_var)
11623               << CurrentCUDATarget())
11624         VD->setInvalidDecl();
11625     }
11626   }
11627 
11628   // Perform check for initializers of device-side global variables.
11629   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11630   // 7.5). We must also apply the same checks to all __shared__
11631   // variables whether they are local or not. CUDA also allows
11632   // constant initializers for __constant__ and __device__ variables.
11633   if (getLangOpts().CUDA) {
11634     const Expr *Init = VD->getInit();
11635     if (Init && VD->hasGlobalStorage()) {
11636       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11637           VD->hasAttr<CUDASharedAttr>()) {
11638         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11639         bool AllowedInit = false;
11640         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11641           AllowedInit =
11642               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11643         // We'll allow constant initializers even if it's a non-empty
11644         // constructor according to CUDA rules. This deviates from NVCC,
11645         // but allows us to handle things like constexpr constructors.
11646         if (!AllowedInit &&
11647             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11648           AllowedInit = VD->getInit()->isConstantInitializer(
11649               Context, VD->getType()->isReferenceType());
11650 
11651         // Also make sure that destructor, if there is one, is empty.
11652         if (AllowedInit)
11653           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11654             AllowedInit =
11655                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11656 
11657         if (!AllowedInit) {
11658           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11659                                       ? diag::err_shared_var_init
11660                                       : diag::err_dynamic_var_init)
11661               << Init->getSourceRange();
11662           VD->setInvalidDecl();
11663         }
11664       } else {
11665         // This is a host-side global variable.  Check that the initializer is
11666         // callable from the host side.
11667         const FunctionDecl *InitFn = nullptr;
11668         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11669           InitFn = CE->getConstructor();
11670         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11671           InitFn = CE->getDirectCallee();
11672         }
11673         if (InitFn) {
11674           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11675           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11676             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11677                 << InitFnTarget << InitFn;
11678             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11679             VD->setInvalidDecl();
11680           }
11681         }
11682       }
11683     }
11684   }
11685 
11686   // Grab the dllimport or dllexport attribute off of the VarDecl.
11687   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11688 
11689   // Imported static data members cannot be defined out-of-line.
11690   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11691     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11692         VD->isThisDeclarationADefinition()) {
11693       // We allow definitions of dllimport class template static data members
11694       // with a warning.
11695       CXXRecordDecl *Context =
11696         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11697       bool IsClassTemplateMember =
11698           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11699           Context->getDescribedClassTemplate();
11700 
11701       Diag(VD->getLocation(),
11702            IsClassTemplateMember
11703                ? diag::warn_attribute_dllimport_static_field_definition
11704                : diag::err_attribute_dllimport_static_field_definition);
11705       Diag(IA->getLocation(), diag::note_attribute);
11706       if (!IsClassTemplateMember)
11707         VD->setInvalidDecl();
11708     }
11709   }
11710 
11711   // dllimport/dllexport variables cannot be thread local, their TLS index
11712   // isn't exported with the variable.
11713   if (DLLAttr && VD->getTLSKind()) {
11714     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11715     if (F && getDLLAttr(F)) {
11716       assert(VD->isStaticLocal());
11717       // But if this is a static local in a dlimport/dllexport function, the
11718       // function will never be inlined, which means the var would never be
11719       // imported, so having it marked import/export is safe.
11720     } else {
11721       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11722                                                                     << DLLAttr;
11723       VD->setInvalidDecl();
11724     }
11725   }
11726 
11727   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11728     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11729       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11730       VD->dropAttr<UsedAttr>();
11731     }
11732   }
11733 
11734   const DeclContext *DC = VD->getDeclContext();
11735   // If there's a #pragma GCC visibility in scope, and this isn't a class
11736   // member, set the visibility of this variable.
11737   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11738     AddPushedVisibilityAttribute(VD);
11739 
11740   // FIXME: Warn on unused var template partial specializations.
11741   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11742     MarkUnusedFileScopedDecl(VD);
11743 
11744   // Now we have parsed the initializer and can update the table of magic
11745   // tag values.
11746   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11747       !VD->getType()->isIntegralOrEnumerationType())
11748     return;
11749 
11750   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11751     const Expr *MagicValueExpr = VD->getInit();
11752     if (!MagicValueExpr) {
11753       continue;
11754     }
11755     llvm::APSInt MagicValueInt;
11756     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11757       Diag(I->getRange().getBegin(),
11758            diag::err_type_tag_for_datatype_not_ice)
11759         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11760       continue;
11761     }
11762     if (MagicValueInt.getActiveBits() > 64) {
11763       Diag(I->getRange().getBegin(),
11764            diag::err_type_tag_for_datatype_too_large)
11765         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11766       continue;
11767     }
11768     uint64_t MagicValue = MagicValueInt.getZExtValue();
11769     RegisterTypeTagForDatatype(I->getArgumentKind(),
11770                                MagicValue,
11771                                I->getMatchingCType(),
11772                                I->getLayoutCompatible(),
11773                                I->getMustBeNull());
11774   }
11775 }
11776 
11777 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11778   auto *VD = dyn_cast<VarDecl>(DD);
11779   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11780 }
11781 
11782 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11783                                                    ArrayRef<Decl *> Group) {
11784   SmallVector<Decl*, 8> Decls;
11785 
11786   if (DS.isTypeSpecOwned())
11787     Decls.push_back(DS.getRepAsDecl());
11788 
11789   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11790   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11791   bool DiagnosedMultipleDecomps = false;
11792   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11793   bool DiagnosedNonDeducedAuto = false;
11794 
11795   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11796     if (Decl *D = Group[i]) {
11797       // For declarators, there are some additional syntactic-ish checks we need
11798       // to perform.
11799       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11800         if (!FirstDeclaratorInGroup)
11801           FirstDeclaratorInGroup = DD;
11802         if (!FirstDecompDeclaratorInGroup)
11803           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11804         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11805             !hasDeducedAuto(DD))
11806           FirstNonDeducedAutoInGroup = DD;
11807 
11808         if (FirstDeclaratorInGroup != DD) {
11809           // A decomposition declaration cannot be combined with any other
11810           // declaration in the same group.
11811           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11812             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11813                  diag::err_decomp_decl_not_alone)
11814                 << FirstDeclaratorInGroup->getSourceRange()
11815                 << DD->getSourceRange();
11816             DiagnosedMultipleDecomps = true;
11817           }
11818 
11819           // A declarator that uses 'auto' in any way other than to declare a
11820           // variable with a deduced type cannot be combined with any other
11821           // declarator in the same group.
11822           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11823             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11824                  diag::err_auto_non_deduced_not_alone)
11825                 << FirstNonDeducedAutoInGroup->getType()
11826                        ->hasAutoForTrailingReturnType()
11827                 << FirstDeclaratorInGroup->getSourceRange()
11828                 << DD->getSourceRange();
11829             DiagnosedNonDeducedAuto = true;
11830           }
11831         }
11832       }
11833 
11834       Decls.push_back(D);
11835     }
11836   }
11837 
11838   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11839     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11840       handleTagNumbering(Tag, S);
11841       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11842           getLangOpts().CPlusPlus)
11843         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11844     }
11845   }
11846 
11847   return BuildDeclaratorGroup(Decls);
11848 }
11849 
11850 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11851 /// group, performing any necessary semantic checking.
11852 Sema::DeclGroupPtrTy
11853 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11854   // C++14 [dcl.spec.auto]p7: (DR1347)
11855   //   If the type that replaces the placeholder type is not the same in each
11856   //   deduction, the program is ill-formed.
11857   if (Group.size() > 1) {
11858     QualType Deduced;
11859     VarDecl *DeducedDecl = nullptr;
11860     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11861       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11862       if (!D || D->isInvalidDecl())
11863         break;
11864       DeducedType *DT = D->getType()->getContainedDeducedType();
11865       if (!DT || DT->getDeducedType().isNull())
11866         continue;
11867       if (Deduced.isNull()) {
11868         Deduced = DT->getDeducedType();
11869         DeducedDecl = D;
11870       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11871         auto *AT = dyn_cast<AutoType>(DT);
11872         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11873              diag::err_auto_different_deductions)
11874           << (AT ? (unsigned)AT->getKeyword() : 3)
11875           << Deduced << DeducedDecl->getDeclName()
11876           << DT->getDeducedType() << D->getDeclName()
11877           << DeducedDecl->getInit()->getSourceRange()
11878           << D->getInit()->getSourceRange();
11879         D->setInvalidDecl();
11880         break;
11881       }
11882     }
11883   }
11884 
11885   ActOnDocumentableDecls(Group);
11886 
11887   return DeclGroupPtrTy::make(
11888       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11889 }
11890 
11891 void Sema::ActOnDocumentableDecl(Decl *D) {
11892   ActOnDocumentableDecls(D);
11893 }
11894 
11895 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11896   // Don't parse the comment if Doxygen diagnostics are ignored.
11897   if (Group.empty() || !Group[0])
11898     return;
11899 
11900   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11901                       Group[0]->getLocation()) &&
11902       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11903                       Group[0]->getLocation()))
11904     return;
11905 
11906   if (Group.size() >= 2) {
11907     // This is a decl group.  Normally it will contain only declarations
11908     // produced from declarator list.  But in case we have any definitions or
11909     // additional declaration references:
11910     //   'typedef struct S {} S;'
11911     //   'typedef struct S *S;'
11912     //   'struct S *pS;'
11913     // FinalizeDeclaratorGroup adds these as separate declarations.
11914     Decl *MaybeTagDecl = Group[0];
11915     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11916       Group = Group.slice(1);
11917     }
11918   }
11919 
11920   // See if there are any new comments that are not attached to a decl.
11921   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11922   if (!Comments.empty() &&
11923       !Comments.back()->isAttached()) {
11924     // There is at least one comment that not attached to a decl.
11925     // Maybe it should be attached to one of these decls?
11926     //
11927     // Note that this way we pick up not only comments that precede the
11928     // declaration, but also comments that *follow* the declaration -- thanks to
11929     // the lookahead in the lexer: we've consumed the semicolon and looked
11930     // ahead through comments.
11931     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11932       Context.getCommentForDecl(Group[i], &PP);
11933   }
11934 }
11935 
11936 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11937 /// to introduce parameters into function prototype scope.
11938 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11939   const DeclSpec &DS = D.getDeclSpec();
11940 
11941   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11942 
11943   // C++03 [dcl.stc]p2 also permits 'auto'.
11944   StorageClass SC = SC_None;
11945   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11946     SC = SC_Register;
11947     // In C++11, the 'register' storage class specifier is deprecated.
11948     // In C++17, it is not allowed, but we tolerate it as an extension.
11949     if (getLangOpts().CPlusPlus11) {
11950       Diag(DS.getStorageClassSpecLoc(),
11951            getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
11952                                      : diag::warn_deprecated_register)
11953         << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11954     }
11955   } else if (getLangOpts().CPlusPlus &&
11956              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11957     SC = SC_Auto;
11958   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11959     Diag(DS.getStorageClassSpecLoc(),
11960          diag::err_invalid_storage_class_in_func_decl);
11961     D.getMutableDeclSpec().ClearStorageClassSpecs();
11962   }
11963 
11964   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11965     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11966       << DeclSpec::getSpecifierName(TSCS);
11967   if (DS.isInlineSpecified())
11968     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11969         << getLangOpts().CPlusPlus17;
11970   if (DS.isConstexprSpecified())
11971     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11972       << 0;
11973 
11974   DiagnoseFunctionSpecifiers(DS);
11975 
11976   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11977   QualType parmDeclType = TInfo->getType();
11978 
11979   if (getLangOpts().CPlusPlus) {
11980     // Check that there are no default arguments inside the type of this
11981     // parameter.
11982     CheckExtraCXXDefaultArguments(D);
11983 
11984     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11985     if (D.getCXXScopeSpec().isSet()) {
11986       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11987         << D.getCXXScopeSpec().getRange();
11988       D.getCXXScopeSpec().clear();
11989     }
11990   }
11991 
11992   // Ensure we have a valid name
11993   IdentifierInfo *II = nullptr;
11994   if (D.hasName()) {
11995     II = D.getIdentifier();
11996     if (!II) {
11997       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11998         << GetNameForDeclarator(D).getName();
11999       D.setInvalidType(true);
12000     }
12001   }
12002 
12003   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12004   if (II) {
12005     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12006                    ForVisibleRedeclaration);
12007     LookupName(R, S);
12008     if (R.isSingleResult()) {
12009       NamedDecl *PrevDecl = R.getFoundDecl();
12010       if (PrevDecl->isTemplateParameter()) {
12011         // Maybe we will complain about the shadowed template parameter.
12012         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12013         // Just pretend that we didn't see the previous declaration.
12014         PrevDecl = nullptr;
12015       } else if (S->isDeclScope(PrevDecl)) {
12016         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12017         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12018 
12019         // Recover by removing the name
12020         II = nullptr;
12021         D.SetIdentifier(nullptr, D.getIdentifierLoc());
12022         D.setInvalidType(true);
12023       }
12024     }
12025   }
12026 
12027   // Temporarily put parameter variables in the translation unit, not
12028   // the enclosing context.  This prevents them from accidentally
12029   // looking like class members in C++.
12030   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12031                                     D.getLocStart(),
12032                                     D.getIdentifierLoc(), II,
12033                                     parmDeclType, TInfo,
12034                                     SC);
12035 
12036   if (D.isInvalidType())
12037     New->setInvalidDecl();
12038 
12039   assert(S->isFunctionPrototypeScope());
12040   assert(S->getFunctionPrototypeDepth() >= 1);
12041   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12042                     S->getNextFunctionPrototypeIndex());
12043 
12044   // Add the parameter declaration into this scope.
12045   S->AddDecl(New);
12046   if (II)
12047     IdResolver.AddDecl(New);
12048 
12049   ProcessDeclAttributes(S, New, D);
12050 
12051   if (D.getDeclSpec().isModulePrivateSpecified())
12052     Diag(New->getLocation(), diag::err_module_private_local)
12053       << 1 << New->getDeclName()
12054       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12055       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12056 
12057   if (New->hasAttr<BlocksAttr>()) {
12058     Diag(New->getLocation(), diag::err_block_on_nonlocal);
12059   }
12060   return New;
12061 }
12062 
12063 /// \brief Synthesizes a variable for a parameter arising from a
12064 /// typedef.
12065 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12066                                               SourceLocation Loc,
12067                                               QualType T) {
12068   /* FIXME: setting StartLoc == Loc.
12069      Would it be worth to modify callers so as to provide proper source
12070      location for the unnamed parameters, embedding the parameter's type? */
12071   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12072                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
12073                                            SC_None, nullptr);
12074   Param->setImplicit();
12075   return Param;
12076 }
12077 
12078 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12079   // Don't diagnose unused-parameter errors in template instantiations; we
12080   // will already have done so in the template itself.
12081   if (inTemplateInstantiation())
12082     return;
12083 
12084   for (const ParmVarDecl *Parameter : Parameters) {
12085     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12086         !Parameter->hasAttr<UnusedAttr>()) {
12087       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12088         << Parameter->getDeclName();
12089     }
12090   }
12091 }
12092 
12093 void Sema::DiagnoseSizeOfParametersAndReturnValue(
12094     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12095   if (LangOpts.NumLargeByValueCopy == 0) // No check.
12096     return;
12097 
12098   // Warn if the return value is pass-by-value and larger than the specified
12099   // threshold.
12100   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12101     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12102     if (Size > LangOpts.NumLargeByValueCopy)
12103       Diag(D->getLocation(), diag::warn_return_value_size)
12104           << D->getDeclName() << Size;
12105   }
12106 
12107   // Warn if any parameter is pass-by-value and larger than the specified
12108   // threshold.
12109   for (const ParmVarDecl *Parameter : Parameters) {
12110     QualType T = Parameter->getType();
12111     if (T->isDependentType() || !T.isPODType(Context))
12112       continue;
12113     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12114     if (Size > LangOpts.NumLargeByValueCopy)
12115       Diag(Parameter->getLocation(), diag::warn_parameter_size)
12116           << Parameter->getDeclName() << Size;
12117   }
12118 }
12119 
12120 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12121                                   SourceLocation NameLoc, IdentifierInfo *Name,
12122                                   QualType T, TypeSourceInfo *TSInfo,
12123                                   StorageClass SC) {
12124   // In ARC, infer a lifetime qualifier for appropriate parameter types.
12125   if (getLangOpts().ObjCAutoRefCount &&
12126       T.getObjCLifetime() == Qualifiers::OCL_None &&
12127       T->isObjCLifetimeType()) {
12128 
12129     Qualifiers::ObjCLifetime lifetime;
12130 
12131     // Special cases for arrays:
12132     //   - if it's const, use __unsafe_unretained
12133     //   - otherwise, it's an error
12134     if (T->isArrayType()) {
12135       if (!T.isConstQualified()) {
12136         DelayedDiagnostics.add(
12137             sema::DelayedDiagnostic::makeForbiddenType(
12138             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12139       }
12140       lifetime = Qualifiers::OCL_ExplicitNone;
12141     } else {
12142       lifetime = T->getObjCARCImplicitLifetime();
12143     }
12144     T = Context.getLifetimeQualifiedType(T, lifetime);
12145   }
12146 
12147   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12148                                          Context.getAdjustedParameterType(T),
12149                                          TSInfo, SC, nullptr);
12150 
12151   // Parameters can not be abstract class types.
12152   // For record types, this is done by the AbstractClassUsageDiagnoser once
12153   // the class has been completely parsed.
12154   if (!CurContext->isRecord() &&
12155       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12156                              AbstractParamType))
12157     New->setInvalidDecl();
12158 
12159   // Parameter declarators cannot be interface types. All ObjC objects are
12160   // passed by reference.
12161   if (T->isObjCObjectType()) {
12162     SourceLocation TypeEndLoc =
12163         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12164     Diag(NameLoc,
12165          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12166       << FixItHint::CreateInsertion(TypeEndLoc, "*");
12167     T = Context.getObjCObjectPointerType(T);
12168     New->setType(T);
12169   }
12170 
12171   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12172   // duration shall not be qualified by an address-space qualifier."
12173   // Since all parameters have automatic store duration, they can not have
12174   // an address space.
12175   if (T.getAddressSpace() != LangAS::Default &&
12176       // OpenCL allows function arguments declared to be an array of a type
12177       // to be qualified with an address space.
12178       !(getLangOpts().OpenCL &&
12179         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12180     Diag(NameLoc, diag::err_arg_with_address_space);
12181     New->setInvalidDecl();
12182   }
12183 
12184   return New;
12185 }
12186 
12187 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12188                                            SourceLocation LocAfterDecls) {
12189   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12190 
12191   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12192   // for a K&R function.
12193   if (!FTI.hasPrototype) {
12194     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12195       --i;
12196       if (FTI.Params[i].Param == nullptr) {
12197         SmallString<256> Code;
12198         llvm::raw_svector_ostream(Code)
12199             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12200         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12201             << FTI.Params[i].Ident
12202             << FixItHint::CreateInsertion(LocAfterDecls, Code);
12203 
12204         // Implicitly declare the argument as type 'int' for lack of a better
12205         // type.
12206         AttributeFactory attrs;
12207         DeclSpec DS(attrs);
12208         const char* PrevSpec; // unused
12209         unsigned DiagID; // unused
12210         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12211                            DiagID, Context.getPrintingPolicy());
12212         // Use the identifier location for the type source range.
12213         DS.SetRangeStart(FTI.Params[i].IdentLoc);
12214         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12215         Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12216         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12217         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12218       }
12219     }
12220   }
12221 }
12222 
12223 Decl *
12224 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12225                               MultiTemplateParamsArg TemplateParameterLists,
12226                               SkipBodyInfo *SkipBody) {
12227   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12228   assert(D.isFunctionDeclarator() && "Not a function declarator!");
12229   Scope *ParentScope = FnBodyScope->getParent();
12230 
12231   D.setFunctionDefinitionKind(FDK_Definition);
12232   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12233   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12234 }
12235 
12236 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12237   Consumer.HandleInlineFunctionDefinition(D);
12238 }
12239 
12240 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12241                              const FunctionDecl*& PossibleZeroParamPrototype) {
12242   // Don't warn about invalid declarations.
12243   if (FD->isInvalidDecl())
12244     return false;
12245 
12246   // Or declarations that aren't global.
12247   if (!FD->isGlobal())
12248     return false;
12249 
12250   // Don't warn about C++ member functions.
12251   if (isa<CXXMethodDecl>(FD))
12252     return false;
12253 
12254   // Don't warn about 'main'.
12255   if (FD->isMain())
12256     return false;
12257 
12258   // Don't warn about inline functions.
12259   if (FD->isInlined())
12260     return false;
12261 
12262   // Don't warn about function templates.
12263   if (FD->getDescribedFunctionTemplate())
12264     return false;
12265 
12266   // Don't warn about function template specializations.
12267   if (FD->isFunctionTemplateSpecialization())
12268     return false;
12269 
12270   // Don't warn for OpenCL kernels.
12271   if (FD->hasAttr<OpenCLKernelAttr>())
12272     return false;
12273 
12274   // Don't warn on explicitly deleted functions.
12275   if (FD->isDeleted())
12276     return false;
12277 
12278   bool MissingPrototype = true;
12279   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12280        Prev; Prev = Prev->getPreviousDecl()) {
12281     // Ignore any declarations that occur in function or method
12282     // scope, because they aren't visible from the header.
12283     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12284       continue;
12285 
12286     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12287     if (FD->getNumParams() == 0)
12288       PossibleZeroParamPrototype = Prev;
12289     break;
12290   }
12291 
12292   return MissingPrototype;
12293 }
12294 
12295 void
12296 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12297                                    const FunctionDecl *EffectiveDefinition,
12298                                    SkipBodyInfo *SkipBody) {
12299   const FunctionDecl *Definition = EffectiveDefinition;
12300   if (!Definition)
12301     if (!FD->isDefined(Definition))
12302       return;
12303 
12304   if (canRedefineFunction(Definition, getLangOpts()))
12305     return;
12306 
12307   // Don't emit an error when this is redefinition of a typo-corrected
12308   // definition.
12309   if (TypoCorrectedFunctionDefinitions.count(Definition))
12310     return;
12311 
12312   // If we don't have a visible definition of the function, and it's inline or
12313   // a template, skip the new definition.
12314   if (SkipBody && !hasVisibleDefinition(Definition) &&
12315       (Definition->getFormalLinkage() == InternalLinkage ||
12316        Definition->isInlined() ||
12317        Definition->getDescribedFunctionTemplate() ||
12318        Definition->getNumTemplateParameterLists())) {
12319     SkipBody->ShouldSkip = true;
12320     if (auto *TD = Definition->getDescribedFunctionTemplate())
12321       makeMergedDefinitionVisible(TD);
12322     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12323     return;
12324   }
12325 
12326   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12327       Definition->getStorageClass() == SC_Extern)
12328     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12329         << FD->getDeclName() << getLangOpts().CPlusPlus;
12330   else
12331     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12332 
12333   Diag(Definition->getLocation(), diag::note_previous_definition);
12334   FD->setInvalidDecl();
12335 }
12336 
12337 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12338                                    Sema &S) {
12339   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12340 
12341   LambdaScopeInfo *LSI = S.PushLambdaScope();
12342   LSI->CallOperator = CallOperator;
12343   LSI->Lambda = LambdaClass;
12344   LSI->ReturnType = CallOperator->getReturnType();
12345   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12346 
12347   if (LCD == LCD_None)
12348     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12349   else if (LCD == LCD_ByCopy)
12350     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12351   else if (LCD == LCD_ByRef)
12352     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12353   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12354 
12355   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12356   LSI->Mutable = !CallOperator->isConst();
12357 
12358   // Add the captures to the LSI so they can be noted as already
12359   // captured within tryCaptureVar.
12360   auto I = LambdaClass->field_begin();
12361   for (const auto &C : LambdaClass->captures()) {
12362     if (C.capturesVariable()) {
12363       VarDecl *VD = C.getCapturedVar();
12364       if (VD->isInitCapture())
12365         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12366       QualType CaptureType = VD->getType();
12367       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12368       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12369           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12370           /*EllipsisLoc*/C.isPackExpansion()
12371                          ? C.getEllipsisLoc() : SourceLocation(),
12372           CaptureType, /*Expr*/ nullptr);
12373 
12374     } else if (C.capturesThis()) {
12375       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12376                               /*Expr*/ nullptr,
12377                               C.getCaptureKind() == LCK_StarThis);
12378     } else {
12379       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12380     }
12381     ++I;
12382   }
12383 }
12384 
12385 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12386                                     SkipBodyInfo *SkipBody) {
12387   if (!D)
12388     return D;
12389   FunctionDecl *FD = nullptr;
12390 
12391   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12392     FD = FunTmpl->getTemplatedDecl();
12393   else
12394     FD = cast<FunctionDecl>(D);
12395 
12396   // Check for defining attributes before the check for redefinition.
12397   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12398     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12399     FD->dropAttr<AliasAttr>();
12400     FD->setInvalidDecl();
12401   }
12402   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12403     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12404     FD->dropAttr<IFuncAttr>();
12405     FD->setInvalidDecl();
12406   }
12407 
12408   // See if this is a redefinition. If 'will have body' is already set, then
12409   // these checks were already performed when it was set.
12410   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12411     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12412 
12413     // If we're skipping the body, we're done. Don't enter the scope.
12414     if (SkipBody && SkipBody->ShouldSkip)
12415       return D;
12416   }
12417 
12418   // Mark this function as "will have a body eventually".  This lets users to
12419   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12420   // this function.
12421   FD->setWillHaveBody();
12422 
12423   // If we are instantiating a generic lambda call operator, push
12424   // a LambdaScopeInfo onto the function stack.  But use the information
12425   // that's already been calculated (ActOnLambdaExpr) to prime the current
12426   // LambdaScopeInfo.
12427   // When the template operator is being specialized, the LambdaScopeInfo,
12428   // has to be properly restored so that tryCaptureVariable doesn't try
12429   // and capture any new variables. In addition when calculating potential
12430   // captures during transformation of nested lambdas, it is necessary to
12431   // have the LSI properly restored.
12432   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12433     assert(inTemplateInstantiation() &&
12434            "There should be an active template instantiation on the stack "
12435            "when instantiating a generic lambda!");
12436     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12437   } else {
12438     // Enter a new function scope
12439     PushFunctionScope();
12440   }
12441 
12442   // Builtin functions cannot be defined.
12443   if (unsigned BuiltinID = FD->getBuiltinID()) {
12444     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12445         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12446       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12447       FD->setInvalidDecl();
12448     }
12449   }
12450 
12451   // The return type of a function definition must be complete
12452   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12453   QualType ResultType = FD->getReturnType();
12454   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12455       !FD->isInvalidDecl() &&
12456       RequireCompleteType(FD->getLocation(), ResultType,
12457                           diag::err_func_def_incomplete_result))
12458     FD->setInvalidDecl();
12459 
12460   if (FnBodyScope)
12461     PushDeclContext(FnBodyScope, FD);
12462 
12463   // Check the validity of our function parameters
12464   CheckParmsForFunctionDef(FD->parameters(),
12465                            /*CheckParameterNames=*/true);
12466 
12467   // Add non-parameter declarations already in the function to the current
12468   // scope.
12469   if (FnBodyScope) {
12470     for (Decl *NPD : FD->decls()) {
12471       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12472       if (!NonParmDecl)
12473         continue;
12474       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12475              "parameters should not be in newly created FD yet");
12476 
12477       // If the decl has a name, make it accessible in the current scope.
12478       if (NonParmDecl->getDeclName())
12479         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12480 
12481       // Similarly, dive into enums and fish their constants out, making them
12482       // accessible in this scope.
12483       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12484         for (auto *EI : ED->enumerators())
12485           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12486       }
12487     }
12488   }
12489 
12490   // Introduce our parameters into the function scope
12491   for (auto Param : FD->parameters()) {
12492     Param->setOwningFunction(FD);
12493 
12494     // If this has an identifier, add it to the scope stack.
12495     if (Param->getIdentifier() && FnBodyScope) {
12496       CheckShadow(FnBodyScope, Param);
12497 
12498       PushOnScopeChains(Param, FnBodyScope);
12499     }
12500   }
12501 
12502   // Ensure that the function's exception specification is instantiated.
12503   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12504     ResolveExceptionSpec(D->getLocation(), FPT);
12505 
12506   // dllimport cannot be applied to non-inline function definitions.
12507   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12508       !FD->isTemplateInstantiation()) {
12509     assert(!FD->hasAttr<DLLExportAttr>());
12510     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12511     FD->setInvalidDecl();
12512     return D;
12513   }
12514   // We want to attach documentation to original Decl (which might be
12515   // a function template).
12516   ActOnDocumentableDecl(D);
12517   if (getCurLexicalContext()->isObjCContainer() &&
12518       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12519       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12520     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12521 
12522   return D;
12523 }
12524 
12525 /// \brief Given the set of return statements within a function body,
12526 /// compute the variables that are subject to the named return value
12527 /// optimization.
12528 ///
12529 /// Each of the variables that is subject to the named return value
12530 /// optimization will be marked as NRVO variables in the AST, and any
12531 /// return statement that has a marked NRVO variable as its NRVO candidate can
12532 /// use the named return value optimization.
12533 ///
12534 /// This function applies a very simplistic algorithm for NRVO: if every return
12535 /// statement in the scope of a variable has the same NRVO candidate, that
12536 /// candidate is an NRVO variable.
12537 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12538   ReturnStmt **Returns = Scope->Returns.data();
12539 
12540   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12541     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12542       if (!NRVOCandidate->isNRVOVariable())
12543         Returns[I]->setNRVOCandidate(nullptr);
12544     }
12545   }
12546 }
12547 
12548 bool Sema::canDelayFunctionBody(const Declarator &D) {
12549   // We can't delay parsing the body of a constexpr function template (yet).
12550   if (D.getDeclSpec().isConstexprSpecified())
12551     return false;
12552 
12553   // We can't delay parsing the body of a function template with a deduced
12554   // return type (yet).
12555   if (D.getDeclSpec().hasAutoTypeSpec()) {
12556     // If the placeholder introduces a non-deduced trailing return type,
12557     // we can still delay parsing it.
12558     if (D.getNumTypeObjects()) {
12559       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12560       if (Outer.Kind == DeclaratorChunk::Function &&
12561           Outer.Fun.hasTrailingReturnType()) {
12562         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12563         return Ty.isNull() || !Ty->isUndeducedType();
12564       }
12565     }
12566     return false;
12567   }
12568 
12569   return true;
12570 }
12571 
12572 bool Sema::canSkipFunctionBody(Decl *D) {
12573   // We cannot skip the body of a function (or function template) which is
12574   // constexpr, since we may need to evaluate its body in order to parse the
12575   // rest of the file.
12576   // We cannot skip the body of a function with an undeduced return type,
12577   // because any callers of that function need to know the type.
12578   if (const FunctionDecl *FD = D->getAsFunction())
12579     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12580       return false;
12581   return Consumer.shouldSkipFunctionBody(D);
12582 }
12583 
12584 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12585   if (!Decl)
12586     return nullptr;
12587   if (FunctionDecl *FD = Decl->getAsFunction())
12588     FD->setHasSkippedBody();
12589   else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12590     MD->setHasSkippedBody();
12591   return Decl;
12592 }
12593 
12594 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12595   return ActOnFinishFunctionBody(D, BodyArg, false);
12596 }
12597 
12598 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12599                                     bool IsInstantiation) {
12600   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12601 
12602   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12603   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12604 
12605   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12606     CheckCompletedCoroutineBody(FD, Body);
12607 
12608   if (FD) {
12609     FD->setBody(Body);
12610     FD->setWillHaveBody(false);
12611 
12612     if (getLangOpts().CPlusPlus14) {
12613       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12614           FD->getReturnType()->isUndeducedType()) {
12615         // If the function has a deduced result type but contains no 'return'
12616         // statements, the result type as written must be exactly 'auto', and
12617         // the deduced result type is 'void'.
12618         if (!FD->getReturnType()->getAs<AutoType>()) {
12619           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12620               << FD->getReturnType();
12621           FD->setInvalidDecl();
12622         } else {
12623           // Substitute 'void' for the 'auto' in the type.
12624           TypeLoc ResultType = getReturnTypeLoc(FD);
12625           Context.adjustDeducedFunctionResultType(
12626               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12627         }
12628       }
12629     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12630       // In C++11, we don't use 'auto' deduction rules for lambda call
12631       // operators because we don't support return type deduction.
12632       auto *LSI = getCurLambda();
12633       if (LSI->HasImplicitReturnType) {
12634         deduceClosureReturnType(*LSI);
12635 
12636         // C++11 [expr.prim.lambda]p4:
12637         //   [...] if there are no return statements in the compound-statement
12638         //   [the deduced type is] the type void
12639         QualType RetType =
12640             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12641 
12642         // Update the return type to the deduced type.
12643         const FunctionProtoType *Proto =
12644             FD->getType()->getAs<FunctionProtoType>();
12645         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12646                                             Proto->getExtProtoInfo()));
12647       }
12648     }
12649 
12650     // If the function implicitly returns zero (like 'main') or is naked,
12651     // don't complain about missing return statements.
12652     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12653       WP.disableCheckFallThrough();
12654 
12655     // MSVC permits the use of pure specifier (=0) on function definition,
12656     // defined at class scope, warn about this non-standard construct.
12657     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12658       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12659 
12660     if (!FD->isInvalidDecl()) {
12661       // Don't diagnose unused parameters of defaulted or deleted functions.
12662       if (!FD->isDeleted() && !FD->isDefaulted())
12663         DiagnoseUnusedParameters(FD->parameters());
12664       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12665                                              FD->getReturnType(), FD);
12666 
12667       // If this is a structor, we need a vtable.
12668       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12669         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12670       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12671         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12672 
12673       // Try to apply the named return value optimization. We have to check
12674       // if we can do this here because lambdas keep return statements around
12675       // to deduce an implicit return type.
12676       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12677           !FD->isDependentContext())
12678         computeNRVO(Body, getCurFunction());
12679     }
12680 
12681     // GNU warning -Wmissing-prototypes:
12682     //   Warn if a global function is defined without a previous
12683     //   prototype declaration. This warning is issued even if the
12684     //   definition itself provides a prototype. The aim is to detect
12685     //   global functions that fail to be declared in header files.
12686     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12687     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12688       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12689 
12690       if (PossibleZeroParamPrototype) {
12691         // We found a declaration that is not a prototype,
12692         // but that could be a zero-parameter prototype
12693         if (TypeSourceInfo *TI =
12694                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12695           TypeLoc TL = TI->getTypeLoc();
12696           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12697             Diag(PossibleZeroParamPrototype->getLocation(),
12698                  diag::note_declaration_not_a_prototype)
12699                 << PossibleZeroParamPrototype
12700                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12701         }
12702       }
12703 
12704       // GNU warning -Wstrict-prototypes
12705       //   Warn if K&R function is defined without a previous declaration.
12706       //   This warning is issued only if the definition itself does not provide
12707       //   a prototype. Only K&R definitions do not provide a prototype.
12708       //   An empty list in a function declarator that is part of a definition
12709       //   of that function specifies that the function has no parameters
12710       //   (C99 6.7.5.3p14)
12711       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12712           !LangOpts.CPlusPlus) {
12713         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12714         TypeLoc TL = TI->getTypeLoc();
12715         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12716         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12717       }
12718     }
12719 
12720     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12721       const CXXMethodDecl *KeyFunction;
12722       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12723           MD->isVirtual() &&
12724           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12725           MD == KeyFunction->getCanonicalDecl()) {
12726         // Update the key-function state if necessary for this ABI.
12727         if (FD->isInlined() &&
12728             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12729           Context.setNonKeyFunction(MD);
12730 
12731           // If the newly-chosen key function is already defined, then we
12732           // need to mark the vtable as used retroactively.
12733           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12734           const FunctionDecl *Definition;
12735           if (KeyFunction && KeyFunction->isDefined(Definition))
12736             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12737         } else {
12738           // We just defined they key function; mark the vtable as used.
12739           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12740         }
12741       }
12742     }
12743 
12744     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12745            "Function parsing confused");
12746   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12747     assert(MD == getCurMethodDecl() && "Method parsing confused");
12748     MD->setBody(Body);
12749     if (!MD->isInvalidDecl()) {
12750       DiagnoseUnusedParameters(MD->parameters());
12751       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12752                                              MD->getReturnType(), MD);
12753 
12754       if (Body)
12755         computeNRVO(Body, getCurFunction());
12756     }
12757     if (getCurFunction()->ObjCShouldCallSuper) {
12758       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12759         << MD->getSelector().getAsString();
12760       getCurFunction()->ObjCShouldCallSuper = false;
12761     }
12762     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12763       const ObjCMethodDecl *InitMethod = nullptr;
12764       bool isDesignated =
12765           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12766       assert(isDesignated && InitMethod);
12767       (void)isDesignated;
12768 
12769       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12770         auto IFace = MD->getClassInterface();
12771         if (!IFace)
12772           return false;
12773         auto SuperD = IFace->getSuperClass();
12774         if (!SuperD)
12775           return false;
12776         return SuperD->getIdentifier() ==
12777             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12778       };
12779       // Don't issue this warning for unavailable inits or direct subclasses
12780       // of NSObject.
12781       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12782         Diag(MD->getLocation(),
12783              diag::warn_objc_designated_init_missing_super_call);
12784         Diag(InitMethod->getLocation(),
12785              diag::note_objc_designated_init_marked_here);
12786       }
12787       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12788     }
12789     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12790       // Don't issue this warning for unavaialable inits.
12791       if (!MD->isUnavailable())
12792         Diag(MD->getLocation(),
12793              diag::warn_objc_secondary_init_missing_init_call);
12794       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12795     }
12796   } else {
12797     return nullptr;
12798   }
12799 
12800   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12801     DiagnoseUnguardedAvailabilityViolations(dcl);
12802 
12803   assert(!getCurFunction()->ObjCShouldCallSuper &&
12804          "This should only be set for ObjC methods, which should have been "
12805          "handled in the block above.");
12806 
12807   // Verify and clean out per-function state.
12808   if (Body && (!FD || !FD->isDefaulted())) {
12809     // C++ constructors that have function-try-blocks can't have return
12810     // statements in the handlers of that block. (C++ [except.handle]p14)
12811     // Verify this.
12812     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12813       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12814 
12815     // Verify that gotos and switch cases don't jump into scopes illegally.
12816     if (getCurFunction()->NeedsScopeChecking() &&
12817         !PP.isCodeCompletionEnabled())
12818       DiagnoseInvalidJumps(Body);
12819 
12820     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12821       if (!Destructor->getParent()->isDependentType())
12822         CheckDestructor(Destructor);
12823 
12824       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12825                                              Destructor->getParent());
12826     }
12827 
12828     // If any errors have occurred, clear out any temporaries that may have
12829     // been leftover. This ensures that these temporaries won't be picked up for
12830     // deletion in some later function.
12831     if (getDiagnostics().hasErrorOccurred() ||
12832         getDiagnostics().getSuppressAllDiagnostics()) {
12833       DiscardCleanupsInEvaluationContext();
12834     }
12835     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12836         !isa<FunctionTemplateDecl>(dcl)) {
12837       // Since the body is valid, issue any analysis-based warnings that are
12838       // enabled.
12839       ActivePolicy = &WP;
12840     }
12841 
12842     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12843         (!CheckConstexprFunctionDecl(FD) ||
12844          !CheckConstexprFunctionBody(FD, Body)))
12845       FD->setInvalidDecl();
12846 
12847     if (FD && FD->hasAttr<NakedAttr>()) {
12848       for (const Stmt *S : Body->children()) {
12849         // Allow local register variables without initializer as they don't
12850         // require prologue.
12851         bool RegisterVariables = false;
12852         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12853           for (const auto *Decl : DS->decls()) {
12854             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12855               RegisterVariables =
12856                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12857               if (!RegisterVariables)
12858                 break;
12859             }
12860           }
12861         }
12862         if (RegisterVariables)
12863           continue;
12864         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12865           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12866           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12867           FD->setInvalidDecl();
12868           break;
12869         }
12870       }
12871     }
12872 
12873     assert(ExprCleanupObjects.size() ==
12874                ExprEvalContexts.back().NumCleanupObjects &&
12875            "Leftover temporaries in function");
12876     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12877     assert(MaybeODRUseExprs.empty() &&
12878            "Leftover expressions for odr-use checking");
12879   }
12880 
12881   if (!IsInstantiation)
12882     PopDeclContext();
12883 
12884   PopFunctionScopeInfo(ActivePolicy, dcl);
12885   // If any errors have occurred, clear out any temporaries that may have
12886   // been leftover. This ensures that these temporaries won't be picked up for
12887   // deletion in some later function.
12888   if (getDiagnostics().hasErrorOccurred()) {
12889     DiscardCleanupsInEvaluationContext();
12890   }
12891 
12892   return dcl;
12893 }
12894 
12895 /// When we finish delayed parsing of an attribute, we must attach it to the
12896 /// relevant Decl.
12897 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12898                                        ParsedAttributes &Attrs) {
12899   // Always attach attributes to the underlying decl.
12900   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12901     D = TD->getTemplatedDecl();
12902   ProcessDeclAttributeList(S, D, Attrs.getList());
12903 
12904   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12905     if (Method->isStatic())
12906       checkThisInStaticMemberFunctionAttributes(Method);
12907 }
12908 
12909 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12910 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12911 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12912                                           IdentifierInfo &II, Scope *S) {
12913   Scope *BlockScope = S;
12914   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12915     BlockScope = BlockScope->getParent();
12916 
12917   // Before we produce a declaration for an implicitly defined
12918   // function, see whether there was a locally-scoped declaration of
12919   // this name as a function or variable. If so, use that
12920   // (non-visible) declaration, and complain about it.
12921   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12922   if (ExternCPrev) {
12923     // We still need to inject the function into the enclosing block scope so
12924     // that later (non-call) uses can see it.
12925     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12926 
12927     // C89 footnote 38:
12928     //   If in fact it is not defined as having type "function returning int",
12929     //   the behavior is undefined.
12930     if (!isa<FunctionDecl>(ExternCPrev) ||
12931         !Context.typesAreCompatible(
12932             cast<FunctionDecl>(ExternCPrev)->getType(),
12933             Context.getFunctionNoProtoType(Context.IntTy))) {
12934       Diag(Loc, diag::ext_use_out_of_scope_declaration)
12935           << ExternCPrev << !getLangOpts().C99;
12936       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12937       return ExternCPrev;
12938     }
12939   }
12940 
12941   // Extension in C99.  Legal in C90, but warn about it.
12942   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12943   unsigned diag_id;
12944   if (II.getName().startswith("__builtin_"))
12945     diag_id = diag::warn_builtin_unknown;
12946   else if (getLangOpts().C99 || getLangOpts().OpenCL)
12947     diag_id = diag::ext_implicit_function_decl;
12948   else
12949     diag_id = diag::warn_implicit_function_decl;
12950   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
12951 
12952   // If we found a prior declaration of this function, don't bother building
12953   // another one. We've already pushed that one into scope, so there's nothing
12954   // more to do.
12955   if (ExternCPrev)
12956     return ExternCPrev;
12957 
12958   // Because typo correction is expensive, only do it if the implicit
12959   // function declaration is going to be treated as an error.
12960   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12961     TypoCorrection Corrected;
12962     if (S &&
12963         (Corrected = CorrectTypo(
12964              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12965              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12966       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12967                    /*ErrorRecovery*/false);
12968   }
12969 
12970   // Set a Declarator for the implicit definition: int foo();
12971   const char *Dummy;
12972   AttributeFactory attrFactory;
12973   DeclSpec DS(attrFactory);
12974   unsigned DiagID;
12975   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12976                                   Context.getPrintingPolicy());
12977   (void)Error; // Silence warning.
12978   assert(!Error && "Error setting up implicit decl!");
12979   SourceLocation NoLoc;
12980   Declarator D(DS, DeclaratorContext::BlockContext);
12981   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12982                                              /*IsAmbiguous=*/false,
12983                                              /*LParenLoc=*/NoLoc,
12984                                              /*Params=*/nullptr,
12985                                              /*NumParams=*/0,
12986                                              /*EllipsisLoc=*/NoLoc,
12987                                              /*RParenLoc=*/NoLoc,
12988                                              /*TypeQuals=*/0,
12989                                              /*RefQualifierIsLvalueRef=*/true,
12990                                              /*RefQualifierLoc=*/NoLoc,
12991                                              /*ConstQualifierLoc=*/NoLoc,
12992                                              /*VolatileQualifierLoc=*/NoLoc,
12993                                              /*RestrictQualifierLoc=*/NoLoc,
12994                                              /*MutableLoc=*/NoLoc,
12995                                              EST_None,
12996                                              /*ESpecRange=*/SourceRange(),
12997                                              /*Exceptions=*/nullptr,
12998                                              /*ExceptionRanges=*/nullptr,
12999                                              /*NumExceptions=*/0,
13000                                              /*NoexceptExpr=*/nullptr,
13001                                              /*ExceptionSpecTokens=*/nullptr,
13002                                              /*DeclsInPrototype=*/None,
13003                                              Loc, Loc, D),
13004                 DS.getAttributes(),
13005                 SourceLocation());
13006   D.SetIdentifier(&II, Loc);
13007 
13008   // Insert this function into the enclosing block scope.
13009   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13010   FD->setImplicit();
13011 
13012   AddKnownFunctionAttributes(FD);
13013 
13014   return FD;
13015 }
13016 
13017 /// \brief Adds any function attributes that we know a priori based on
13018 /// the declaration of this function.
13019 ///
13020 /// These attributes can apply both to implicitly-declared builtins
13021 /// (like __builtin___printf_chk) or to library-declared functions
13022 /// like NSLog or printf.
13023 ///
13024 /// We need to check for duplicate attributes both here and where user-written
13025 /// attributes are applied to declarations.
13026 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13027   if (FD->isInvalidDecl())
13028     return;
13029 
13030   // If this is a built-in function, map its builtin attributes to
13031   // actual attributes.
13032   if (unsigned BuiltinID = FD->getBuiltinID()) {
13033     // Handle printf-formatting attributes.
13034     unsigned FormatIdx;
13035     bool HasVAListArg;
13036     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13037       if (!FD->hasAttr<FormatAttr>()) {
13038         const char *fmt = "printf";
13039         unsigned int NumParams = FD->getNumParams();
13040         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13041             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13042           fmt = "NSString";
13043         FD->addAttr(FormatAttr::CreateImplicit(Context,
13044                                                &Context.Idents.get(fmt),
13045                                                FormatIdx+1,
13046                                                HasVAListArg ? 0 : FormatIdx+2,
13047                                                FD->getLocation()));
13048       }
13049     }
13050     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13051                                              HasVAListArg)) {
13052      if (!FD->hasAttr<FormatAttr>())
13053        FD->addAttr(FormatAttr::CreateImplicit(Context,
13054                                               &Context.Idents.get("scanf"),
13055                                               FormatIdx+1,
13056                                               HasVAListArg ? 0 : FormatIdx+2,
13057                                               FD->getLocation()));
13058     }
13059 
13060     // Mark const if we don't care about errno and that is the only thing
13061     // preventing the function from being const. This allows IRgen to use LLVM
13062     // intrinsics for such functions.
13063     if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13064         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13065       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13066 
13067     // We make "fma" on GNU or Windows const because we know it does not set
13068     // errno in those environments even though it could set errno based on the
13069     // C standard.
13070     const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13071     if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
13072         !FD->hasAttr<ConstAttr>()) {
13073       switch (BuiltinID) {
13074       case Builtin::BI__builtin_fma:
13075       case Builtin::BI__builtin_fmaf:
13076       case Builtin::BI__builtin_fmal:
13077       case Builtin::BIfma:
13078       case Builtin::BIfmaf:
13079       case Builtin::BIfmal:
13080         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13081         break;
13082       default:
13083         break;
13084       }
13085     }
13086 
13087     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13088         !FD->hasAttr<ReturnsTwiceAttr>())
13089       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13090                                          FD->getLocation()));
13091     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13092       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13093     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13094       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13095     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13096       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13097     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13098         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13099       // Add the appropriate attribute, depending on the CUDA compilation mode
13100       // and which target the builtin belongs to. For example, during host
13101       // compilation, aux builtins are __device__, while the rest are __host__.
13102       if (getLangOpts().CUDAIsDevice !=
13103           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13104         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13105       else
13106         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13107     }
13108   }
13109 
13110   // If C++ exceptions are enabled but we are told extern "C" functions cannot
13111   // throw, add an implicit nothrow attribute to any extern "C" function we come
13112   // across.
13113   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13114       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13115     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13116     if (!FPT || FPT->getExceptionSpecType() == EST_None)
13117       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13118   }
13119 
13120   IdentifierInfo *Name = FD->getIdentifier();
13121   if (!Name)
13122     return;
13123   if ((!getLangOpts().CPlusPlus &&
13124        FD->getDeclContext()->isTranslationUnit()) ||
13125       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13126        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13127        LinkageSpecDecl::lang_c)) {
13128     // Okay: this could be a libc/libm/Objective-C function we know
13129     // about.
13130   } else
13131     return;
13132 
13133   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13134     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13135     // target-specific builtins, perhaps?
13136     if (!FD->hasAttr<FormatAttr>())
13137       FD->addAttr(FormatAttr::CreateImplicit(Context,
13138                                              &Context.Idents.get("printf"), 2,
13139                                              Name->isStr("vasprintf") ? 0 : 3,
13140                                              FD->getLocation()));
13141   }
13142 
13143   if (Name->isStr("__CFStringMakeConstantString")) {
13144     // We already have a __builtin___CFStringMakeConstantString,
13145     // but builds that use -fno-constant-cfstrings don't go through that.
13146     if (!FD->hasAttr<FormatArgAttr>())
13147       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
13148                                                 FD->getLocation()));
13149   }
13150 }
13151 
13152 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13153                                     TypeSourceInfo *TInfo) {
13154   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13155   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13156 
13157   if (!TInfo) {
13158     assert(D.isInvalidType() && "no declarator info for valid type");
13159     TInfo = Context.getTrivialTypeSourceInfo(T);
13160   }
13161 
13162   // Scope manipulation handled by caller.
13163   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13164                                            D.getLocStart(),
13165                                            D.getIdentifierLoc(),
13166                                            D.getIdentifier(),
13167                                            TInfo);
13168 
13169   // Bail out immediately if we have an invalid declaration.
13170   if (D.isInvalidType()) {
13171     NewTD->setInvalidDecl();
13172     return NewTD;
13173   }
13174 
13175   if (D.getDeclSpec().isModulePrivateSpecified()) {
13176     if (CurContext->isFunctionOrMethod())
13177       Diag(NewTD->getLocation(), diag::err_module_private_local)
13178         << 2 << NewTD->getDeclName()
13179         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13180         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13181     else
13182       NewTD->setModulePrivate();
13183   }
13184 
13185   // C++ [dcl.typedef]p8:
13186   //   If the typedef declaration defines an unnamed class (or
13187   //   enum), the first typedef-name declared by the declaration
13188   //   to be that class type (or enum type) is used to denote the
13189   //   class type (or enum type) for linkage purposes only.
13190   // We need to check whether the type was declared in the declaration.
13191   switch (D.getDeclSpec().getTypeSpecType()) {
13192   case TST_enum:
13193   case TST_struct:
13194   case TST_interface:
13195   case TST_union:
13196   case TST_class: {
13197     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13198     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13199     break;
13200   }
13201 
13202   default:
13203     break;
13204   }
13205 
13206   return NewTD;
13207 }
13208 
13209 /// \brief Check that this is a valid underlying type for an enum declaration.
13210 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13211   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13212   QualType T = TI->getType();
13213 
13214   if (T->isDependentType())
13215     return false;
13216 
13217   if (const BuiltinType *BT = T->getAs<BuiltinType>())
13218     if (BT->isInteger())
13219       return false;
13220 
13221   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13222   return true;
13223 }
13224 
13225 /// Check whether this is a valid redeclaration of a previous enumeration.
13226 /// \return true if the redeclaration was invalid.
13227 bool Sema::CheckEnumRedeclaration(
13228     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
13229     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
13230   bool IsFixed = !EnumUnderlyingTy.isNull();
13231 
13232   if (IsScoped != Prev->isScoped()) {
13233     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13234       << Prev->isScoped();
13235     Diag(Prev->getLocation(), diag::note_previous_declaration);
13236     return true;
13237   }
13238 
13239   if (IsFixed && Prev->isFixed()) {
13240     if (!EnumUnderlyingTy->isDependentType() &&
13241         !Prev->getIntegerType()->isDependentType() &&
13242         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13243                                         Prev->getIntegerType())) {
13244       // TODO: Highlight the underlying type of the redeclaration.
13245       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13246         << EnumUnderlyingTy << Prev->getIntegerType();
13247       Diag(Prev->getLocation(), diag::note_previous_declaration)
13248           << Prev->getIntegerTypeRange();
13249       return true;
13250     }
13251   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
13252     ;
13253   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
13254     ;
13255   } else if (IsFixed != Prev->isFixed()) {
13256     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13257       << Prev->isFixed();
13258     Diag(Prev->getLocation(), diag::note_previous_declaration);
13259     return true;
13260   }
13261 
13262   return false;
13263 }
13264 
13265 /// \brief Get diagnostic %select index for tag kind for
13266 /// redeclaration diagnostic message.
13267 /// WARNING: Indexes apply to particular diagnostics only!
13268 ///
13269 /// \returns diagnostic %select index.
13270 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13271   switch (Tag) {
13272   case TTK_Struct: return 0;
13273   case TTK_Interface: return 1;
13274   case TTK_Class:  return 2;
13275   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13276   }
13277 }
13278 
13279 /// \brief Determine if tag kind is a class-key compatible with
13280 /// class for redeclaration (class, struct, or __interface).
13281 ///
13282 /// \returns true iff the tag kind is compatible.
13283 static bool isClassCompatTagKind(TagTypeKind Tag)
13284 {
13285   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13286 }
13287 
13288 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13289                                              TagTypeKind TTK) {
13290   if (isa<TypedefDecl>(PrevDecl))
13291     return NTK_Typedef;
13292   else if (isa<TypeAliasDecl>(PrevDecl))
13293     return NTK_TypeAlias;
13294   else if (isa<ClassTemplateDecl>(PrevDecl))
13295     return NTK_Template;
13296   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13297     return NTK_TypeAliasTemplate;
13298   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13299     return NTK_TemplateTemplateArgument;
13300   switch (TTK) {
13301   case TTK_Struct:
13302   case TTK_Interface:
13303   case TTK_Class:
13304     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13305   case TTK_Union:
13306     return NTK_NonUnion;
13307   case TTK_Enum:
13308     return NTK_NonEnum;
13309   }
13310   llvm_unreachable("invalid TTK");
13311 }
13312 
13313 /// \brief Determine whether a tag with a given kind is acceptable
13314 /// as a redeclaration of the given tag declaration.
13315 ///
13316 /// \returns true if the new tag kind is acceptable, false otherwise.
13317 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13318                                         TagTypeKind NewTag, bool isDefinition,
13319                                         SourceLocation NewTagLoc,
13320                                         const IdentifierInfo *Name) {
13321   // C++ [dcl.type.elab]p3:
13322   //   The class-key or enum keyword present in the
13323   //   elaborated-type-specifier shall agree in kind with the
13324   //   declaration to which the name in the elaborated-type-specifier
13325   //   refers. This rule also applies to the form of
13326   //   elaborated-type-specifier that declares a class-name or
13327   //   friend class since it can be construed as referring to the
13328   //   definition of the class. Thus, in any
13329   //   elaborated-type-specifier, the enum keyword shall be used to
13330   //   refer to an enumeration (7.2), the union class-key shall be
13331   //   used to refer to a union (clause 9), and either the class or
13332   //   struct class-key shall be used to refer to a class (clause 9)
13333   //   declared using the class or struct class-key.
13334   TagTypeKind OldTag = Previous->getTagKind();
13335   if (!isDefinition || !isClassCompatTagKind(NewTag))
13336     if (OldTag == NewTag)
13337       return true;
13338 
13339   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13340     // Warn about the struct/class tag mismatch.
13341     bool isTemplate = false;
13342     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13343       isTemplate = Record->getDescribedClassTemplate();
13344 
13345     if (inTemplateInstantiation()) {
13346       // In a template instantiation, do not offer fix-its for tag mismatches
13347       // since they usually mess up the template instead of fixing the problem.
13348       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13349         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13350         << getRedeclDiagFromTagKind(OldTag);
13351       return true;
13352     }
13353 
13354     if (isDefinition) {
13355       // On definitions, check previous tags and issue a fix-it for each
13356       // one that doesn't match the current tag.
13357       if (Previous->getDefinition()) {
13358         // Don't suggest fix-its for redefinitions.
13359         return true;
13360       }
13361 
13362       bool previousMismatch = false;
13363       for (auto I : Previous->redecls()) {
13364         if (I->getTagKind() != NewTag) {
13365           if (!previousMismatch) {
13366             previousMismatch = true;
13367             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13368               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13369               << getRedeclDiagFromTagKind(I->getTagKind());
13370           }
13371           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13372             << getRedeclDiagFromTagKind(NewTag)
13373             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13374                  TypeWithKeyword::getTagTypeKindName(NewTag));
13375         }
13376       }
13377       return true;
13378     }
13379 
13380     // Check for a previous definition.  If current tag and definition
13381     // are same type, do nothing.  If no definition, but disagree with
13382     // with previous tag type, give a warning, but no fix-it.
13383     const TagDecl *Redecl = Previous->getDefinition() ?
13384                             Previous->getDefinition() : Previous;
13385     if (Redecl->getTagKind() == NewTag) {
13386       return true;
13387     }
13388 
13389     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13390       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13391       << getRedeclDiagFromTagKind(OldTag);
13392     Diag(Redecl->getLocation(), diag::note_previous_use);
13393 
13394     // If there is a previous definition, suggest a fix-it.
13395     if (Previous->getDefinition()) {
13396         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13397           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13398           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13399                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13400     }
13401 
13402     return true;
13403   }
13404   return false;
13405 }
13406 
13407 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13408 /// from an outer enclosing namespace or file scope inside a friend declaration.
13409 /// This should provide the commented out code in the following snippet:
13410 ///   namespace N {
13411 ///     struct X;
13412 ///     namespace M {
13413 ///       struct Y { friend struct /*N::*/ X; };
13414 ///     }
13415 ///   }
13416 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13417                                          SourceLocation NameLoc) {
13418   // While the decl is in a namespace, do repeated lookup of that name and see
13419   // if we get the same namespace back.  If we do not, continue until
13420   // translation unit scope, at which point we have a fully qualified NNS.
13421   SmallVector<IdentifierInfo *, 4> Namespaces;
13422   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13423   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13424     // This tag should be declared in a namespace, which can only be enclosed by
13425     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13426     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13427     if (!Namespace || Namespace->isAnonymousNamespace())
13428       return FixItHint();
13429     IdentifierInfo *II = Namespace->getIdentifier();
13430     Namespaces.push_back(II);
13431     NamedDecl *Lookup = SemaRef.LookupSingleName(
13432         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13433     if (Lookup == Namespace)
13434       break;
13435   }
13436 
13437   // Once we have all the namespaces, reverse them to go outermost first, and
13438   // build an NNS.
13439   SmallString<64> Insertion;
13440   llvm::raw_svector_ostream OS(Insertion);
13441   if (DC->isTranslationUnit())
13442     OS << "::";
13443   std::reverse(Namespaces.begin(), Namespaces.end());
13444   for (auto *II : Namespaces)
13445     OS << II->getName() << "::";
13446   return FixItHint::CreateInsertion(NameLoc, Insertion);
13447 }
13448 
13449 /// \brief Determine whether a tag originally declared in context \p OldDC can
13450 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13451 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13452 /// using-declaration).
13453 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13454                                          DeclContext *NewDC) {
13455   OldDC = OldDC->getRedeclContext();
13456   NewDC = NewDC->getRedeclContext();
13457 
13458   if (OldDC->Equals(NewDC))
13459     return true;
13460 
13461   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13462   // encloses the other).
13463   if (S.getLangOpts().MSVCCompat &&
13464       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13465     return true;
13466 
13467   return false;
13468 }
13469 
13470 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13471 /// former case, Name will be non-null.  In the later case, Name will be null.
13472 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13473 /// reference/declaration/definition of a tag.
13474 ///
13475 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13476 /// trailing-type-specifier) other than one in an alias-declaration.
13477 ///
13478 /// \param SkipBody If non-null, will be set to indicate if the caller should
13479 /// skip the definition of this tag and treat it as if it were a declaration.
13480 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13481                      SourceLocation KWLoc, CXXScopeSpec &SS,
13482                      IdentifierInfo *Name, SourceLocation NameLoc,
13483                      AttributeList *Attr, AccessSpecifier AS,
13484                      SourceLocation ModulePrivateLoc,
13485                      MultiTemplateParamsArg TemplateParameterLists,
13486                      bool &OwnedDecl, bool &IsDependent,
13487                      SourceLocation ScopedEnumKWLoc,
13488                      bool ScopedEnumUsesClassTag,
13489                      TypeResult UnderlyingType,
13490                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13491                      SkipBodyInfo *SkipBody) {
13492   // If this is not a definition, it must have a name.
13493   IdentifierInfo *OrigName = Name;
13494   assert((Name != nullptr || TUK == TUK_Definition) &&
13495          "Nameless record must be a definition!");
13496   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13497 
13498   OwnedDecl = false;
13499   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13500   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13501 
13502   // FIXME: Check member specializations more carefully.
13503   bool isMemberSpecialization = false;
13504   bool Invalid = false;
13505 
13506   // We only need to do this matching if we have template parameters
13507   // or a scope specifier, which also conveniently avoids this work
13508   // for non-C++ cases.
13509   if (TemplateParameterLists.size() > 0 ||
13510       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13511     if (TemplateParameterList *TemplateParams =
13512             MatchTemplateParametersToScopeSpecifier(
13513                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13514                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13515       if (Kind == TTK_Enum) {
13516         Diag(KWLoc, diag::err_enum_template);
13517         return nullptr;
13518       }
13519 
13520       if (TemplateParams->size() > 0) {
13521         // This is a declaration or definition of a class template (which may
13522         // be a member of another template).
13523 
13524         if (Invalid)
13525           return nullptr;
13526 
13527         OwnedDecl = false;
13528         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13529                                                SS, Name, NameLoc, Attr,
13530                                                TemplateParams, AS,
13531                                                ModulePrivateLoc,
13532                                                /*FriendLoc*/SourceLocation(),
13533                                                TemplateParameterLists.size()-1,
13534                                                TemplateParameterLists.data(),
13535                                                SkipBody);
13536         return Result.get();
13537       } else {
13538         // The "template<>" header is extraneous.
13539         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13540           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13541         isMemberSpecialization = true;
13542       }
13543     }
13544   }
13545 
13546   // Figure out the underlying type if this a enum declaration. We need to do
13547   // this early, because it's needed to detect if this is an incompatible
13548   // redeclaration.
13549   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13550   bool EnumUnderlyingIsImplicit = false;
13551 
13552   if (Kind == TTK_Enum) {
13553     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13554       // No underlying type explicitly specified, or we failed to parse the
13555       // type, default to int.
13556       EnumUnderlying = Context.IntTy.getTypePtr();
13557     else if (UnderlyingType.get()) {
13558       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13559       // integral type; any cv-qualification is ignored.
13560       TypeSourceInfo *TI = nullptr;
13561       GetTypeFromParser(UnderlyingType.get(), &TI);
13562       EnumUnderlying = TI;
13563 
13564       if (CheckEnumUnderlyingType(TI))
13565         // Recover by falling back to int.
13566         EnumUnderlying = Context.IntTy.getTypePtr();
13567 
13568       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13569                                           UPPC_FixedUnderlyingType))
13570         EnumUnderlying = Context.IntTy.getTypePtr();
13571 
13572     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13573       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13574         // Microsoft enums are always of int type.
13575         EnumUnderlying = Context.IntTy.getTypePtr();
13576         EnumUnderlyingIsImplicit = true;
13577       }
13578     }
13579   }
13580 
13581   DeclContext *SearchDC = CurContext;
13582   DeclContext *DC = CurContext;
13583   bool isStdBadAlloc = false;
13584   bool isStdAlignValT = false;
13585 
13586   RedeclarationKind Redecl = forRedeclarationInCurContext();
13587   if (TUK == TUK_Friend || TUK == TUK_Reference)
13588     Redecl = NotForRedeclaration;
13589 
13590   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13591   /// implemented asks for structural equivalence checking, the returned decl
13592   /// here is passed back to the parser, allowing the tag body to be parsed.
13593   auto createTagFromNewDecl = [&]() -> TagDecl * {
13594     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13595     // If there is an identifier, use the location of the identifier as the
13596     // location of the decl, otherwise use the location of the struct/union
13597     // keyword.
13598     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13599     TagDecl *New = nullptr;
13600 
13601     if (Kind == TTK_Enum) {
13602       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13603                              ScopedEnum, ScopedEnumUsesClassTag,
13604                              !EnumUnderlying.isNull());
13605       // If this is an undefined enum, bail.
13606       if (TUK != TUK_Definition && !Invalid)
13607         return nullptr;
13608       if (EnumUnderlying) {
13609         EnumDecl *ED = cast<EnumDecl>(New);
13610         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13611           ED->setIntegerTypeSourceInfo(TI);
13612         else
13613           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13614         ED->setPromotionType(ED->getIntegerType());
13615       }
13616     } else { // struct/union
13617       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13618                                nullptr);
13619     }
13620 
13621     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13622       // Add alignment attributes if necessary; these attributes are checked
13623       // when the ASTContext lays out the structure.
13624       //
13625       // It is important for implementing the correct semantics that this
13626       // happen here (in ActOnTag). The #pragma pack stack is
13627       // maintained as a result of parser callbacks which can occur at
13628       // many points during the parsing of a struct declaration (because
13629       // the #pragma tokens are effectively skipped over during the
13630       // parsing of the struct).
13631       if (TUK == TUK_Definition) {
13632         AddAlignmentAttributesForRecord(RD);
13633         AddMsStructLayoutForRecord(RD);
13634       }
13635     }
13636     New->setLexicalDeclContext(CurContext);
13637     return New;
13638   };
13639 
13640   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13641   if (Name && SS.isNotEmpty()) {
13642     // We have a nested-name tag ('struct foo::bar').
13643 
13644     // Check for invalid 'foo::'.
13645     if (SS.isInvalid()) {
13646       Name = nullptr;
13647       goto CreateNewDecl;
13648     }
13649 
13650     // If this is a friend or a reference to a class in a dependent
13651     // context, don't try to make a decl for it.
13652     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13653       DC = computeDeclContext(SS, false);
13654       if (!DC) {
13655         IsDependent = true;
13656         return nullptr;
13657       }
13658     } else {
13659       DC = computeDeclContext(SS, true);
13660       if (!DC) {
13661         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13662           << SS.getRange();
13663         return nullptr;
13664       }
13665     }
13666 
13667     if (RequireCompleteDeclContext(SS, DC))
13668       return nullptr;
13669 
13670     SearchDC = DC;
13671     // Look-up name inside 'foo::'.
13672     LookupQualifiedName(Previous, DC);
13673 
13674     if (Previous.isAmbiguous())
13675       return nullptr;
13676 
13677     if (Previous.empty()) {
13678       // Name lookup did not find anything. However, if the
13679       // nested-name-specifier refers to the current instantiation,
13680       // and that current instantiation has any dependent base
13681       // classes, we might find something at instantiation time: treat
13682       // this as a dependent elaborated-type-specifier.
13683       // But this only makes any sense for reference-like lookups.
13684       if (Previous.wasNotFoundInCurrentInstantiation() &&
13685           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13686         IsDependent = true;
13687         return nullptr;
13688       }
13689 
13690       // A tag 'foo::bar' must already exist.
13691       Diag(NameLoc, diag::err_not_tag_in_scope)
13692         << Kind << Name << DC << SS.getRange();
13693       Name = nullptr;
13694       Invalid = true;
13695       goto CreateNewDecl;
13696     }
13697   } else if (Name) {
13698     // C++14 [class.mem]p14:
13699     //   If T is the name of a class, then each of the following shall have a
13700     //   name different from T:
13701     //    -- every member of class T that is itself a type
13702     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13703         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13704       return nullptr;
13705 
13706     // If this is a named struct, check to see if there was a previous forward
13707     // declaration or definition.
13708     // FIXME: We're looking into outer scopes here, even when we
13709     // shouldn't be. Doing so can result in ambiguities that we
13710     // shouldn't be diagnosing.
13711     LookupName(Previous, S);
13712 
13713     // When declaring or defining a tag, ignore ambiguities introduced
13714     // by types using'ed into this scope.
13715     if (Previous.isAmbiguous() &&
13716         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13717       LookupResult::Filter F = Previous.makeFilter();
13718       while (F.hasNext()) {
13719         NamedDecl *ND = F.next();
13720         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13721                 SearchDC->getRedeclContext()))
13722           F.erase();
13723       }
13724       F.done();
13725     }
13726 
13727     // C++11 [namespace.memdef]p3:
13728     //   If the name in a friend declaration is neither qualified nor
13729     //   a template-id and the declaration is a function or an
13730     //   elaborated-type-specifier, the lookup to determine whether
13731     //   the entity has been previously declared shall not consider
13732     //   any scopes outside the innermost enclosing namespace.
13733     //
13734     // MSVC doesn't implement the above rule for types, so a friend tag
13735     // declaration may be a redeclaration of a type declared in an enclosing
13736     // scope.  They do implement this rule for friend functions.
13737     //
13738     // Does it matter that this should be by scope instead of by
13739     // semantic context?
13740     if (!Previous.empty() && TUK == TUK_Friend) {
13741       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13742       LookupResult::Filter F = Previous.makeFilter();
13743       bool FriendSawTagOutsideEnclosingNamespace = false;
13744       while (F.hasNext()) {
13745         NamedDecl *ND = F.next();
13746         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13747         if (DC->isFileContext() &&
13748             !EnclosingNS->Encloses(ND->getDeclContext())) {
13749           if (getLangOpts().MSVCCompat)
13750             FriendSawTagOutsideEnclosingNamespace = true;
13751           else
13752             F.erase();
13753         }
13754       }
13755       F.done();
13756 
13757       // Diagnose this MSVC extension in the easy case where lookup would have
13758       // unambiguously found something outside the enclosing namespace.
13759       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13760         NamedDecl *ND = Previous.getFoundDecl();
13761         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13762             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13763       }
13764     }
13765 
13766     // Note:  there used to be some attempt at recovery here.
13767     if (Previous.isAmbiguous())
13768       return nullptr;
13769 
13770     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13771       // FIXME: This makes sure that we ignore the contexts associated
13772       // with C structs, unions, and enums when looking for a matching
13773       // tag declaration or definition. See the similar lookup tweak
13774       // in Sema::LookupName; is there a better way to deal with this?
13775       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13776         SearchDC = SearchDC->getParent();
13777     }
13778   }
13779 
13780   if (Previous.isSingleResult() &&
13781       Previous.getFoundDecl()->isTemplateParameter()) {
13782     // Maybe we will complain about the shadowed template parameter.
13783     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13784     // Just pretend that we didn't see the previous declaration.
13785     Previous.clear();
13786   }
13787 
13788   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13789       DC->Equals(getStdNamespace())) {
13790     if (Name->isStr("bad_alloc")) {
13791       // This is a declaration of or a reference to "std::bad_alloc".
13792       isStdBadAlloc = true;
13793 
13794       // If std::bad_alloc has been implicitly declared (but made invisible to
13795       // name lookup), fill in this implicit declaration as the previous
13796       // declaration, so that the declarations get chained appropriately.
13797       if (Previous.empty() && StdBadAlloc)
13798         Previous.addDecl(getStdBadAlloc());
13799     } else if (Name->isStr("align_val_t")) {
13800       isStdAlignValT = true;
13801       if (Previous.empty() && StdAlignValT)
13802         Previous.addDecl(getStdAlignValT());
13803     }
13804   }
13805 
13806   // If we didn't find a previous declaration, and this is a reference
13807   // (or friend reference), move to the correct scope.  In C++, we
13808   // also need to do a redeclaration lookup there, just in case
13809   // there's a shadow friend decl.
13810   if (Name && Previous.empty() &&
13811       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13812     if (Invalid) goto CreateNewDecl;
13813     assert(SS.isEmpty());
13814 
13815     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13816       // C++ [basic.scope.pdecl]p5:
13817       //   -- for an elaborated-type-specifier of the form
13818       //
13819       //          class-key identifier
13820       //
13821       //      if the elaborated-type-specifier is used in the
13822       //      decl-specifier-seq or parameter-declaration-clause of a
13823       //      function defined in namespace scope, the identifier is
13824       //      declared as a class-name in the namespace that contains
13825       //      the declaration; otherwise, except as a friend
13826       //      declaration, the identifier is declared in the smallest
13827       //      non-class, non-function-prototype scope that contains the
13828       //      declaration.
13829       //
13830       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13831       // C structs and unions.
13832       //
13833       // It is an error in C++ to declare (rather than define) an enum
13834       // type, including via an elaborated type specifier.  We'll
13835       // diagnose that later; for now, declare the enum in the same
13836       // scope as we would have picked for any other tag type.
13837       //
13838       // GNU C also supports this behavior as part of its incomplete
13839       // enum types extension, while GNU C++ does not.
13840       //
13841       // Find the context where we'll be declaring the tag.
13842       // FIXME: We would like to maintain the current DeclContext as the
13843       // lexical context,
13844       SearchDC = getTagInjectionContext(SearchDC);
13845 
13846       // Find the scope where we'll be declaring the tag.
13847       S = getTagInjectionScope(S, getLangOpts());
13848     } else {
13849       assert(TUK == TUK_Friend);
13850       // C++ [namespace.memdef]p3:
13851       //   If a friend declaration in a non-local class first declares a
13852       //   class or function, the friend class or function is a member of
13853       //   the innermost enclosing namespace.
13854       SearchDC = SearchDC->getEnclosingNamespaceContext();
13855     }
13856 
13857     // In C++, we need to do a redeclaration lookup to properly
13858     // diagnose some problems.
13859     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13860     // hidden declaration so that we don't get ambiguity errors when using a
13861     // type declared by an elaborated-type-specifier.  In C that is not correct
13862     // and we should instead merge compatible types found by lookup.
13863     if (getLangOpts().CPlusPlus) {
13864       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13865       LookupQualifiedName(Previous, SearchDC);
13866     } else {
13867       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13868       LookupName(Previous, S);
13869     }
13870   }
13871 
13872   // If we have a known previous declaration to use, then use it.
13873   if (Previous.empty() && SkipBody && SkipBody->Previous)
13874     Previous.addDecl(SkipBody->Previous);
13875 
13876   if (!Previous.empty()) {
13877     NamedDecl *PrevDecl = Previous.getFoundDecl();
13878     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13879 
13880     // It's okay to have a tag decl in the same scope as a typedef
13881     // which hides a tag decl in the same scope.  Finding this
13882     // insanity with a redeclaration lookup can only actually happen
13883     // in C++.
13884     //
13885     // This is also okay for elaborated-type-specifiers, which is
13886     // technically forbidden by the current standard but which is
13887     // okay according to the likely resolution of an open issue;
13888     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13889     if (getLangOpts().CPlusPlus) {
13890       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13891         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13892           TagDecl *Tag = TT->getDecl();
13893           if (Tag->getDeclName() == Name &&
13894               Tag->getDeclContext()->getRedeclContext()
13895                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13896             PrevDecl = Tag;
13897             Previous.clear();
13898             Previous.addDecl(Tag);
13899             Previous.resolveKind();
13900           }
13901         }
13902       }
13903     }
13904 
13905     // If this is a redeclaration of a using shadow declaration, it must
13906     // declare a tag in the same context. In MSVC mode, we allow a
13907     // redefinition if either context is within the other.
13908     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13909       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13910       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13911           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13912           !(OldTag && isAcceptableTagRedeclContext(
13913                           *this, OldTag->getDeclContext(), SearchDC))) {
13914         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13915         Diag(Shadow->getTargetDecl()->getLocation(),
13916              diag::note_using_decl_target);
13917         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13918             << 0;
13919         // Recover by ignoring the old declaration.
13920         Previous.clear();
13921         goto CreateNewDecl;
13922       }
13923     }
13924 
13925     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13926       // If this is a use of a previous tag, or if the tag is already declared
13927       // in the same scope (so that the definition/declaration completes or
13928       // rementions the tag), reuse the decl.
13929       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13930           isDeclInScope(DirectPrevDecl, SearchDC, S,
13931                         SS.isNotEmpty() || isMemberSpecialization)) {
13932         // Make sure that this wasn't declared as an enum and now used as a
13933         // struct or something similar.
13934         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13935                                           TUK == TUK_Definition, KWLoc,
13936                                           Name)) {
13937           bool SafeToContinue
13938             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13939                Kind != TTK_Enum);
13940           if (SafeToContinue)
13941             Diag(KWLoc, diag::err_use_with_wrong_tag)
13942               << Name
13943               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13944                                               PrevTagDecl->getKindName());
13945           else
13946             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13947           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13948 
13949           if (SafeToContinue)
13950             Kind = PrevTagDecl->getTagKind();
13951           else {
13952             // Recover by making this an anonymous redefinition.
13953             Name = nullptr;
13954             Previous.clear();
13955             Invalid = true;
13956           }
13957         }
13958 
13959         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13960           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13961 
13962           // If this is an elaborated-type-specifier for a scoped enumeration,
13963           // the 'class' keyword is not necessary and not permitted.
13964           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13965             if (ScopedEnum)
13966               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13967                 << PrevEnum->isScoped()
13968                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13969             return PrevTagDecl;
13970           }
13971 
13972           QualType EnumUnderlyingTy;
13973           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13974             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13975           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13976             EnumUnderlyingTy = QualType(T, 0);
13977 
13978           // All conflicts with previous declarations are recovered by
13979           // returning the previous declaration, unless this is a definition,
13980           // in which case we want the caller to bail out.
13981           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13982                                      ScopedEnum, EnumUnderlyingTy,
13983                                      EnumUnderlyingIsImplicit, PrevEnum))
13984             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13985         }
13986 
13987         // C++11 [class.mem]p1:
13988         //   A member shall not be declared twice in the member-specification,
13989         //   except that a nested class or member class template can be declared
13990         //   and then later defined.
13991         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13992             S->isDeclScope(PrevDecl)) {
13993           Diag(NameLoc, diag::ext_member_redeclared);
13994           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13995         }
13996 
13997         if (!Invalid) {
13998           // If this is a use, just return the declaration we found, unless
13999           // we have attributes.
14000           if (TUK == TUK_Reference || TUK == TUK_Friend) {
14001             if (Attr) {
14002               // FIXME: Diagnose these attributes. For now, we create a new
14003               // declaration to hold them.
14004             } else if (TUK == TUK_Reference &&
14005                        (PrevTagDecl->getFriendObjectKind() ==
14006                             Decl::FOK_Undeclared ||
14007                         PrevDecl->getOwningModule() != getCurrentModule()) &&
14008                        SS.isEmpty()) {
14009               // This declaration is a reference to an existing entity, but
14010               // has different visibility from that entity: it either makes
14011               // a friend visible or it makes a type visible in a new module.
14012               // In either case, create a new declaration. We only do this if
14013               // the declaration would have meant the same thing if no prior
14014               // declaration were found, that is, if it was found in the same
14015               // scope where we would have injected a declaration.
14016               if (!getTagInjectionContext(CurContext)->getRedeclContext()
14017                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14018                 return PrevTagDecl;
14019               // This is in the injected scope, create a new declaration in
14020               // that scope.
14021               S = getTagInjectionScope(S, getLangOpts());
14022             } else {
14023               return PrevTagDecl;
14024             }
14025           }
14026 
14027           // Diagnose attempts to redefine a tag.
14028           if (TUK == TUK_Definition) {
14029             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14030               // If we're defining a specialization and the previous definition
14031               // is from an implicit instantiation, don't emit an error
14032               // here; we'll catch this in the general case below.
14033               bool IsExplicitSpecializationAfterInstantiation = false;
14034               if (isMemberSpecialization) {
14035                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14036                   IsExplicitSpecializationAfterInstantiation =
14037                     RD->getTemplateSpecializationKind() !=
14038                     TSK_ExplicitSpecialization;
14039                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14040                   IsExplicitSpecializationAfterInstantiation =
14041                     ED->getTemplateSpecializationKind() !=
14042                     TSK_ExplicitSpecialization;
14043               }
14044 
14045               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14046               // not keep more that one definition around (merge them). However,
14047               // ensure the decl passes the structural compatibility check in
14048               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14049               NamedDecl *Hidden = nullptr;
14050               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14051                 // There is a definition of this tag, but it is not visible. We
14052                 // explicitly make use of C++'s one definition rule here, and
14053                 // assume that this definition is identical to the hidden one
14054                 // we already have. Make the existing definition visible and
14055                 // use it in place of this one.
14056                 if (!getLangOpts().CPlusPlus) {
14057                   // Postpone making the old definition visible until after we
14058                   // complete parsing the new one and do the structural
14059                   // comparison.
14060                   SkipBody->CheckSameAsPrevious = true;
14061                   SkipBody->New = createTagFromNewDecl();
14062                   SkipBody->Previous = Hidden;
14063                 } else {
14064                   SkipBody->ShouldSkip = true;
14065                   makeMergedDefinitionVisible(Hidden);
14066                 }
14067                 return Def;
14068               } else if (!IsExplicitSpecializationAfterInstantiation) {
14069                 // A redeclaration in function prototype scope in C isn't
14070                 // visible elsewhere, so merely issue a warning.
14071                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14072                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14073                 else
14074                   Diag(NameLoc, diag::err_redefinition) << Name;
14075                 notePreviousDefinition(Def,
14076                                        NameLoc.isValid() ? NameLoc : KWLoc);
14077                 // If this is a redefinition, recover by making this
14078                 // struct be anonymous, which will make any later
14079                 // references get the previous definition.
14080                 Name = nullptr;
14081                 Previous.clear();
14082                 Invalid = true;
14083               }
14084             } else {
14085               // If the type is currently being defined, complain
14086               // about a nested redefinition.
14087               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14088               if (TD->isBeingDefined()) {
14089                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14090                 Diag(PrevTagDecl->getLocation(),
14091                      diag::note_previous_definition);
14092                 Name = nullptr;
14093                 Previous.clear();
14094                 Invalid = true;
14095               }
14096             }
14097 
14098             // Okay, this is definition of a previously declared or referenced
14099             // tag. We're going to create a new Decl for it.
14100           }
14101 
14102           // Okay, we're going to make a redeclaration.  If this is some kind
14103           // of reference, make sure we build the redeclaration in the same DC
14104           // as the original, and ignore the current access specifier.
14105           if (TUK == TUK_Friend || TUK == TUK_Reference) {
14106             SearchDC = PrevTagDecl->getDeclContext();
14107             AS = AS_none;
14108           }
14109         }
14110         // If we get here we have (another) forward declaration or we
14111         // have a definition.  Just create a new decl.
14112 
14113       } else {
14114         // If we get here, this is a definition of a new tag type in a nested
14115         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14116         // new decl/type.  We set PrevDecl to NULL so that the entities
14117         // have distinct types.
14118         Previous.clear();
14119       }
14120       // If we get here, we're going to create a new Decl. If PrevDecl
14121       // is non-NULL, it's a definition of the tag declared by
14122       // PrevDecl. If it's NULL, we have a new definition.
14123 
14124     // Otherwise, PrevDecl is not a tag, but was found with tag
14125     // lookup.  This is only actually possible in C++, where a few
14126     // things like templates still live in the tag namespace.
14127     } else {
14128       // Use a better diagnostic if an elaborated-type-specifier
14129       // found the wrong kind of type on the first
14130       // (non-redeclaration) lookup.
14131       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14132           !Previous.isForRedeclaration()) {
14133         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14134         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14135                                                        << Kind;
14136         Diag(PrevDecl->getLocation(), diag::note_declared_at);
14137         Invalid = true;
14138 
14139       // Otherwise, only diagnose if the declaration is in scope.
14140       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14141                                 SS.isNotEmpty() || isMemberSpecialization)) {
14142         // do nothing
14143 
14144       // Diagnose implicit declarations introduced by elaborated types.
14145       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14146         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14147         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14148         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14149         Invalid = true;
14150 
14151       // Otherwise it's a declaration.  Call out a particularly common
14152       // case here.
14153       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14154         unsigned Kind = 0;
14155         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14156         Diag(NameLoc, diag::err_tag_definition_of_typedef)
14157           << Name << Kind << TND->getUnderlyingType();
14158         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14159         Invalid = true;
14160 
14161       // Otherwise, diagnose.
14162       } else {
14163         // The tag name clashes with something else in the target scope,
14164         // issue an error and recover by making this tag be anonymous.
14165         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14166         notePreviousDefinition(PrevDecl, NameLoc);
14167         Name = nullptr;
14168         Invalid = true;
14169       }
14170 
14171       // The existing declaration isn't relevant to us; we're in a
14172       // new scope, so clear out the previous declaration.
14173       Previous.clear();
14174     }
14175   }
14176 
14177 CreateNewDecl:
14178 
14179   TagDecl *PrevDecl = nullptr;
14180   if (Previous.isSingleResult())
14181     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14182 
14183   // If there is an identifier, use the location of the identifier as the
14184   // location of the decl, otherwise use the location of the struct/union
14185   // keyword.
14186   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14187 
14188   // Otherwise, create a new declaration. If there is a previous
14189   // declaration of the same entity, the two will be linked via
14190   // PrevDecl.
14191   TagDecl *New;
14192 
14193   bool IsForwardReference = false;
14194   if (Kind == TTK_Enum) {
14195     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14196     // enum X { A, B, C } D;    D should chain to X.
14197     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14198                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14199                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
14200 
14201     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14202       StdAlignValT = cast<EnumDecl>(New);
14203 
14204     // If this is an undefined enum, warn.
14205     if (TUK != TUK_Definition && !Invalid) {
14206       TagDecl *Def;
14207       if (!EnumUnderlyingIsImplicit &&
14208           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14209           cast<EnumDecl>(New)->isFixed()) {
14210         // C++0x: 7.2p2: opaque-enum-declaration.
14211         // Conflicts are diagnosed above. Do nothing.
14212       }
14213       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14214         Diag(Loc, diag::ext_forward_ref_enum_def)
14215           << New;
14216         Diag(Def->getLocation(), diag::note_previous_definition);
14217       } else {
14218         unsigned DiagID = diag::ext_forward_ref_enum;
14219         if (getLangOpts().MSVCCompat)
14220           DiagID = diag::ext_ms_forward_ref_enum;
14221         else if (getLangOpts().CPlusPlus)
14222           DiagID = diag::err_forward_ref_enum;
14223         Diag(Loc, DiagID);
14224 
14225         // If this is a forward-declared reference to an enumeration, make a
14226         // note of it; we won't actually be introducing the declaration into
14227         // the declaration context.
14228         if (TUK == TUK_Reference)
14229           IsForwardReference = true;
14230       }
14231     }
14232 
14233     if (EnumUnderlying) {
14234       EnumDecl *ED = cast<EnumDecl>(New);
14235       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14236         ED->setIntegerTypeSourceInfo(TI);
14237       else
14238         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14239       ED->setPromotionType(ED->getIntegerType());
14240     }
14241   } else {
14242     // struct/union/class
14243 
14244     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14245     // struct X { int A; } D;    D should chain to X.
14246     if (getLangOpts().CPlusPlus) {
14247       // FIXME: Look for a way to use RecordDecl for simple structs.
14248       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14249                                   cast_or_null<CXXRecordDecl>(PrevDecl));
14250 
14251       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14252         StdBadAlloc = cast<CXXRecordDecl>(New);
14253     } else
14254       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14255                                cast_or_null<RecordDecl>(PrevDecl));
14256   }
14257 
14258   // C++11 [dcl.type]p3:
14259   //   A type-specifier-seq shall not define a class or enumeration [...].
14260   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14261       TUK == TUK_Definition) {
14262     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14263       << Context.getTagDeclType(New);
14264     Invalid = true;
14265   }
14266 
14267   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14268       DC->getDeclKind() == Decl::Enum) {
14269     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14270       << Context.getTagDeclType(New);
14271     Invalid = true;
14272   }
14273 
14274   // Maybe add qualifier info.
14275   if (SS.isNotEmpty()) {
14276     if (SS.isSet()) {
14277       // If this is either a declaration or a definition, check the
14278       // nested-name-specifier against the current context. We don't do this
14279       // for explicit specializations, because they have similar checking
14280       // (with more specific diagnostics) in the call to
14281       // CheckMemberSpecialization, below.
14282       if (!isMemberSpecialization &&
14283           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
14284           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
14285         Invalid = true;
14286 
14287       New->setQualifierInfo(SS.getWithLocInContext(Context));
14288       if (TemplateParameterLists.size() > 0) {
14289         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14290       }
14291     }
14292     else
14293       Invalid = true;
14294   }
14295 
14296   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14297     // Add alignment attributes if necessary; these attributes are checked when
14298     // the ASTContext lays out the structure.
14299     //
14300     // It is important for implementing the correct semantics that this
14301     // happen here (in ActOnTag). The #pragma pack stack is
14302     // maintained as a result of parser callbacks which can occur at
14303     // many points during the parsing of a struct declaration (because
14304     // the #pragma tokens are effectively skipped over during the
14305     // parsing of the struct).
14306     if (TUK == TUK_Definition) {
14307       AddAlignmentAttributesForRecord(RD);
14308       AddMsStructLayoutForRecord(RD);
14309     }
14310   }
14311 
14312   if (ModulePrivateLoc.isValid()) {
14313     if (isMemberSpecialization)
14314       Diag(New->getLocation(), diag::err_module_private_specialization)
14315         << 2
14316         << FixItHint::CreateRemoval(ModulePrivateLoc);
14317     // __module_private__ does not apply to local classes. However, we only
14318     // diagnose this as an error when the declaration specifiers are
14319     // freestanding. Here, we just ignore the __module_private__.
14320     else if (!SearchDC->isFunctionOrMethod())
14321       New->setModulePrivate();
14322   }
14323 
14324   // If this is a specialization of a member class (of a class template),
14325   // check the specialization.
14326   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14327     Invalid = true;
14328 
14329   // If we're declaring or defining a tag in function prototype scope in C,
14330   // note that this type can only be used within the function and add it to
14331   // the list of decls to inject into the function definition scope.
14332   if ((Name || Kind == TTK_Enum) &&
14333       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14334     if (getLangOpts().CPlusPlus) {
14335       // C++ [dcl.fct]p6:
14336       //   Types shall not be defined in return or parameter types.
14337       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14338         Diag(Loc, diag::err_type_defined_in_param_type)
14339             << Name;
14340         Invalid = true;
14341       }
14342     } else if (!PrevDecl) {
14343       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14344     }
14345   }
14346 
14347   if (Invalid)
14348     New->setInvalidDecl();
14349 
14350   // Set the lexical context. If the tag has a C++ scope specifier, the
14351   // lexical context will be different from the semantic context.
14352   New->setLexicalDeclContext(CurContext);
14353 
14354   // Mark this as a friend decl if applicable.
14355   // In Microsoft mode, a friend declaration also acts as a forward
14356   // declaration so we always pass true to setObjectOfFriendDecl to make
14357   // the tag name visible.
14358   if (TUK == TUK_Friend)
14359     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14360 
14361   // Set the access specifier.
14362   if (!Invalid && SearchDC->isRecord())
14363     SetMemberAccessSpecifier(New, PrevDecl, AS);
14364 
14365   if (PrevDecl)
14366     CheckRedeclarationModuleOwnership(New, PrevDecl);
14367 
14368   if (TUK == TUK_Definition)
14369     New->startDefinition();
14370 
14371   if (Attr)
14372     ProcessDeclAttributeList(S, New, Attr);
14373   AddPragmaAttributes(S, New);
14374 
14375   // If this has an identifier, add it to the scope stack.
14376   if (TUK == TUK_Friend) {
14377     // We might be replacing an existing declaration in the lookup tables;
14378     // if so, borrow its access specifier.
14379     if (PrevDecl)
14380       New->setAccess(PrevDecl->getAccess());
14381 
14382     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14383     DC->makeDeclVisibleInContext(New);
14384     if (Name) // can be null along some error paths
14385       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14386         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14387   } else if (Name) {
14388     S = getNonFieldDeclScope(S);
14389     PushOnScopeChains(New, S, !IsForwardReference);
14390     if (IsForwardReference)
14391       SearchDC->makeDeclVisibleInContext(New);
14392   } else {
14393     CurContext->addDecl(New);
14394   }
14395 
14396   // If this is the C FILE type, notify the AST context.
14397   if (IdentifierInfo *II = New->getIdentifier())
14398     if (!New->isInvalidDecl() &&
14399         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14400         II->isStr("FILE"))
14401       Context.setFILEDecl(New);
14402 
14403   if (PrevDecl)
14404     mergeDeclAttributes(New, PrevDecl);
14405 
14406   // If there's a #pragma GCC visibility in scope, set the visibility of this
14407   // record.
14408   AddPushedVisibilityAttribute(New);
14409 
14410   if (isMemberSpecialization && !New->isInvalidDecl())
14411     CompleteMemberSpecialization(New, Previous);
14412 
14413   OwnedDecl = true;
14414   // In C++, don't return an invalid declaration. We can't recover well from
14415   // the cases where we make the type anonymous.
14416   if (Invalid && getLangOpts().CPlusPlus) {
14417     if (New->isBeingDefined())
14418       if (auto RD = dyn_cast<RecordDecl>(New))
14419         RD->completeDefinition();
14420     return nullptr;
14421   } else {
14422     return New;
14423   }
14424 }
14425 
14426 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14427   AdjustDeclIfTemplate(TagD);
14428   TagDecl *Tag = cast<TagDecl>(TagD);
14429 
14430   // Enter the tag context.
14431   PushDeclContext(S, Tag);
14432 
14433   ActOnDocumentableDecl(TagD);
14434 
14435   // If there's a #pragma GCC visibility in scope, set the visibility of this
14436   // record.
14437   AddPushedVisibilityAttribute(Tag);
14438 }
14439 
14440 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14441                                     SkipBodyInfo &SkipBody) {
14442   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14443     return false;
14444 
14445   // Make the previous decl visible.
14446   makeMergedDefinitionVisible(SkipBody.Previous);
14447   return true;
14448 }
14449 
14450 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14451   assert(isa<ObjCContainerDecl>(IDecl) &&
14452          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14453   DeclContext *OCD = cast<DeclContext>(IDecl);
14454   assert(getContainingDC(OCD) == CurContext &&
14455       "The next DeclContext should be lexically contained in the current one.");
14456   CurContext = OCD;
14457   return IDecl;
14458 }
14459 
14460 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14461                                            SourceLocation FinalLoc,
14462                                            bool IsFinalSpelledSealed,
14463                                            SourceLocation LBraceLoc) {
14464   AdjustDeclIfTemplate(TagD);
14465   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14466 
14467   FieldCollector->StartClass();
14468 
14469   if (!Record->getIdentifier())
14470     return;
14471 
14472   if (FinalLoc.isValid())
14473     Record->addAttr(new (Context)
14474                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14475 
14476   // C++ [class]p2:
14477   //   [...] The class-name is also inserted into the scope of the
14478   //   class itself; this is known as the injected-class-name. For
14479   //   purposes of access checking, the injected-class-name is treated
14480   //   as if it were a public member name.
14481   CXXRecordDecl *InjectedClassName
14482     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14483                             Record->getLocStart(), Record->getLocation(),
14484                             Record->getIdentifier(),
14485                             /*PrevDecl=*/nullptr,
14486                             /*DelayTypeCreation=*/true);
14487   Context.getTypeDeclType(InjectedClassName, Record);
14488   InjectedClassName->setImplicit();
14489   InjectedClassName->setAccess(AS_public);
14490   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14491       InjectedClassName->setDescribedClassTemplate(Template);
14492   PushOnScopeChains(InjectedClassName, S);
14493   assert(InjectedClassName->isInjectedClassName() &&
14494          "Broken injected-class-name");
14495 }
14496 
14497 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14498                                     SourceRange BraceRange) {
14499   AdjustDeclIfTemplate(TagD);
14500   TagDecl *Tag = cast<TagDecl>(TagD);
14501   Tag->setBraceRange(BraceRange);
14502 
14503   // Make sure we "complete" the definition even it is invalid.
14504   if (Tag->isBeingDefined()) {
14505     assert(Tag->isInvalidDecl() && "We should already have completed it");
14506     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14507       RD->completeDefinition();
14508   }
14509 
14510   if (isa<CXXRecordDecl>(Tag)) {
14511     FieldCollector->FinishClass();
14512   }
14513 
14514   // Exit this scope of this tag's definition.
14515   PopDeclContext();
14516 
14517   if (getCurLexicalContext()->isObjCContainer() &&
14518       Tag->getDeclContext()->isFileContext())
14519     Tag->setTopLevelDeclInObjCContainer();
14520 
14521   // Notify the consumer that we've defined a tag.
14522   if (!Tag->isInvalidDecl())
14523     Consumer.HandleTagDeclDefinition(Tag);
14524 }
14525 
14526 void Sema::ActOnObjCContainerFinishDefinition() {
14527   // Exit this scope of this interface definition.
14528   PopDeclContext();
14529 }
14530 
14531 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14532   assert(DC == CurContext && "Mismatch of container contexts");
14533   OriginalLexicalContext = DC;
14534   ActOnObjCContainerFinishDefinition();
14535 }
14536 
14537 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14538   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14539   OriginalLexicalContext = nullptr;
14540 }
14541 
14542 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14543   AdjustDeclIfTemplate(TagD);
14544   TagDecl *Tag = cast<TagDecl>(TagD);
14545   Tag->setInvalidDecl();
14546 
14547   // Make sure we "complete" the definition even it is invalid.
14548   if (Tag->isBeingDefined()) {
14549     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14550       RD->completeDefinition();
14551   }
14552 
14553   // We're undoing ActOnTagStartDefinition here, not
14554   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14555   // the FieldCollector.
14556 
14557   PopDeclContext();
14558 }
14559 
14560 // Note that FieldName may be null for anonymous bitfields.
14561 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14562                                 IdentifierInfo *FieldName,
14563                                 QualType FieldTy, bool IsMsStruct,
14564                                 Expr *BitWidth, bool *ZeroWidth) {
14565   // Default to true; that shouldn't confuse checks for emptiness
14566   if (ZeroWidth)
14567     *ZeroWidth = true;
14568 
14569   // C99 6.7.2.1p4 - verify the field type.
14570   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14571   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14572     // Handle incomplete types with specific error.
14573     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14574       return ExprError();
14575     if (FieldName)
14576       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14577         << FieldName << FieldTy << BitWidth->getSourceRange();
14578     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14579       << FieldTy << BitWidth->getSourceRange();
14580   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14581                                              UPPC_BitFieldWidth))
14582     return ExprError();
14583 
14584   // If the bit-width is type- or value-dependent, don't try to check
14585   // it now.
14586   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14587     return BitWidth;
14588 
14589   llvm::APSInt Value;
14590   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14591   if (ICE.isInvalid())
14592     return ICE;
14593   BitWidth = ICE.get();
14594 
14595   if (Value != 0 && ZeroWidth)
14596     *ZeroWidth = false;
14597 
14598   // Zero-width bitfield is ok for anonymous field.
14599   if (Value == 0 && FieldName)
14600     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14601 
14602   if (Value.isSigned() && Value.isNegative()) {
14603     if (FieldName)
14604       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14605                << FieldName << Value.toString(10);
14606     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14607       << Value.toString(10);
14608   }
14609 
14610   if (!FieldTy->isDependentType()) {
14611     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14612     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14613     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14614 
14615     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14616     // ABI.
14617     bool CStdConstraintViolation =
14618         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14619     bool MSBitfieldViolation =
14620         Value.ugt(TypeStorageSize) &&
14621         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14622     if (CStdConstraintViolation || MSBitfieldViolation) {
14623       unsigned DiagWidth =
14624           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14625       if (FieldName)
14626         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14627                << FieldName << (unsigned)Value.getZExtValue()
14628                << !CStdConstraintViolation << DiagWidth;
14629 
14630       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14631              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14632              << DiagWidth;
14633     }
14634 
14635     // Warn on types where the user might conceivably expect to get all
14636     // specified bits as value bits: that's all integral types other than
14637     // 'bool'.
14638     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14639       if (FieldName)
14640         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14641             << FieldName << (unsigned)Value.getZExtValue()
14642             << (unsigned)TypeWidth;
14643       else
14644         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14645             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14646     }
14647   }
14648 
14649   return BitWidth;
14650 }
14651 
14652 /// ActOnField - Each field of a C struct/union is passed into this in order
14653 /// to create a FieldDecl object for it.
14654 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14655                        Declarator &D, Expr *BitfieldWidth) {
14656   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14657                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14658                                /*InitStyle=*/ICIS_NoInit, AS_public);
14659   return Res;
14660 }
14661 
14662 /// HandleField - Analyze a field of a C struct or a C++ data member.
14663 ///
14664 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14665                              SourceLocation DeclStart,
14666                              Declarator &D, Expr *BitWidth,
14667                              InClassInitStyle InitStyle,
14668                              AccessSpecifier AS) {
14669   if (D.isDecompositionDeclarator()) {
14670     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14671     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14672       << Decomp.getSourceRange();
14673     return nullptr;
14674   }
14675 
14676   IdentifierInfo *II = D.getIdentifier();
14677   SourceLocation Loc = DeclStart;
14678   if (II) Loc = D.getIdentifierLoc();
14679 
14680   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14681   QualType T = TInfo->getType();
14682   if (getLangOpts().CPlusPlus) {
14683     CheckExtraCXXDefaultArguments(D);
14684 
14685     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14686                                         UPPC_DataMemberType)) {
14687       D.setInvalidType();
14688       T = Context.IntTy;
14689       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14690     }
14691   }
14692 
14693   // TR 18037 does not allow fields to be declared with address spaces.
14694   if (T.getQualifiers().hasAddressSpace() ||
14695       T->isDependentAddressSpaceType() ||
14696       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14697     Diag(Loc, diag::err_field_with_address_space);
14698     D.setInvalidType();
14699   }
14700 
14701   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14702   // used as structure or union field: image, sampler, event or block types.
14703   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14704                           T->isSamplerT() || T->isBlockPointerType())) {
14705     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14706     D.setInvalidType();
14707   }
14708 
14709   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14710 
14711   if (D.getDeclSpec().isInlineSpecified())
14712     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14713         << getLangOpts().CPlusPlus17;
14714   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14715     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14716          diag::err_invalid_thread)
14717       << DeclSpec::getSpecifierName(TSCS);
14718 
14719   // Check to see if this name was declared as a member previously
14720   NamedDecl *PrevDecl = nullptr;
14721   LookupResult Previous(*this, II, Loc, LookupMemberName,
14722                         ForVisibleRedeclaration);
14723   LookupName(Previous, S);
14724   switch (Previous.getResultKind()) {
14725     case LookupResult::Found:
14726     case LookupResult::FoundUnresolvedValue:
14727       PrevDecl = Previous.getAsSingle<NamedDecl>();
14728       break;
14729 
14730     case LookupResult::FoundOverloaded:
14731       PrevDecl = Previous.getRepresentativeDecl();
14732       break;
14733 
14734     case LookupResult::NotFound:
14735     case LookupResult::NotFoundInCurrentInstantiation:
14736     case LookupResult::Ambiguous:
14737       break;
14738   }
14739   Previous.suppressDiagnostics();
14740 
14741   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14742     // Maybe we will complain about the shadowed template parameter.
14743     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14744     // Just pretend that we didn't see the previous declaration.
14745     PrevDecl = nullptr;
14746   }
14747 
14748   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14749     PrevDecl = nullptr;
14750 
14751   bool Mutable
14752     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14753   SourceLocation TSSL = D.getLocStart();
14754   FieldDecl *NewFD
14755     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14756                      TSSL, AS, PrevDecl, &D);
14757 
14758   if (NewFD->isInvalidDecl())
14759     Record->setInvalidDecl();
14760 
14761   if (D.getDeclSpec().isModulePrivateSpecified())
14762     NewFD->setModulePrivate();
14763 
14764   if (NewFD->isInvalidDecl() && PrevDecl) {
14765     // Don't introduce NewFD into scope; there's already something
14766     // with the same name in the same scope.
14767   } else if (II) {
14768     PushOnScopeChains(NewFD, S);
14769   } else
14770     Record->addDecl(NewFD);
14771 
14772   return NewFD;
14773 }
14774 
14775 /// \brief Build a new FieldDecl and check its well-formedness.
14776 ///
14777 /// This routine builds a new FieldDecl given the fields name, type,
14778 /// record, etc. \p PrevDecl should refer to any previous declaration
14779 /// with the same name and in the same scope as the field to be
14780 /// created.
14781 ///
14782 /// \returns a new FieldDecl.
14783 ///
14784 /// \todo The Declarator argument is a hack. It will be removed once
14785 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14786                                 TypeSourceInfo *TInfo,
14787                                 RecordDecl *Record, SourceLocation Loc,
14788                                 bool Mutable, Expr *BitWidth,
14789                                 InClassInitStyle InitStyle,
14790                                 SourceLocation TSSL,
14791                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14792                                 Declarator *D) {
14793   IdentifierInfo *II = Name.getAsIdentifierInfo();
14794   bool InvalidDecl = false;
14795   if (D) InvalidDecl = D->isInvalidType();
14796 
14797   // If we receive a broken type, recover by assuming 'int' and
14798   // marking this declaration as invalid.
14799   if (T.isNull()) {
14800     InvalidDecl = true;
14801     T = Context.IntTy;
14802   }
14803 
14804   QualType EltTy = Context.getBaseElementType(T);
14805   if (!EltTy->isDependentType()) {
14806     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14807       // Fields of incomplete type force their record to be invalid.
14808       Record->setInvalidDecl();
14809       InvalidDecl = true;
14810     } else {
14811       NamedDecl *Def;
14812       EltTy->isIncompleteType(&Def);
14813       if (Def && Def->isInvalidDecl()) {
14814         Record->setInvalidDecl();
14815         InvalidDecl = true;
14816       }
14817     }
14818   }
14819 
14820   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14821   if (BitWidth && getLangOpts().OpenCL) {
14822     Diag(Loc, diag::err_opencl_bitfields);
14823     InvalidDecl = true;
14824   }
14825 
14826   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14827   // than a variably modified type.
14828   if (!InvalidDecl && T->isVariablyModifiedType()) {
14829     bool SizeIsNegative;
14830     llvm::APSInt Oversized;
14831 
14832     TypeSourceInfo *FixedTInfo =
14833       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14834                                                     SizeIsNegative,
14835                                                     Oversized);
14836     if (FixedTInfo) {
14837       Diag(Loc, diag::warn_illegal_constant_array_size);
14838       TInfo = FixedTInfo;
14839       T = FixedTInfo->getType();
14840     } else {
14841       if (SizeIsNegative)
14842         Diag(Loc, diag::err_typecheck_negative_array_size);
14843       else if (Oversized.getBoolValue())
14844         Diag(Loc, diag::err_array_too_large)
14845           << Oversized.toString(10);
14846       else
14847         Diag(Loc, diag::err_typecheck_field_variable_size);
14848       InvalidDecl = true;
14849     }
14850   }
14851 
14852   // Fields can not have abstract class types
14853   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14854                                              diag::err_abstract_type_in_decl,
14855                                              AbstractFieldType))
14856     InvalidDecl = true;
14857 
14858   bool ZeroWidth = false;
14859   if (InvalidDecl)
14860     BitWidth = nullptr;
14861   // If this is declared as a bit-field, check the bit-field.
14862   if (BitWidth) {
14863     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14864                               &ZeroWidth).get();
14865     if (!BitWidth) {
14866       InvalidDecl = true;
14867       BitWidth = nullptr;
14868       ZeroWidth = false;
14869     }
14870   }
14871 
14872   // Check that 'mutable' is consistent with the type of the declaration.
14873   if (!InvalidDecl && Mutable) {
14874     unsigned DiagID = 0;
14875     if (T->isReferenceType())
14876       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14877                                         : diag::err_mutable_reference;
14878     else if (T.isConstQualified())
14879       DiagID = diag::err_mutable_const;
14880 
14881     if (DiagID) {
14882       SourceLocation ErrLoc = Loc;
14883       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14884         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14885       Diag(ErrLoc, DiagID);
14886       if (DiagID != diag::ext_mutable_reference) {
14887         Mutable = false;
14888         InvalidDecl = true;
14889       }
14890     }
14891   }
14892 
14893   // C++11 [class.union]p8 (DR1460):
14894   //   At most one variant member of a union may have a
14895   //   brace-or-equal-initializer.
14896   if (InitStyle != ICIS_NoInit)
14897     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14898 
14899   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14900                                        BitWidth, Mutable, InitStyle);
14901   if (InvalidDecl)
14902     NewFD->setInvalidDecl();
14903 
14904   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14905     Diag(Loc, diag::err_duplicate_member) << II;
14906     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14907     NewFD->setInvalidDecl();
14908   }
14909 
14910   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14911     if (Record->isUnion()) {
14912       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14913         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14914         if (RDecl->getDefinition()) {
14915           // C++ [class.union]p1: An object of a class with a non-trivial
14916           // constructor, a non-trivial copy constructor, a non-trivial
14917           // destructor, or a non-trivial copy assignment operator
14918           // cannot be a member of a union, nor can an array of such
14919           // objects.
14920           if (CheckNontrivialField(NewFD))
14921             NewFD->setInvalidDecl();
14922         }
14923       }
14924 
14925       // C++ [class.union]p1: If a union contains a member of reference type,
14926       // the program is ill-formed, except when compiling with MSVC extensions
14927       // enabled.
14928       if (EltTy->isReferenceType()) {
14929         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14930                                     diag::ext_union_member_of_reference_type :
14931                                     diag::err_union_member_of_reference_type)
14932           << NewFD->getDeclName() << EltTy;
14933         if (!getLangOpts().MicrosoftExt)
14934           NewFD->setInvalidDecl();
14935       }
14936     }
14937   }
14938 
14939   // FIXME: We need to pass in the attributes given an AST
14940   // representation, not a parser representation.
14941   if (D) {
14942     // FIXME: The current scope is almost... but not entirely... correct here.
14943     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14944 
14945     if (NewFD->hasAttrs())
14946       CheckAlignasUnderalignment(NewFD);
14947   }
14948 
14949   // In auto-retain/release, infer strong retension for fields of
14950   // retainable type.
14951   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14952     NewFD->setInvalidDecl();
14953 
14954   if (T.isObjCGCWeak())
14955     Diag(Loc, diag::warn_attribute_weak_on_field);
14956 
14957   NewFD->setAccess(AS);
14958   return NewFD;
14959 }
14960 
14961 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14962   assert(FD);
14963   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14964 
14965   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14966     return false;
14967 
14968   QualType EltTy = Context.getBaseElementType(FD->getType());
14969   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14970     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14971     if (RDecl->getDefinition()) {
14972       // We check for copy constructors before constructors
14973       // because otherwise we'll never get complaints about
14974       // copy constructors.
14975 
14976       CXXSpecialMember member = CXXInvalid;
14977       // We're required to check for any non-trivial constructors. Since the
14978       // implicit default constructor is suppressed if there are any
14979       // user-declared constructors, we just need to check that there is a
14980       // trivial default constructor and a trivial copy constructor. (We don't
14981       // worry about move constructors here, since this is a C++98 check.)
14982       if (RDecl->hasNonTrivialCopyConstructor())
14983         member = CXXCopyConstructor;
14984       else if (!RDecl->hasTrivialDefaultConstructor())
14985         member = CXXDefaultConstructor;
14986       else if (RDecl->hasNonTrivialCopyAssignment())
14987         member = CXXCopyAssignment;
14988       else if (RDecl->hasNonTrivialDestructor())
14989         member = CXXDestructor;
14990 
14991       if (member != CXXInvalid) {
14992         if (!getLangOpts().CPlusPlus11 &&
14993             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14994           // Objective-C++ ARC: it is an error to have a non-trivial field of
14995           // a union. However, system headers in Objective-C programs
14996           // occasionally have Objective-C lifetime objects within unions,
14997           // and rather than cause the program to fail, we make those
14998           // members unavailable.
14999           SourceLocation Loc = FD->getLocation();
15000           if (getSourceManager().isInSystemHeader(Loc)) {
15001             if (!FD->hasAttr<UnavailableAttr>())
15002               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15003                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15004             return false;
15005           }
15006         }
15007 
15008         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15009                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15010                diag::err_illegal_union_or_anon_struct_member)
15011           << FD->getParent()->isUnion() << FD->getDeclName() << member;
15012         DiagnoseNontrivial(RDecl, member);
15013         return !getLangOpts().CPlusPlus11;
15014       }
15015     }
15016   }
15017 
15018   return false;
15019 }
15020 
15021 /// TranslateIvarVisibility - Translate visibility from a token ID to an
15022 ///  AST enum value.
15023 static ObjCIvarDecl::AccessControl
15024 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15025   switch (ivarVisibility) {
15026   default: llvm_unreachable("Unknown visitibility kind");
15027   case tok::objc_private: return ObjCIvarDecl::Private;
15028   case tok::objc_public: return ObjCIvarDecl::Public;
15029   case tok::objc_protected: return ObjCIvarDecl::Protected;
15030   case tok::objc_package: return ObjCIvarDecl::Package;
15031   }
15032 }
15033 
15034 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
15035 /// in order to create an IvarDecl object for it.
15036 Decl *Sema::ActOnIvar(Scope *S,
15037                                 SourceLocation DeclStart,
15038                                 Declarator &D, Expr *BitfieldWidth,
15039                                 tok::ObjCKeywordKind Visibility) {
15040 
15041   IdentifierInfo *II = D.getIdentifier();
15042   Expr *BitWidth = (Expr*)BitfieldWidth;
15043   SourceLocation Loc = DeclStart;
15044   if (II) Loc = D.getIdentifierLoc();
15045 
15046   // FIXME: Unnamed fields can be handled in various different ways, for
15047   // example, unnamed unions inject all members into the struct namespace!
15048 
15049   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15050   QualType T = TInfo->getType();
15051 
15052   if (BitWidth) {
15053     // 6.7.2.1p3, 6.7.2.1p4
15054     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15055     if (!BitWidth)
15056       D.setInvalidType();
15057   } else {
15058     // Not a bitfield.
15059 
15060     // validate II.
15061 
15062   }
15063   if (T->isReferenceType()) {
15064     Diag(Loc, diag::err_ivar_reference_type);
15065     D.setInvalidType();
15066   }
15067   // C99 6.7.2.1p8: A member of a structure or union may have any type other
15068   // than a variably modified type.
15069   else if (T->isVariablyModifiedType()) {
15070     Diag(Loc, diag::err_typecheck_ivar_variable_size);
15071     D.setInvalidType();
15072   }
15073 
15074   // Get the visibility (access control) for this ivar.
15075   ObjCIvarDecl::AccessControl ac =
15076     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15077                                         : ObjCIvarDecl::None;
15078   // Must set ivar's DeclContext to its enclosing interface.
15079   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15080   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15081     return nullptr;
15082   ObjCContainerDecl *EnclosingContext;
15083   if (ObjCImplementationDecl *IMPDecl =
15084       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15085     if (LangOpts.ObjCRuntime.isFragile()) {
15086     // Case of ivar declared in an implementation. Context is that of its class.
15087       EnclosingContext = IMPDecl->getClassInterface();
15088       assert(EnclosingContext && "Implementation has no class interface!");
15089     }
15090     else
15091       EnclosingContext = EnclosingDecl;
15092   } else {
15093     if (ObjCCategoryDecl *CDecl =
15094         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15095       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15096         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15097         return nullptr;
15098       }
15099     }
15100     EnclosingContext = EnclosingDecl;
15101   }
15102 
15103   // Construct the decl.
15104   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15105                                              DeclStart, Loc, II, T,
15106                                              TInfo, ac, (Expr *)BitfieldWidth);
15107 
15108   if (II) {
15109     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15110                                            ForVisibleRedeclaration);
15111     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15112         && !isa<TagDecl>(PrevDecl)) {
15113       Diag(Loc, diag::err_duplicate_member) << II;
15114       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15115       NewID->setInvalidDecl();
15116     }
15117   }
15118 
15119   // Process attributes attached to the ivar.
15120   ProcessDeclAttributes(S, NewID, D);
15121 
15122   if (D.isInvalidType())
15123     NewID->setInvalidDecl();
15124 
15125   // In ARC, infer 'retaining' for ivars of retainable type.
15126   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15127     NewID->setInvalidDecl();
15128 
15129   if (D.getDeclSpec().isModulePrivateSpecified())
15130     NewID->setModulePrivate();
15131 
15132   if (II) {
15133     // FIXME: When interfaces are DeclContexts, we'll need to add
15134     // these to the interface.
15135     S->AddDecl(NewID);
15136     IdResolver.AddDecl(NewID);
15137   }
15138 
15139   if (LangOpts.ObjCRuntime.isNonFragile() &&
15140       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15141     Diag(Loc, diag::warn_ivars_in_interface);
15142 
15143   return NewID;
15144 }
15145 
15146 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15147 /// class and class extensions. For every class \@interface and class
15148 /// extension \@interface, if the last ivar is a bitfield of any type,
15149 /// then add an implicit `char :0` ivar to the end of that interface.
15150 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15151                              SmallVectorImpl<Decl *> &AllIvarDecls) {
15152   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15153     return;
15154 
15155   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15156   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15157 
15158   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
15159     return;
15160   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15161   if (!ID) {
15162     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15163       if (!CD->IsClassExtension())
15164         return;
15165     }
15166     // No need to add this to end of @implementation.
15167     else
15168       return;
15169   }
15170   // All conditions are met. Add a new bitfield to the tail end of ivars.
15171   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15172   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15173 
15174   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15175                               DeclLoc, DeclLoc, nullptr,
15176                               Context.CharTy,
15177                               Context.getTrivialTypeSourceInfo(Context.CharTy,
15178                                                                DeclLoc),
15179                               ObjCIvarDecl::Private, BW,
15180                               true);
15181   AllIvarDecls.push_back(Ivar);
15182 }
15183 
15184 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15185                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
15186                        SourceLocation RBrac, AttributeList *Attr) {
15187   assert(EnclosingDecl && "missing record or interface decl");
15188 
15189   // If this is an Objective-C @implementation or category and we have
15190   // new fields here we should reset the layout of the interface since
15191   // it will now change.
15192   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15193     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15194     switch (DC->getKind()) {
15195     default: break;
15196     case Decl::ObjCCategory:
15197       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15198       break;
15199     case Decl::ObjCImplementation:
15200       Context.
15201         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15202       break;
15203     }
15204   }
15205 
15206   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15207 
15208   // Start counting up the number of named members; make sure to include
15209   // members of anonymous structs and unions in the total.
15210   unsigned NumNamedMembers = 0;
15211   if (Record) {
15212     for (const auto *I : Record->decls()) {
15213       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15214         if (IFD->getDeclName())
15215           ++NumNamedMembers;
15216     }
15217   }
15218 
15219   // Verify that all the fields are okay.
15220   SmallVector<FieldDecl*, 32> RecFields;
15221 
15222   bool ObjCFieldLifetimeErrReported = false;
15223   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15224        i != end; ++i) {
15225     FieldDecl *FD = cast<FieldDecl>(*i);
15226 
15227     // Get the type for the field.
15228     const Type *FDTy = FD->getType().getTypePtr();
15229 
15230     if (!FD->isAnonymousStructOrUnion()) {
15231       // Remember all fields written by the user.
15232       RecFields.push_back(FD);
15233     }
15234 
15235     // If the field is already invalid for some reason, don't emit more
15236     // diagnostics about it.
15237     if (FD->isInvalidDecl()) {
15238       EnclosingDecl->setInvalidDecl();
15239       continue;
15240     }
15241 
15242     // C99 6.7.2.1p2:
15243     //   A structure or union shall not contain a member with
15244     //   incomplete or function type (hence, a structure shall not
15245     //   contain an instance of itself, but may contain a pointer to
15246     //   an instance of itself), except that the last member of a
15247     //   structure with more than one named member may have incomplete
15248     //   array type; such a structure (and any union containing,
15249     //   possibly recursively, a member that is such a structure)
15250     //   shall not be a member of a structure or an element of an
15251     //   array.
15252     bool IsLastField = (i + 1 == Fields.end());
15253     if (FDTy->isFunctionType()) {
15254       // Field declared as a function.
15255       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15256         << FD->getDeclName();
15257       FD->setInvalidDecl();
15258       EnclosingDecl->setInvalidDecl();
15259       continue;
15260     } else if (FDTy->isIncompleteArrayType() &&
15261                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15262       if (Record) {
15263         // Flexible array member.
15264         // Microsoft and g++ is more permissive regarding flexible array.
15265         // It will accept flexible array in union and also
15266         // as the sole element of a struct/class.
15267         unsigned DiagID = 0;
15268         if (!Record->isUnion() && !IsLastField) {
15269           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15270             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15271           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15272           FD->setInvalidDecl();
15273           EnclosingDecl->setInvalidDecl();
15274           continue;
15275         } else if (Record->isUnion())
15276           DiagID = getLangOpts().MicrosoftExt
15277                        ? diag::ext_flexible_array_union_ms
15278                        : getLangOpts().CPlusPlus
15279                              ? diag::ext_flexible_array_union_gnu
15280                              : diag::err_flexible_array_union;
15281         else if (NumNamedMembers < 1)
15282           DiagID = getLangOpts().MicrosoftExt
15283                        ? diag::ext_flexible_array_empty_aggregate_ms
15284                        : getLangOpts().CPlusPlus
15285                              ? diag::ext_flexible_array_empty_aggregate_gnu
15286                              : diag::err_flexible_array_empty_aggregate;
15287 
15288         if (DiagID)
15289           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15290                                           << Record->getTagKind();
15291         // While the layout of types that contain virtual bases is not specified
15292         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15293         // virtual bases after the derived members.  This would make a flexible
15294         // array member declared at the end of an object not adjacent to the end
15295         // of the type.
15296         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15297           if (RD->getNumVBases() != 0)
15298             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15299               << FD->getDeclName() << Record->getTagKind();
15300         if (!getLangOpts().C99)
15301           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15302             << FD->getDeclName() << Record->getTagKind();
15303 
15304         // If the element type has a non-trivial destructor, we would not
15305         // implicitly destroy the elements, so disallow it for now.
15306         //
15307         // FIXME: GCC allows this. We should probably either implicitly delete
15308         // the destructor of the containing class, or just allow this.
15309         QualType BaseElem = Context.getBaseElementType(FD->getType());
15310         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15311           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15312             << FD->getDeclName() << FD->getType();
15313           FD->setInvalidDecl();
15314           EnclosingDecl->setInvalidDecl();
15315           continue;
15316         }
15317         // Okay, we have a legal flexible array member at the end of the struct.
15318         Record->setHasFlexibleArrayMember(true);
15319       } else {
15320         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15321         // unless they are followed by another ivar. That check is done
15322         // elsewhere, after synthesized ivars are known.
15323       }
15324     } else if (!FDTy->isDependentType() &&
15325                RequireCompleteType(FD->getLocation(), FD->getType(),
15326                                    diag::err_field_incomplete)) {
15327       // Incomplete type
15328       FD->setInvalidDecl();
15329       EnclosingDecl->setInvalidDecl();
15330       continue;
15331     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15332       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15333         // A type which contains a flexible array member is considered to be a
15334         // flexible array member.
15335         Record->setHasFlexibleArrayMember(true);
15336         if (!Record->isUnion()) {
15337           // If this is a struct/class and this is not the last element, reject
15338           // it.  Note that GCC supports variable sized arrays in the middle of
15339           // structures.
15340           if (!IsLastField)
15341             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15342               << FD->getDeclName() << FD->getType();
15343           else {
15344             // We support flexible arrays at the end of structs in
15345             // other structs as an extension.
15346             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15347               << FD->getDeclName();
15348           }
15349         }
15350       }
15351       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15352           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15353                                  diag::err_abstract_type_in_decl,
15354                                  AbstractIvarType)) {
15355         // Ivars can not have abstract class types
15356         FD->setInvalidDecl();
15357       }
15358       if (Record && FDTTy->getDecl()->hasObjectMember())
15359         Record->setHasObjectMember(true);
15360       if (Record && FDTTy->getDecl()->hasVolatileMember())
15361         Record->setHasVolatileMember(true);
15362     } else if (FDTy->isObjCObjectType()) {
15363       /// A field cannot be an Objective-c object
15364       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15365         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15366       QualType T = Context.getObjCObjectPointerType(FD->getType());
15367       FD->setType(T);
15368     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15369                Record && !ObjCFieldLifetimeErrReported &&
15370                (!getLangOpts().CPlusPlus || Record->isUnion())) {
15371       // It's an error in ARC or Weak if a field has lifetime.
15372       // We don't want to report this in a system header, though,
15373       // so we just make the field unavailable.
15374       // FIXME: that's really not sufficient; we need to make the type
15375       // itself invalid to, say, initialize or copy.
15376       QualType T = FD->getType();
15377       if (T.hasNonTrivialObjCLifetime()) {
15378         SourceLocation loc = FD->getLocation();
15379         if (getSourceManager().isInSystemHeader(loc)) {
15380           if (!FD->hasAttr<UnavailableAttr>()) {
15381             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15382                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15383           }
15384         } else {
15385           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15386             << T->isBlockPointerType() << Record->getTagKind();
15387         }
15388         ObjCFieldLifetimeErrReported = true;
15389       }
15390     } else if (getLangOpts().ObjC1 &&
15391                getLangOpts().getGC() != LangOptions::NonGC &&
15392                Record && !Record->hasObjectMember()) {
15393       if (FD->getType()->isObjCObjectPointerType() ||
15394           FD->getType().isObjCGCStrong())
15395         Record->setHasObjectMember(true);
15396       else if (Context.getAsArrayType(FD->getType())) {
15397         QualType BaseType = Context.getBaseElementType(FD->getType());
15398         if (BaseType->isRecordType() &&
15399             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15400           Record->setHasObjectMember(true);
15401         else if (BaseType->isObjCObjectPointerType() ||
15402                  BaseType.isObjCGCStrong())
15403                Record->setHasObjectMember(true);
15404       }
15405     }
15406     if (Record && FD->getType().isVolatileQualified())
15407       Record->setHasVolatileMember(true);
15408     // Keep track of the number of named members.
15409     if (FD->getIdentifier())
15410       ++NumNamedMembers;
15411   }
15412 
15413   // Okay, we successfully defined 'Record'.
15414   if (Record) {
15415     bool Completed = false;
15416     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15417       if (!CXXRecord->isInvalidDecl()) {
15418         // Set access bits correctly on the directly-declared conversions.
15419         for (CXXRecordDecl::conversion_iterator
15420                I = CXXRecord->conversion_begin(),
15421                E = CXXRecord->conversion_end(); I != E; ++I)
15422           I.setAccess((*I)->getAccess());
15423       }
15424 
15425       if (!CXXRecord->isDependentType()) {
15426         if (CXXRecord->hasUserDeclaredDestructor()) {
15427           // Adjust user-defined destructor exception spec.
15428           if (getLangOpts().CPlusPlus11)
15429             AdjustDestructorExceptionSpec(CXXRecord,
15430                                           CXXRecord->getDestructor());
15431         }
15432 
15433         if (!CXXRecord->isInvalidDecl()) {
15434           // Add any implicitly-declared members to this class.
15435           AddImplicitlyDeclaredMembersToClass(CXXRecord);
15436 
15437           // If we have virtual base classes, we may end up finding multiple
15438           // final overriders for a given virtual function. Check for this
15439           // problem now.
15440           if (CXXRecord->getNumVBases()) {
15441             CXXFinalOverriderMap FinalOverriders;
15442             CXXRecord->getFinalOverriders(FinalOverriders);
15443 
15444             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15445                                              MEnd = FinalOverriders.end();
15446                  M != MEnd; ++M) {
15447               for (OverridingMethods::iterator SO = M->second.begin(),
15448                                             SOEnd = M->second.end();
15449                    SO != SOEnd; ++SO) {
15450                 assert(SO->second.size() > 0 &&
15451                        "Virtual function without overridding functions?");
15452                 if (SO->second.size() == 1)
15453                   continue;
15454 
15455                 // C++ [class.virtual]p2:
15456                 //   In a derived class, if a virtual member function of a base
15457                 //   class subobject has more than one final overrider the
15458                 //   program is ill-formed.
15459                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15460                   << (const NamedDecl *)M->first << Record;
15461                 Diag(M->first->getLocation(),
15462                      diag::note_overridden_virtual_function);
15463                 for (OverridingMethods::overriding_iterator
15464                           OM = SO->second.begin(),
15465                        OMEnd = SO->second.end();
15466                      OM != OMEnd; ++OM)
15467                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15468                     << (const NamedDecl *)M->first << OM->Method->getParent();
15469 
15470                 Record->setInvalidDecl();
15471               }
15472             }
15473             CXXRecord->completeDefinition(&FinalOverriders);
15474             Completed = true;
15475           }
15476         }
15477       }
15478     }
15479 
15480     if (!Completed)
15481       Record->completeDefinition();
15482 
15483     // We may have deferred checking for a deleted destructor. Check now.
15484     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15485       auto *Dtor = CXXRecord->getDestructor();
15486       if (Dtor && Dtor->isImplicit() &&
15487           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15488         CXXRecord->setImplicitDestructorIsDeleted();
15489         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15490       }
15491     }
15492 
15493     if (Record->hasAttrs()) {
15494       CheckAlignasUnderalignment(Record);
15495 
15496       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15497         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15498                                            IA->getRange(), IA->getBestCase(),
15499                                            IA->getSemanticSpelling());
15500     }
15501 
15502     // Check if the structure/union declaration is a type that can have zero
15503     // size in C. For C this is a language extension, for C++ it may cause
15504     // compatibility problems.
15505     bool CheckForZeroSize;
15506     if (!getLangOpts().CPlusPlus) {
15507       CheckForZeroSize = true;
15508     } else {
15509       // For C++ filter out types that cannot be referenced in C code.
15510       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15511       CheckForZeroSize =
15512           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15513           !CXXRecord->isDependentType() &&
15514           CXXRecord->isCLike();
15515     }
15516     if (CheckForZeroSize) {
15517       bool ZeroSize = true;
15518       bool IsEmpty = true;
15519       unsigned NonBitFields = 0;
15520       for (RecordDecl::field_iterator I = Record->field_begin(),
15521                                       E = Record->field_end();
15522            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15523         IsEmpty = false;
15524         if (I->isUnnamedBitfield()) {
15525           if (I->getBitWidthValue(Context) > 0)
15526             ZeroSize = false;
15527         } else {
15528           ++NonBitFields;
15529           QualType FieldType = I->getType();
15530           if (FieldType->isIncompleteType() ||
15531               !Context.getTypeSizeInChars(FieldType).isZero())
15532             ZeroSize = false;
15533         }
15534       }
15535 
15536       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15537       // allowed in C++, but warn if its declaration is inside
15538       // extern "C" block.
15539       if (ZeroSize) {
15540         Diag(RecLoc, getLangOpts().CPlusPlus ?
15541                          diag::warn_zero_size_struct_union_in_extern_c :
15542                          diag::warn_zero_size_struct_union_compat)
15543           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15544       }
15545 
15546       // Structs without named members are extension in C (C99 6.7.2.1p7),
15547       // but are accepted by GCC.
15548       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15549         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15550                                diag::ext_no_named_members_in_struct_union)
15551           << Record->isUnion();
15552       }
15553     }
15554   } else {
15555     ObjCIvarDecl **ClsFields =
15556       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15557     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15558       ID->setEndOfDefinitionLoc(RBrac);
15559       // Add ivar's to class's DeclContext.
15560       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15561         ClsFields[i]->setLexicalDeclContext(ID);
15562         ID->addDecl(ClsFields[i]);
15563       }
15564       // Must enforce the rule that ivars in the base classes may not be
15565       // duplicates.
15566       if (ID->getSuperClass())
15567         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15568     } else if (ObjCImplementationDecl *IMPDecl =
15569                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15570       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15571       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15572         // Ivar declared in @implementation never belongs to the implementation.
15573         // Only it is in implementation's lexical context.
15574         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15575       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15576       IMPDecl->setIvarLBraceLoc(LBrac);
15577       IMPDecl->setIvarRBraceLoc(RBrac);
15578     } else if (ObjCCategoryDecl *CDecl =
15579                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15580       // case of ivars in class extension; all other cases have been
15581       // reported as errors elsewhere.
15582       // FIXME. Class extension does not have a LocEnd field.
15583       // CDecl->setLocEnd(RBrac);
15584       // Add ivar's to class extension's DeclContext.
15585       // Diagnose redeclaration of private ivars.
15586       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15587       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15588         if (IDecl) {
15589           if (const ObjCIvarDecl *ClsIvar =
15590               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15591             Diag(ClsFields[i]->getLocation(),
15592                  diag::err_duplicate_ivar_declaration);
15593             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15594             continue;
15595           }
15596           for (const auto *Ext : IDecl->known_extensions()) {
15597             if (const ObjCIvarDecl *ClsExtIvar
15598                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15599               Diag(ClsFields[i]->getLocation(),
15600                    diag::err_duplicate_ivar_declaration);
15601               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15602               continue;
15603             }
15604           }
15605         }
15606         ClsFields[i]->setLexicalDeclContext(CDecl);
15607         CDecl->addDecl(ClsFields[i]);
15608       }
15609       CDecl->setIvarLBraceLoc(LBrac);
15610       CDecl->setIvarRBraceLoc(RBrac);
15611     }
15612   }
15613 
15614   if (Attr)
15615     ProcessDeclAttributeList(S, Record, Attr);
15616 }
15617 
15618 /// \brief Determine whether the given integral value is representable within
15619 /// the given type T.
15620 static bool isRepresentableIntegerValue(ASTContext &Context,
15621                                         llvm::APSInt &Value,
15622                                         QualType T) {
15623   assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
15624          "Integral type required!");
15625   unsigned BitWidth = Context.getIntWidth(T);
15626 
15627   if (Value.isUnsigned() || Value.isNonNegative()) {
15628     if (T->isSignedIntegerOrEnumerationType())
15629       --BitWidth;
15630     return Value.getActiveBits() <= BitWidth;
15631   }
15632   return Value.getMinSignedBits() <= BitWidth;
15633 }
15634 
15635 // \brief Given an integral type, return the next larger integral type
15636 // (or a NULL type of no such type exists).
15637 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15638   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15639   // enum checking below.
15640   assert((T->isIntegralType(Context) ||
15641          T->isEnumeralType()) && "Integral type required!");
15642   const unsigned NumTypes = 4;
15643   QualType SignedIntegralTypes[NumTypes] = {
15644     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15645   };
15646   QualType UnsignedIntegralTypes[NumTypes] = {
15647     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15648     Context.UnsignedLongLongTy
15649   };
15650 
15651   unsigned BitWidth = Context.getTypeSize(T);
15652   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15653                                                         : UnsignedIntegralTypes;
15654   for (unsigned I = 0; I != NumTypes; ++I)
15655     if (Context.getTypeSize(Types[I]) > BitWidth)
15656       return Types[I];
15657 
15658   return QualType();
15659 }
15660 
15661 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15662                                           EnumConstantDecl *LastEnumConst,
15663                                           SourceLocation IdLoc,
15664                                           IdentifierInfo *Id,
15665                                           Expr *Val) {
15666   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15667   llvm::APSInt EnumVal(IntWidth);
15668   QualType EltTy;
15669 
15670   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15671     Val = nullptr;
15672 
15673   if (Val)
15674     Val = DefaultLvalueConversion(Val).get();
15675 
15676   if (Val) {
15677     if (Enum->isDependentType() || Val->isTypeDependent())
15678       EltTy = Context.DependentTy;
15679     else {
15680       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15681           !getLangOpts().MSVCCompat) {
15682         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15683         // constant-expression in the enumerator-definition shall be a converted
15684         // constant expression of the underlying type.
15685         EltTy = Enum->getIntegerType();
15686         ExprResult Converted =
15687           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15688                                            CCEK_Enumerator);
15689         if (Converted.isInvalid())
15690           Val = nullptr;
15691         else
15692           Val = Converted.get();
15693       } else if (!Val->isValueDependent() &&
15694                  !(Val = VerifyIntegerConstantExpression(Val,
15695                                                          &EnumVal).get())) {
15696         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15697       } else {
15698         if (Enum->isFixed()) {
15699           EltTy = Enum->getIntegerType();
15700 
15701           // In Obj-C and Microsoft mode, require the enumeration value to be
15702           // representable in the underlying type of the enumeration. In C++11,
15703           // we perform a non-narrowing conversion as part of converted constant
15704           // expression checking.
15705           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15706             if (getLangOpts().MSVCCompat) {
15707               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15708               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15709             } else
15710               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15711           } else
15712             Val = ImpCastExprToType(Val, EltTy,
15713                                     EltTy->isBooleanType() ?
15714                                     CK_IntegralToBoolean : CK_IntegralCast)
15715                     .get();
15716         } else if (getLangOpts().CPlusPlus) {
15717           // C++11 [dcl.enum]p5:
15718           //   If the underlying type is not fixed, the type of each enumerator
15719           //   is the type of its initializing value:
15720           //     - If an initializer is specified for an enumerator, the
15721           //       initializing value has the same type as the expression.
15722           EltTy = Val->getType();
15723         } else {
15724           // C99 6.7.2.2p2:
15725           //   The expression that defines the value of an enumeration constant
15726           //   shall be an integer constant expression that has a value
15727           //   representable as an int.
15728 
15729           // Complain if the value is not representable in an int.
15730           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15731             Diag(IdLoc, diag::ext_enum_value_not_int)
15732               << EnumVal.toString(10) << Val->getSourceRange()
15733               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15734           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15735             // Force the type of the expression to 'int'.
15736             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15737           }
15738           EltTy = Val->getType();
15739         }
15740       }
15741     }
15742   }
15743 
15744   if (!Val) {
15745     if (Enum->isDependentType())
15746       EltTy = Context.DependentTy;
15747     else if (!LastEnumConst) {
15748       // C++0x [dcl.enum]p5:
15749       //   If the underlying type is not fixed, the type of each enumerator
15750       //   is the type of its initializing value:
15751       //     - If no initializer is specified for the first enumerator, the
15752       //       initializing value has an unspecified integral type.
15753       //
15754       // GCC uses 'int' for its unspecified integral type, as does
15755       // C99 6.7.2.2p3.
15756       if (Enum->isFixed()) {
15757         EltTy = Enum->getIntegerType();
15758       }
15759       else {
15760         EltTy = Context.IntTy;
15761       }
15762     } else {
15763       // Assign the last value + 1.
15764       EnumVal = LastEnumConst->getInitVal();
15765       ++EnumVal;
15766       EltTy = LastEnumConst->getType();
15767 
15768       // Check for overflow on increment.
15769       if (EnumVal < LastEnumConst->getInitVal()) {
15770         // C++0x [dcl.enum]p5:
15771         //   If the underlying type is not fixed, the type of each enumerator
15772         //   is the type of its initializing value:
15773         //
15774         //     - Otherwise the type of the initializing value is the same as
15775         //       the type of the initializing value of the preceding enumerator
15776         //       unless the incremented value is not representable in that type,
15777         //       in which case the type is an unspecified integral type
15778         //       sufficient to contain the incremented value. If no such type
15779         //       exists, the program is ill-formed.
15780         QualType T = getNextLargerIntegralType(Context, EltTy);
15781         if (T.isNull() || Enum->isFixed()) {
15782           // There is no integral type larger enough to represent this
15783           // value. Complain, then allow the value to wrap around.
15784           EnumVal = LastEnumConst->getInitVal();
15785           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15786           ++EnumVal;
15787           if (Enum->isFixed())
15788             // When the underlying type is fixed, this is ill-formed.
15789             Diag(IdLoc, diag::err_enumerator_wrapped)
15790               << EnumVal.toString(10)
15791               << EltTy;
15792           else
15793             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15794               << EnumVal.toString(10);
15795         } else {
15796           EltTy = T;
15797         }
15798 
15799         // Retrieve the last enumerator's value, extent that type to the
15800         // type that is supposed to be large enough to represent the incremented
15801         // value, then increment.
15802         EnumVal = LastEnumConst->getInitVal();
15803         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15804         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15805         ++EnumVal;
15806 
15807         // If we're not in C++, diagnose the overflow of enumerator values,
15808         // which in C99 means that the enumerator value is not representable in
15809         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15810         // permits enumerator values that are representable in some larger
15811         // integral type.
15812         if (!getLangOpts().CPlusPlus && !T.isNull())
15813           Diag(IdLoc, diag::warn_enum_value_overflow);
15814       } else if (!getLangOpts().CPlusPlus &&
15815                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15816         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15817         Diag(IdLoc, diag::ext_enum_value_not_int)
15818           << EnumVal.toString(10) << 1;
15819       }
15820     }
15821   }
15822 
15823   if (!EltTy->isDependentType()) {
15824     // Make the enumerator value match the signedness and size of the
15825     // enumerator's type.
15826     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15827     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15828   }
15829 
15830   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15831                                   Val, EnumVal);
15832 }
15833 
15834 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15835                                                 SourceLocation IILoc) {
15836   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15837       !getLangOpts().CPlusPlus)
15838     return SkipBodyInfo();
15839 
15840   // We have an anonymous enum definition. Look up the first enumerator to
15841   // determine if we should merge the definition with an existing one and
15842   // skip the body.
15843   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15844                                          forRedeclarationInCurContext());
15845   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15846   if (!PrevECD)
15847     return SkipBodyInfo();
15848 
15849   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15850   NamedDecl *Hidden;
15851   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15852     SkipBodyInfo Skip;
15853     Skip.Previous = Hidden;
15854     return Skip;
15855   }
15856 
15857   return SkipBodyInfo();
15858 }
15859 
15860 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15861                               SourceLocation IdLoc, IdentifierInfo *Id,
15862                               AttributeList *Attr,
15863                               SourceLocation EqualLoc, Expr *Val) {
15864   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15865   EnumConstantDecl *LastEnumConst =
15866     cast_or_null<EnumConstantDecl>(lastEnumConst);
15867 
15868   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15869   // we find one that is.
15870   S = getNonFieldDeclScope(S);
15871 
15872   // Verify that there isn't already something declared with this name in this
15873   // scope.
15874   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15875                                          ForVisibleRedeclaration);
15876   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15877     // Maybe we will complain about the shadowed template parameter.
15878     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15879     // Just pretend that we didn't see the previous declaration.
15880     PrevDecl = nullptr;
15881   }
15882 
15883   // C++ [class.mem]p15:
15884   // If T is the name of a class, then each of the following shall have a name
15885   // different from T:
15886   // - every enumerator of every member of class T that is an unscoped
15887   // enumerated type
15888   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15889     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15890                             DeclarationNameInfo(Id, IdLoc));
15891 
15892   EnumConstantDecl *New =
15893     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15894   if (!New)
15895     return nullptr;
15896 
15897   if (PrevDecl) {
15898     // When in C++, we may get a TagDecl with the same name; in this case the
15899     // enum constant will 'hide' the tag.
15900     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15901            "Received TagDecl when not in C++!");
15902     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15903       if (isa<EnumConstantDecl>(PrevDecl))
15904         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15905       else
15906         Diag(IdLoc, diag::err_redefinition) << Id;
15907       notePreviousDefinition(PrevDecl, IdLoc);
15908       return nullptr;
15909     }
15910   }
15911 
15912   // Process attributes.
15913   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15914   AddPragmaAttributes(S, New);
15915 
15916   // Register this decl in the current scope stack.
15917   New->setAccess(TheEnumDecl->getAccess());
15918   PushOnScopeChains(New, S);
15919 
15920   ActOnDocumentableDecl(New);
15921 
15922   return New;
15923 }
15924 
15925 // Returns true when the enum initial expression does not trigger the
15926 // duplicate enum warning.  A few common cases are exempted as follows:
15927 // Element2 = Element1
15928 // Element2 = Element1 + 1
15929 // Element2 = Element1 - 1
15930 // Where Element2 and Element1 are from the same enum.
15931 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15932   Expr *InitExpr = ECD->getInitExpr();
15933   if (!InitExpr)
15934     return true;
15935   InitExpr = InitExpr->IgnoreImpCasts();
15936 
15937   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15938     if (!BO->isAdditiveOp())
15939       return true;
15940     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15941     if (!IL)
15942       return true;
15943     if (IL->getValue() != 1)
15944       return true;
15945 
15946     InitExpr = BO->getLHS();
15947   }
15948 
15949   // This checks if the elements are from the same enum.
15950   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15951   if (!DRE)
15952     return true;
15953 
15954   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15955   if (!EnumConstant)
15956     return true;
15957 
15958   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15959       Enum)
15960     return true;
15961 
15962   return false;
15963 }
15964 
15965 namespace {
15966 struct DupKey {
15967   int64_t val;
15968   bool isTombstoneOrEmptyKey;
15969   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15970     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15971 };
15972 
15973 static DupKey GetDupKey(const llvm::APSInt& Val) {
15974   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15975                 false);
15976 }
15977 
15978 struct DenseMapInfoDupKey {
15979   static DupKey getEmptyKey() { return DupKey(0, true); }
15980   static DupKey getTombstoneKey() { return DupKey(1, true); }
15981   static unsigned getHashValue(const DupKey Key) {
15982     return (unsigned)(Key.val * 37);
15983   }
15984   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15985     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15986            LHS.val == RHS.val;
15987   }
15988 };
15989 } // end anonymous namespace
15990 
15991 // Emits a warning when an element is implicitly set a value that
15992 // a previous element has already been set to.
15993 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15994                                         EnumDecl *Enum,
15995                                         QualType EnumType) {
15996   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15997     return;
15998   // Avoid anonymous enums
15999   if (!Enum->getIdentifier())
16000     return;
16001 
16002   // Only check for small enums.
16003   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16004     return;
16005 
16006   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16007   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
16008 
16009   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16010   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
16011           ValueToVectorMap;
16012 
16013   DuplicatesVector DupVector;
16014   ValueToVectorMap EnumMap;
16015 
16016   // Populate the EnumMap with all values represented by enum constants without
16017   // an initialier.
16018   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16019     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
16020 
16021     // Null EnumConstantDecl means a previous diagnostic has been emitted for
16022     // this constant.  Skip this enum since it may be ill-formed.
16023     if (!ECD) {
16024       return;
16025     }
16026 
16027     if (ECD->getInitExpr())
16028       continue;
16029 
16030     DupKey Key = GetDupKey(ECD->getInitVal());
16031     DeclOrVector &Entry = EnumMap[Key];
16032 
16033     // First time encountering this value.
16034     if (Entry.isNull())
16035       Entry = ECD;
16036   }
16037 
16038   // Create vectors for any values that has duplicates.
16039   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16040     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
16041     if (!ValidDuplicateEnum(ECD, Enum))
16042       continue;
16043 
16044     DupKey Key = GetDupKey(ECD->getInitVal());
16045 
16046     DeclOrVector& Entry = EnumMap[Key];
16047     if (Entry.isNull())
16048       continue;
16049 
16050     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16051       // Ensure constants are different.
16052       if (D == ECD)
16053         continue;
16054 
16055       // Create new vector and push values onto it.
16056       ECDVector *Vec = new ECDVector();
16057       Vec->push_back(D);
16058       Vec->push_back(ECD);
16059 
16060       // Update entry to point to the duplicates vector.
16061       Entry = Vec;
16062 
16063       // Store the vector somewhere we can consult later for quick emission of
16064       // diagnostics.
16065       DupVector.push_back(Vec);
16066       continue;
16067     }
16068 
16069     ECDVector *Vec = Entry.get<ECDVector*>();
16070     // Make sure constants are not added more than once.
16071     if (*Vec->begin() == ECD)
16072       continue;
16073 
16074     Vec->push_back(ECD);
16075   }
16076 
16077   // Emit diagnostics.
16078   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
16079                                   DupVectorEnd = DupVector.end();
16080        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
16081     ECDVector *Vec = *DupVectorIter;
16082     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16083 
16084     // Emit warning for one enum constant.
16085     ECDVector::iterator I = Vec->begin();
16086     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
16087       << (*I)->getName() << (*I)->getInitVal().toString(10)
16088       << (*I)->getSourceRange();
16089     ++I;
16090 
16091     // Emit one note for each of the remaining enum constants with
16092     // the same value.
16093     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
16094       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
16095         << (*I)->getName() << (*I)->getInitVal().toString(10)
16096         << (*I)->getSourceRange();
16097     delete Vec;
16098   }
16099 }
16100 
16101 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16102                              bool AllowMask) const {
16103   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16104   assert(ED->isCompleteDefinition() && "expected enum definition");
16105 
16106   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16107   llvm::APInt &FlagBits = R.first->second;
16108 
16109   if (R.second) {
16110     for (auto *E : ED->enumerators()) {
16111       const auto &EVal = E->getInitVal();
16112       // Only single-bit enumerators introduce new flag values.
16113       if (EVal.isPowerOf2())
16114         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16115     }
16116   }
16117 
16118   // A value is in a flag enum if either its bits are a subset of the enum's
16119   // flag bits (the first condition) or we are allowing masks and the same is
16120   // true of its complement (the second condition). When masks are allowed, we
16121   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16122   //
16123   // While it's true that any value could be used as a mask, the assumption is
16124   // that a mask will have all of the insignificant bits set. Anything else is
16125   // likely a logic error.
16126   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16127   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16128 }
16129 
16130 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16131                          Decl *EnumDeclX,
16132                          ArrayRef<Decl *> Elements,
16133                          Scope *S, AttributeList *Attr) {
16134   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16135   QualType EnumType = Context.getTypeDeclType(Enum);
16136 
16137   if (Attr)
16138     ProcessDeclAttributeList(S, Enum, Attr);
16139 
16140   if (Enum->isDependentType()) {
16141     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16142       EnumConstantDecl *ECD =
16143         cast_or_null<EnumConstantDecl>(Elements[i]);
16144       if (!ECD) continue;
16145 
16146       ECD->setType(EnumType);
16147     }
16148 
16149     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16150     return;
16151   }
16152 
16153   // TODO: If the result value doesn't fit in an int, it must be a long or long
16154   // long value.  ISO C does not support this, but GCC does as an extension,
16155   // emit a warning.
16156   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16157   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16158   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16159 
16160   // Verify that all the values are okay, compute the size of the values, and
16161   // reverse the list.
16162   unsigned NumNegativeBits = 0;
16163   unsigned NumPositiveBits = 0;
16164 
16165   // Keep track of whether all elements have type int.
16166   bool AllElementsInt = true;
16167 
16168   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16169     EnumConstantDecl *ECD =
16170       cast_or_null<EnumConstantDecl>(Elements[i]);
16171     if (!ECD) continue;  // Already issued a diagnostic.
16172 
16173     const llvm::APSInt &InitVal = ECD->getInitVal();
16174 
16175     // Keep track of the size of positive and negative values.
16176     if (InitVal.isUnsigned() || InitVal.isNonNegative())
16177       NumPositiveBits = std::max(NumPositiveBits,
16178                                  (unsigned)InitVal.getActiveBits());
16179     else
16180       NumNegativeBits = std::max(NumNegativeBits,
16181                                  (unsigned)InitVal.getMinSignedBits());
16182 
16183     // Keep track of whether every enum element has type int (very commmon).
16184     if (AllElementsInt)
16185       AllElementsInt = ECD->getType() == Context.IntTy;
16186   }
16187 
16188   // Figure out the type that should be used for this enum.
16189   QualType BestType;
16190   unsigned BestWidth;
16191 
16192   // C++0x N3000 [conv.prom]p3:
16193   //   An rvalue of an unscoped enumeration type whose underlying
16194   //   type is not fixed can be converted to an rvalue of the first
16195   //   of the following types that can represent all the values of
16196   //   the enumeration: int, unsigned int, long int, unsigned long
16197   //   int, long long int, or unsigned long long int.
16198   // C99 6.4.4.3p2:
16199   //   An identifier declared as an enumeration constant has type int.
16200   // The C99 rule is modified by a gcc extension
16201   QualType BestPromotionType;
16202 
16203   bool Packed = Enum->hasAttr<PackedAttr>();
16204   // -fshort-enums is the equivalent to specifying the packed attribute on all
16205   // enum definitions.
16206   if (LangOpts.ShortEnums)
16207     Packed = true;
16208 
16209   if (Enum->isFixed()) {
16210     BestType = Enum->getIntegerType();
16211     if (BestType->isPromotableIntegerType())
16212       BestPromotionType = Context.getPromotedIntegerType(BestType);
16213     else
16214       BestPromotionType = BestType;
16215 
16216     BestWidth = Context.getIntWidth(BestType);
16217   }
16218   else if (NumNegativeBits) {
16219     // If there is a negative value, figure out the smallest integer type (of
16220     // int/long/longlong) that fits.
16221     // If it's packed, check also if it fits a char or a short.
16222     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16223       BestType = Context.SignedCharTy;
16224       BestWidth = CharWidth;
16225     } else if (Packed && NumNegativeBits <= ShortWidth &&
16226                NumPositiveBits < ShortWidth) {
16227       BestType = Context.ShortTy;
16228       BestWidth = ShortWidth;
16229     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16230       BestType = Context.IntTy;
16231       BestWidth = IntWidth;
16232     } else {
16233       BestWidth = Context.getTargetInfo().getLongWidth();
16234 
16235       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16236         BestType = Context.LongTy;
16237       } else {
16238         BestWidth = Context.getTargetInfo().getLongLongWidth();
16239 
16240         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16241           Diag(Enum->getLocation(), diag::ext_enum_too_large);
16242         BestType = Context.LongLongTy;
16243       }
16244     }
16245     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16246   } else {
16247     // If there is no negative value, figure out the smallest type that fits
16248     // all of the enumerator values.
16249     // If it's packed, check also if it fits a char or a short.
16250     if (Packed && NumPositiveBits <= CharWidth) {
16251       BestType = Context.UnsignedCharTy;
16252       BestPromotionType = Context.IntTy;
16253       BestWidth = CharWidth;
16254     } else if (Packed && NumPositiveBits <= ShortWidth) {
16255       BestType = Context.UnsignedShortTy;
16256       BestPromotionType = Context.IntTy;
16257       BestWidth = ShortWidth;
16258     } else if (NumPositiveBits <= IntWidth) {
16259       BestType = Context.UnsignedIntTy;
16260       BestWidth = IntWidth;
16261       BestPromotionType
16262         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16263                            ? Context.UnsignedIntTy : Context.IntTy;
16264     } else if (NumPositiveBits <=
16265                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16266       BestType = Context.UnsignedLongTy;
16267       BestPromotionType
16268         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16269                            ? Context.UnsignedLongTy : Context.LongTy;
16270     } else {
16271       BestWidth = Context.getTargetInfo().getLongLongWidth();
16272       assert(NumPositiveBits <= BestWidth &&
16273              "How could an initializer get larger than ULL?");
16274       BestType = Context.UnsignedLongLongTy;
16275       BestPromotionType
16276         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16277                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16278     }
16279   }
16280 
16281   // Loop over all of the enumerator constants, changing their types to match
16282   // the type of the enum if needed.
16283   for (auto *D : Elements) {
16284     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16285     if (!ECD) continue;  // Already issued a diagnostic.
16286 
16287     // Standard C says the enumerators have int type, but we allow, as an
16288     // extension, the enumerators to be larger than int size.  If each
16289     // enumerator value fits in an int, type it as an int, otherwise type it the
16290     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16291     // that X has type 'int', not 'unsigned'.
16292 
16293     // Determine whether the value fits into an int.
16294     llvm::APSInt InitVal = ECD->getInitVal();
16295 
16296     // If it fits into an integer type, force it.  Otherwise force it to match
16297     // the enum decl type.
16298     QualType NewTy;
16299     unsigned NewWidth;
16300     bool NewSign;
16301     if (!getLangOpts().CPlusPlus &&
16302         !Enum->isFixed() &&
16303         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16304       NewTy = Context.IntTy;
16305       NewWidth = IntWidth;
16306       NewSign = true;
16307     } else if (ECD->getType() == BestType) {
16308       // Already the right type!
16309       if (getLangOpts().CPlusPlus)
16310         // C++ [dcl.enum]p4: Following the closing brace of an
16311         // enum-specifier, each enumerator has the type of its
16312         // enumeration.
16313         ECD->setType(EnumType);
16314       continue;
16315     } else {
16316       NewTy = BestType;
16317       NewWidth = BestWidth;
16318       NewSign = BestType->isSignedIntegerOrEnumerationType();
16319     }
16320 
16321     // Adjust the APSInt value.
16322     InitVal = InitVal.extOrTrunc(NewWidth);
16323     InitVal.setIsSigned(NewSign);
16324     ECD->setInitVal(InitVal);
16325 
16326     // Adjust the Expr initializer and type.
16327     if (ECD->getInitExpr() &&
16328         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16329       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16330                                                 CK_IntegralCast,
16331                                                 ECD->getInitExpr(),
16332                                                 /*base paths*/ nullptr,
16333                                                 VK_RValue));
16334     if (getLangOpts().CPlusPlus)
16335       // C++ [dcl.enum]p4: Following the closing brace of an
16336       // enum-specifier, each enumerator has the type of its
16337       // enumeration.
16338       ECD->setType(EnumType);
16339     else
16340       ECD->setType(NewTy);
16341   }
16342 
16343   Enum->completeDefinition(BestType, BestPromotionType,
16344                            NumPositiveBits, NumNegativeBits);
16345 
16346   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16347 
16348   if (Enum->isClosedFlag()) {
16349     for (Decl *D : Elements) {
16350       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16351       if (!ECD) continue;  // Already issued a diagnostic.
16352 
16353       llvm::APSInt InitVal = ECD->getInitVal();
16354       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16355           !IsValueInFlagEnum(Enum, InitVal, true))
16356         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16357           << ECD << Enum;
16358     }
16359   }
16360 
16361   // Now that the enum type is defined, ensure it's not been underaligned.
16362   if (Enum->hasAttrs())
16363     CheckAlignasUnderalignment(Enum);
16364 }
16365 
16366 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16367                                   SourceLocation StartLoc,
16368                                   SourceLocation EndLoc) {
16369   StringLiteral *AsmString = cast<StringLiteral>(expr);
16370 
16371   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16372                                                    AsmString, StartLoc,
16373                                                    EndLoc);
16374   CurContext->addDecl(New);
16375   return New;
16376 }
16377 
16378 static void checkModuleImportContext(Sema &S, Module *M,
16379                                      SourceLocation ImportLoc, DeclContext *DC,
16380                                      bool FromInclude = false) {
16381   SourceLocation ExternCLoc;
16382 
16383   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16384     switch (LSD->getLanguage()) {
16385     case LinkageSpecDecl::lang_c:
16386       if (ExternCLoc.isInvalid())
16387         ExternCLoc = LSD->getLocStart();
16388       break;
16389     case LinkageSpecDecl::lang_cxx:
16390       break;
16391     }
16392     DC = LSD->getParent();
16393   }
16394 
16395   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16396     DC = DC->getParent();
16397 
16398   if (!isa<TranslationUnitDecl>(DC)) {
16399     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16400                           ? diag::ext_module_import_not_at_top_level_noop
16401                           : diag::err_module_import_not_at_top_level_fatal)
16402         << M->getFullModuleName() << DC;
16403     S.Diag(cast<Decl>(DC)->getLocStart(),
16404            diag::note_module_import_not_at_top_level) << DC;
16405   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16406     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16407       << M->getFullModuleName();
16408     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16409   }
16410 }
16411 
16412 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16413                                            SourceLocation ModuleLoc,
16414                                            ModuleDeclKind MDK,
16415                                            ModuleIdPath Path) {
16416   assert(getLangOpts().ModulesTS &&
16417          "should only have module decl in modules TS");
16418 
16419   // A module implementation unit requires that we are not compiling a module
16420   // of any kind. A module interface unit requires that we are not compiling a
16421   // module map.
16422   switch (getLangOpts().getCompilingModule()) {
16423   case LangOptions::CMK_None:
16424     // It's OK to compile a module interface as a normal translation unit.
16425     break;
16426 
16427   case LangOptions::CMK_ModuleInterface:
16428     if (MDK != ModuleDeclKind::Implementation)
16429       break;
16430 
16431     // We were asked to compile a module interface unit but this is a module
16432     // implementation unit. That indicates the 'export' is missing.
16433     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16434       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16435     MDK = ModuleDeclKind::Interface;
16436     break;
16437 
16438   case LangOptions::CMK_ModuleMap:
16439     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16440     return nullptr;
16441   }
16442 
16443   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16444 
16445   // FIXME: Most of this work should be done by the preprocessor rather than
16446   // here, in order to support macro import.
16447 
16448   // Only one module-declaration is permitted per source file.
16449   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16450     Diag(ModuleLoc, diag::err_module_redeclaration);
16451     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16452          diag::note_prev_module_declaration);
16453     return nullptr;
16454   }
16455 
16456   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16457   // modules, the dots here are just another character that can appear in a
16458   // module name.
16459   std::string ModuleName;
16460   for (auto &Piece : Path) {
16461     if (!ModuleName.empty())
16462       ModuleName += ".";
16463     ModuleName += Piece.first->getName();
16464   }
16465 
16466   // If a module name was explicitly specified on the command line, it must be
16467   // correct.
16468   if (!getLangOpts().CurrentModule.empty() &&
16469       getLangOpts().CurrentModule != ModuleName) {
16470     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16471         << SourceRange(Path.front().second, Path.back().second)
16472         << getLangOpts().CurrentModule;
16473     return nullptr;
16474   }
16475   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16476 
16477   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16478   Module *Mod;
16479 
16480   switch (MDK) {
16481   case ModuleDeclKind::Interface: {
16482     // We can't have parsed or imported a definition of this module or parsed a
16483     // module map defining it already.
16484     if (auto *M = Map.findModule(ModuleName)) {
16485       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16486       if (M->DefinitionLoc.isValid())
16487         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16488       else if (const auto *FE = M->getASTFile())
16489         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16490             << FE->getName();
16491       Mod = M;
16492       break;
16493     }
16494 
16495     // Create a Module for the module that we're defining.
16496     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16497                                            ModuleScopes.front().Module);
16498     assert(Mod && "module creation should not fail");
16499     break;
16500   }
16501 
16502   case ModuleDeclKind::Partition:
16503     // FIXME: Check we are in a submodule of the named module.
16504     return nullptr;
16505 
16506   case ModuleDeclKind::Implementation:
16507     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16508         PP.getIdentifierInfo(ModuleName), Path[0].second);
16509     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16510                                        /*IsIncludeDirective=*/false);
16511     if (!Mod) {
16512       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16513       // Create an empty module interface unit for error recovery.
16514       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16515                                              ModuleScopes.front().Module);
16516     }
16517     break;
16518   }
16519 
16520   // Switch from the global module to the named module.
16521   ModuleScopes.back().Module = Mod;
16522   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16523   VisibleModules.setVisible(Mod, ModuleLoc);
16524 
16525   // From now on, we have an owning module for all declarations we see.
16526   // However, those declarations are module-private unless explicitly
16527   // exported.
16528   auto *TU = Context.getTranslationUnitDecl();
16529   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16530   TU->setLocalOwningModule(Mod);
16531 
16532   // FIXME: Create a ModuleDecl.
16533   return nullptr;
16534 }
16535 
16536 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16537                                    SourceLocation ImportLoc,
16538                                    ModuleIdPath Path) {
16539   Module *Mod =
16540       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16541                                    /*IsIncludeDirective=*/false);
16542   if (!Mod)
16543     return true;
16544 
16545   VisibleModules.setVisible(Mod, ImportLoc);
16546 
16547   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16548 
16549   // FIXME: we should support importing a submodule within a different submodule
16550   // of the same top-level module. Until we do, make it an error rather than
16551   // silently ignoring the import.
16552   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16553   // warn on a redundant import of the current module?
16554   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16555       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16556     Diag(ImportLoc, getLangOpts().isCompilingModule()
16557                         ? diag::err_module_self_import
16558                         : diag::err_module_import_in_implementation)
16559         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16560 
16561   SmallVector<SourceLocation, 2> IdentifierLocs;
16562   Module *ModCheck = Mod;
16563   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16564     // If we've run out of module parents, just drop the remaining identifiers.
16565     // We need the length to be consistent.
16566     if (!ModCheck)
16567       break;
16568     ModCheck = ModCheck->Parent;
16569 
16570     IdentifierLocs.push_back(Path[I].second);
16571   }
16572 
16573   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16574                                           Mod, IdentifierLocs);
16575   if (!ModuleScopes.empty())
16576     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16577   CurContext->addDecl(Import);
16578 
16579   // Re-export the module if needed.
16580   if (Import->isExported() &&
16581       !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16582     getCurrentModule()->Exports.emplace_back(Mod, false);
16583 
16584   return Import;
16585 }
16586 
16587 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16588   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16589   BuildModuleInclude(DirectiveLoc, Mod);
16590 }
16591 
16592 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16593   // Determine whether we're in the #include buffer for a module. The #includes
16594   // in that buffer do not qualify as module imports; they're just an
16595   // implementation detail of us building the module.
16596   //
16597   // FIXME: Should we even get ActOnModuleInclude calls for those?
16598   bool IsInModuleIncludes =
16599       TUKind == TU_Module &&
16600       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16601 
16602   bool ShouldAddImport = !IsInModuleIncludes;
16603 
16604   // If this module import was due to an inclusion directive, create an
16605   // implicit import declaration to capture it in the AST.
16606   if (ShouldAddImport) {
16607     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16608     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16609                                                      DirectiveLoc, Mod,
16610                                                      DirectiveLoc);
16611     if (!ModuleScopes.empty())
16612       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16613     TU->addDecl(ImportD);
16614     Consumer.HandleImplicitImportDecl(ImportD);
16615   }
16616 
16617   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16618   VisibleModules.setVisible(Mod, DirectiveLoc);
16619 }
16620 
16621 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16622   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16623 
16624   ModuleScopes.push_back({});
16625   ModuleScopes.back().Module = Mod;
16626   if (getLangOpts().ModulesLocalVisibility)
16627     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16628 
16629   VisibleModules.setVisible(Mod, DirectiveLoc);
16630 
16631   // The enclosing context is now part of this module.
16632   // FIXME: Consider creating a child DeclContext to hold the entities
16633   // lexically within the module.
16634   if (getLangOpts().trackLocalOwningModule()) {
16635     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16636       cast<Decl>(DC)->setModuleOwnershipKind(
16637           getLangOpts().ModulesLocalVisibility
16638               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16639               : Decl::ModuleOwnershipKind::Visible);
16640       cast<Decl>(DC)->setLocalOwningModule(Mod);
16641     }
16642   }
16643 }
16644 
16645 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16646   if (getLangOpts().ModulesLocalVisibility) {
16647     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16648     // Leaving a module hides namespace names, so our visible namespace cache
16649     // is now out of date.
16650     VisibleNamespaceCache.clear();
16651   }
16652 
16653   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16654          "left the wrong module scope");
16655   ModuleScopes.pop_back();
16656 
16657   // We got to the end of processing a local module. Create an
16658   // ImportDecl as we would for an imported module.
16659   FileID File = getSourceManager().getFileID(EomLoc);
16660   SourceLocation DirectiveLoc;
16661   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16662     // We reached the end of a #included module header. Use the #include loc.
16663     assert(File != getSourceManager().getMainFileID() &&
16664            "end of submodule in main source file");
16665     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16666   } else {
16667     // We reached an EOM pragma. Use the pragma location.
16668     DirectiveLoc = EomLoc;
16669   }
16670   BuildModuleInclude(DirectiveLoc, Mod);
16671 
16672   // Any further declarations are in whatever module we returned to.
16673   if (getLangOpts().trackLocalOwningModule()) {
16674     // The parser guarantees that this is the same context that we entered
16675     // the module within.
16676     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16677       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16678       if (!getCurrentModule())
16679         cast<Decl>(DC)->setModuleOwnershipKind(
16680             Decl::ModuleOwnershipKind::Unowned);
16681     }
16682   }
16683 }
16684 
16685 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16686                                                       Module *Mod) {
16687   // Bail if we're not allowed to implicitly import a module here.
16688   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16689       VisibleModules.isVisible(Mod))
16690     return;
16691 
16692   // Create the implicit import declaration.
16693   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16694   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16695                                                    Loc, Mod, Loc);
16696   TU->addDecl(ImportD);
16697   Consumer.HandleImplicitImportDecl(ImportD);
16698 
16699   // Make the module visible.
16700   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16701   VisibleModules.setVisible(Mod, Loc);
16702 }
16703 
16704 /// We have parsed the start of an export declaration, including the '{'
16705 /// (if present).
16706 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16707                                  SourceLocation LBraceLoc) {
16708   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16709 
16710   // C++ Modules TS draft:
16711   //   An export-declaration shall appear in the purview of a module other than
16712   //   the global module.
16713   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16714     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16715 
16716   //   An export-declaration [...] shall not contain more than one
16717   //   export keyword.
16718   //
16719   // The intent here is that an export-declaration cannot appear within another
16720   // export-declaration.
16721   if (D->isExported())
16722     Diag(ExportLoc, diag::err_export_within_export);
16723 
16724   CurContext->addDecl(D);
16725   PushDeclContext(S, D);
16726   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16727   return D;
16728 }
16729 
16730 /// Complete the definition of an export declaration.
16731 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16732   auto *ED = cast<ExportDecl>(D);
16733   if (RBraceLoc.isValid())
16734     ED->setRBraceLoc(RBraceLoc);
16735 
16736   // FIXME: Diagnose export of internal-linkage declaration (including
16737   // anonymous namespace).
16738 
16739   PopDeclContext();
16740   return D;
16741 }
16742 
16743 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16744                                       IdentifierInfo* AliasName,
16745                                       SourceLocation PragmaLoc,
16746                                       SourceLocation NameLoc,
16747                                       SourceLocation AliasNameLoc) {
16748   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16749                                          LookupOrdinaryName);
16750   AsmLabelAttr *Attr =
16751       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16752 
16753   // If a declaration that:
16754   // 1) declares a function or a variable
16755   // 2) has external linkage
16756   // already exists, add a label attribute to it.
16757   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16758     if (isDeclExternC(PrevDecl))
16759       PrevDecl->addAttr(Attr);
16760     else
16761       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16762           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16763   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16764   } else
16765     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16766 }
16767 
16768 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16769                              SourceLocation PragmaLoc,
16770                              SourceLocation NameLoc) {
16771   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16772 
16773   if (PrevDecl) {
16774     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16775   } else {
16776     (void)WeakUndeclaredIdentifiers.insert(
16777       std::pair<IdentifierInfo*,WeakInfo>
16778         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16779   }
16780 }
16781 
16782 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16783                                 IdentifierInfo* AliasName,
16784                                 SourceLocation PragmaLoc,
16785                                 SourceLocation NameLoc,
16786                                 SourceLocation AliasNameLoc) {
16787   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16788                                     LookupOrdinaryName);
16789   WeakInfo W = WeakInfo(Name, NameLoc);
16790 
16791   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16792     if (!PrevDecl->hasAttr<AliasAttr>())
16793       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16794         DeclApplyPragmaWeak(TUScope, ND, W);
16795   } else {
16796     (void)WeakUndeclaredIdentifiers.insert(
16797       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16798   }
16799 }
16800 
16801 Decl *Sema::getObjCDeclContext() const {
16802   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16803 }
16804