1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142 
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150 
151   default:
152     break;
153   }
154 
155   return false;
156 }
157 
158 namespace {
159 enum class UnqualifiedTypeNameLookupResult {
160   NotFound,
161   FoundNonType,
162   FoundType
163 };
164 } // end anonymous namespace
165 
166 /// \brief Tries to perform unqualified lookup of the type decls in bases for
167 /// dependent class.
168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169 /// type decl, \a FoundType if only type decls are found.
170 static UnqualifiedTypeNameLookupResult
171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
172                                 SourceLocation NameLoc,
173                                 const CXXRecordDecl *RD) {
174   if (!RD->hasDefinition())
175     return UnqualifiedTypeNameLookupResult::NotFound;
176   // Look for type decls in base classes.
177   UnqualifiedTypeNameLookupResult FoundTypeDecl =
178       UnqualifiedTypeNameLookupResult::NotFound;
179   for (const auto &Base : RD->bases()) {
180     const CXXRecordDecl *BaseRD = nullptr;
181     if (auto *BaseTT = Base.getType()->getAs<TagType>())
182       BaseRD = BaseTT->getAsCXXRecordDecl();
183     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184       // Look for type decls in dependent base classes that have known primary
185       // templates.
186       if (!TST || !TST->isDependentType())
187         continue;
188       auto *TD = TST->getTemplateName().getAsTemplateDecl();
189       if (!TD)
190         continue;
191       if (auto *BasePrimaryTemplate =
192           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194           BaseRD = BasePrimaryTemplate;
195         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
196           if (const ClassTemplatePartialSpecializationDecl *PS =
197                   CTD->findPartialSpecialization(Base.getType()))
198             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199               BaseRD = PS;
200         }
201       }
202     }
203     if (BaseRD) {
204       for (NamedDecl *ND : BaseRD->lookup(&II)) {
205         if (!isa<TypeDecl>(ND))
206           return UnqualifiedTypeNameLookupResult::FoundNonType;
207         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208       }
209       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211         case UnqualifiedTypeNameLookupResult::FoundNonType:
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         case UnqualifiedTypeNameLookupResult::FoundType:
214           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215           break;
216         case UnqualifiedTypeNameLookupResult::NotFound:
217           break;
218         }
219       }
220     }
221   }
222 
223   return FoundTypeDecl;
224 }
225 
226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
227                                                       const IdentifierInfo &II,
228                                                       SourceLocation NameLoc) {
229   // Lookup in the parent class template context, if any.
230   const CXXRecordDecl *RD = nullptr;
231   UnqualifiedTypeNameLookupResult FoundTypeDecl =
232       UnqualifiedTypeNameLookupResult::NotFound;
233   for (DeclContext *DC = S.CurContext;
234        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235        DC = DC->getParent()) {
236     // Look for type decls in dependent base classes that have known primary
237     // templates.
238     RD = dyn_cast<CXXRecordDecl>(DC);
239     if (RD && RD->getDescribedClassTemplate())
240       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241   }
242   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243     return nullptr;
244 
245   // We found some types in dependent base classes.  Recover as if the user
246   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
247   // lookup during template instantiation.
248   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249 
250   ASTContext &Context = S.Context;
251   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252                                           cast<Type>(Context.getRecordType(RD)));
253   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254 
255   CXXScopeSpec SS;
256   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257 
258   TypeLocBuilder Builder;
259   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
260   DepTL.setNameLoc(NameLoc);
261   DepTL.setElaboratedKeywordLoc(SourceLocation());
262   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264 }
265 
266 /// \brief If the identifier refers to a type name within this scope,
267 /// return the declaration of that type.
268 ///
269 /// This routine performs ordinary name lookup of the identifier II
270 /// within the given scope, with optional C++ scope specifier SS, to
271 /// determine whether the name refers to a type. If so, returns an
272 /// opaque pointer (actually a QualType) corresponding to that
273 /// type. Otherwise, returns NULL.
274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275                              Scope *S, CXXScopeSpec *SS,
276                              bool isClassName, bool HasTrailingDot,
277                              ParsedType ObjectTypePtr,
278                              bool IsCtorOrDtorName,
279                              bool WantNontrivialTypeSourceInfo,
280                              bool IsClassTemplateDeductionContext,
281                              IdentifierInfo **CorrectedII) {
282   // FIXME: Consider allowing this outside C++1z mode as an extension.
283   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
285                               !isClassName && !HasTrailingDot;
286 
287   // Determine where we will perform name lookup.
288   DeclContext *LookupCtx = nullptr;
289   if (ObjectTypePtr) {
290     QualType ObjectType = ObjectTypePtr.get();
291     if (ObjectType->isRecordType())
292       LookupCtx = computeDeclContext(ObjectType);
293   } else if (SS && SS->isNotEmpty()) {
294     LookupCtx = computeDeclContext(*SS, false);
295 
296     if (!LookupCtx) {
297       if (isDependentScopeSpecifier(*SS)) {
298         // C++ [temp.res]p3:
299         //   A qualified-id that refers to a type and in which the
300         //   nested-name-specifier depends on a template-parameter (14.6.2)
301         //   shall be prefixed by the keyword typename to indicate that the
302         //   qualified-id denotes a type, forming an
303         //   elaborated-type-specifier (7.1.5.3).
304         //
305         // We therefore do not perform any name lookup if the result would
306         // refer to a member of an unknown specialization.
307         if (!isClassName && !IsCtorOrDtorName)
308           return nullptr;
309 
310         // We know from the grammar that this name refers to a type,
311         // so build a dependent node to describe the type.
312         if (WantNontrivialTypeSourceInfo)
313           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314 
315         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317                                        II, NameLoc);
318         return ParsedType::make(T);
319       }
320 
321       return nullptr;
322     }
323 
324     if (!LookupCtx->isDependentContext() &&
325         RequireCompleteDeclContext(*SS, LookupCtx))
326       return nullptr;
327   }
328 
329   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330   // lookup for class-names.
331   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332                                       LookupOrdinaryName;
333   LookupResult Result(*this, &II, NameLoc, Kind);
334   if (LookupCtx) {
335     // Perform "qualified" name lookup into the declaration context we
336     // computed, which is either the type of the base of a member access
337     // expression or the declaration context associated with a prior
338     // nested-name-specifier.
339     LookupQualifiedName(Result, LookupCtx);
340 
341     if (ObjectTypePtr && Result.empty()) {
342       // C++ [basic.lookup.classref]p3:
343       //   If the unqualified-id is ~type-name, the type-name is looked up
344       //   in the context of the entire postfix-expression. If the type T of
345       //   the object expression is of a class type C, the type-name is also
346       //   looked up in the scope of class C. At least one of the lookups shall
347       //   find a name that refers to (possibly cv-qualified) T.
348       LookupName(Result, S);
349     }
350   } else {
351     // Perform unqualified name lookup.
352     LookupName(Result, S);
353 
354     // For unqualified lookup in a class template in MSVC mode, look into
355     // dependent base classes where the primary class template is known.
356     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357       if (ParsedType TypeInBase =
358               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359         return TypeInBase;
360     }
361   }
362 
363   NamedDecl *IIDecl = nullptr;
364   switch (Result.getResultKind()) {
365   case LookupResult::NotFound:
366   case LookupResult::NotFoundInCurrentInstantiation:
367     if (CorrectedII) {
368       TypoCorrection Correction =
369           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370                       llvm::make_unique<TypeNameValidatorCCC>(
371                           true, isClassName, AllowDeducedTemplate),
372                       CTK_ErrorRecovery);
373       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374       TemplateTy Template;
375       bool MemberOfUnknownSpecialization;
376       UnqualifiedId TemplateName;
377       TemplateName.setIdentifier(NewII, NameLoc);
378       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379       CXXScopeSpec NewSS, *NewSSPtr = SS;
380       if (SS && NNS) {
381         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382         NewSSPtr = &NewSS;
383       }
384       if (Correction && (NNS || NewII != &II) &&
385           // Ignore a correction to a template type as the to-be-corrected
386           // identifier is not a template (typo correction for template names
387           // is handled elsewhere).
388           !(getLangOpts().CPlusPlus && NewSSPtr &&
389             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390                            Template, MemberOfUnknownSpecialization))) {
391         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392                                     isClassName, HasTrailingDot, ObjectTypePtr,
393                                     IsCtorOrDtorName,
394                                     WantNontrivialTypeSourceInfo,
395                                     IsClassTemplateDeductionContext);
396         if (Ty) {
397           diagnoseTypo(Correction,
398                        PDiag(diag::err_unknown_type_or_class_name_suggest)
399                          << Result.getLookupName() << isClassName);
400           if (SS && NNS)
401             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402           *CorrectedII = NewII;
403           return Ty;
404         }
405       }
406     }
407     // If typo correction failed or was not performed, fall through
408     LLVM_FALLTHROUGH;
409   case LookupResult::FoundOverloaded:
410   case LookupResult::FoundUnresolvedValue:
411     Result.suppressDiagnostics();
412     return nullptr;
413 
414   case LookupResult::Ambiguous:
415     // Recover from type-hiding ambiguities by hiding the type.  We'll
416     // do the lookup again when looking for an object, and we can
417     // diagnose the error then.  If we don't do this, then the error
418     // about hiding the type will be immediately followed by an error
419     // that only makes sense if the identifier was treated like a type.
420     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
421       Result.suppressDiagnostics();
422       return nullptr;
423     }
424 
425     // Look to see if we have a type anywhere in the list of results.
426     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427          Res != ResEnd; ++Res) {
428       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430         if (!IIDecl ||
431             (*Res)->getLocation().getRawEncoding() <
432               IIDecl->getLocation().getRawEncoding())
433           IIDecl = *Res;
434       }
435     }
436 
437     if (!IIDecl) {
438       // None of the entities we found is a type, so there is no way
439       // to even assume that the result is a type. In this case, don't
440       // complain about the ambiguity. The parser will either try to
441       // perform this lookup again (e.g., as an object name), which
442       // will produce the ambiguity, or will complain that it expected
443       // a type name.
444       Result.suppressDiagnostics();
445       return nullptr;
446     }
447 
448     // We found a type within the ambiguous lookup; diagnose the
449     // ambiguity and then return that type. This might be the right
450     // answer, or it might not be, but it suppresses any attempt to
451     // perform the name lookup again.
452     break;
453 
454   case LookupResult::Found:
455     IIDecl = Result.getFoundDecl();
456     break;
457   }
458 
459   assert(IIDecl && "Didn't find decl");
460 
461   QualType T;
462   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463     // C++ [class.qual]p2: A lookup that would find the injected-class-name
464     // instead names the constructors of the class, except when naming a class.
465     // This is ill-formed when we're not actually forming a ctor or dtor name.
466     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469         FoundRD->isInjectedClassName() &&
470         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472           << &II << /*Type*/1;
473 
474     DiagnoseUseOfDecl(IIDecl, NameLoc);
475 
476     T = Context.getTypeDeclType(TD);
477     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480     if (!HasTrailingDot)
481       T = Context.getObjCInterfaceType(IDecl);
482   } else if (AllowDeducedTemplate) {
483     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
484       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
485                                                        QualType(), false);
486   }
487 
488   if (T.isNull()) {
489     // If it's not plausibly a type, suppress diagnostics.
490     Result.suppressDiagnostics();
491     return nullptr;
492   }
493 
494   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495   // constructor or destructor name (in such a case, the scope specifier
496   // will be attached to the enclosing Expr or Decl node).
497   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498       !isa<ObjCInterfaceDecl>(IIDecl)) {
499     if (WantNontrivialTypeSourceInfo) {
500       // Construct a type with type-source information.
501       TypeLocBuilder Builder;
502       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503 
504       T = getElaboratedType(ETK_None, *SS, T);
505       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
506       ElabTL.setElaboratedKeywordLoc(SourceLocation());
507       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509     } else {
510       T = getElaboratedType(ETK_None, *SS, T);
511     }
512   }
513 
514   return ParsedType::make(T);
515 }
516 
517 // Builds a fake NNS for the given decl context.
518 static NestedNameSpecifier *
519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
520   for (;; DC = DC->getLookupParent()) {
521     DC = DC->getPrimaryContext();
522     auto *ND = dyn_cast<NamespaceDecl>(DC);
523     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524       return NestedNameSpecifier::Create(Context, nullptr, ND);
525     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527                                          RD->getTypeForDecl());
528     else if (isa<TranslationUnitDecl>(DC))
529       return NestedNameSpecifier::GlobalSpecifier(Context);
530   }
531   llvm_unreachable("something isn't in TU scope?");
532 }
533 
534 /// Find the parent class with dependent bases of the innermost enclosing method
535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536 /// up allowing unqualified dependent type names at class-level, which MSVC
537 /// correctly rejects.
538 static const CXXRecordDecl *
539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
540   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541     DC = DC->getPrimaryContext();
542     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543       if (MD->getParent()->hasAnyDependentBases())
544         return MD->getParent();
545   }
546   return nullptr;
547 }
548 
549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
550                                           SourceLocation NameLoc,
551                                           bool IsTemplateTypeArg) {
552   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
553 
554   NestedNameSpecifier *NNS = nullptr;
555   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556     // If we weren't able to parse a default template argument, delay lookup
557     // until instantiation time by making a non-dependent DependentTypeName. We
558     // pretend we saw a NestedNameSpecifier referring to the current scope, and
559     // lookup is retried.
560     // FIXME: This hurts our diagnostic quality, since we get errors like "no
561     // type named 'Foo' in 'current_namespace'" when the user didn't write any
562     // name specifiers.
563     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565   } else if (const CXXRecordDecl *RD =
566                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
567     // Build a DependentNameType that will perform lookup into RD at
568     // instantiation time.
569     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570                                       RD->getTypeForDecl());
571 
572     // Diagnose that this identifier was undeclared, and retry the lookup during
573     // template instantiation.
574     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575                                                                       << RD;
576   } else {
577     // This is not a situation that we should recover from.
578     return ParsedType();
579   }
580 
581   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582 
583   // Build type location information.  We synthesized the qualifier, so we have
584   // to build a fake NestedNameSpecifierLoc.
585   NestedNameSpecifierLocBuilder NNSLocBuilder;
586   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588 
589   TypeLocBuilder Builder;
590   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
591   DepTL.setNameLoc(NameLoc);
592   DepTL.setElaboratedKeywordLoc(SourceLocation());
593   DepTL.setQualifierLoc(QualifierLoc);
594   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595 }
596 
597 /// isTagName() - This method is called *for error recovery purposes only*
598 /// to determine if the specified name is a valid tag name ("struct foo").  If
599 /// so, this returns the TST for the tag corresponding to it (TST_enum,
600 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
601 /// cases in C where the user forgot to specify the tag.
602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
603   // Do a tag name lookup in this scope.
604   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605   LookupName(R, S, false);
606   R.suppressDiagnostics();
607   if (R.getResultKind() == LookupResult::Found)
608     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609       switch (TD->getTagKind()) {
610       case TTK_Struct: return DeclSpec::TST_struct;
611       case TTK_Interface: return DeclSpec::TST_interface;
612       case TTK_Union:  return DeclSpec::TST_union;
613       case TTK_Class:  return DeclSpec::TST_class;
614       case TTK_Enum:   return DeclSpec::TST_enum;
615       }
616     }
617 
618   return DeclSpec::TST_unspecified;
619 }
620 
621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
623 /// then downgrade the missing typename error to a warning.
624 /// This is needed for MSVC compatibility; Example:
625 /// @code
626 /// template<class T> class A {
627 /// public:
628 ///   typedef int TYPE;
629 /// };
630 /// template<class T> class B : public A<T> {
631 /// public:
632 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
633 /// };
634 /// @endcode
635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
636   if (CurContext->isRecord()) {
637     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638       return true;
639 
640     const Type *Ty = SS->getScopeRep()->getAsType();
641 
642     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643     for (const auto &Base : RD->bases())
644       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645         return true;
646     return S->isFunctionPrototypeScope();
647   }
648   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649 }
650 
651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
652                                    SourceLocation IILoc,
653                                    Scope *S,
654                                    CXXScopeSpec *SS,
655                                    ParsedType &SuggestedType,
656                                    bool IsTemplateName) {
657   // Don't report typename errors for editor placeholders.
658   if (II->isEditorPlaceholder())
659     return;
660   // We don't have anything to suggest (yet).
661   SuggestedType = nullptr;
662 
663   // There may have been a typo in the name of the type. Look up typo
664   // results, in case we have something that we can suggest.
665   if (TypoCorrection Corrected =
666           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667                       llvm::make_unique<TypeNameValidatorCCC>(
668                           false, false, IsTemplateName, !IsTemplateName),
669                       CTK_ErrorRecovery)) {
670     // FIXME: Support error recovery for the template-name case.
671     bool CanRecover = !IsTemplateName;
672     if (Corrected.isKeyword()) {
673       // We corrected to a keyword.
674       diagnoseTypo(Corrected,
675                    PDiag(IsTemplateName ? diag::err_no_template_suggest
676                                         : diag::err_unknown_typename_suggest)
677                        << II);
678       II = Corrected.getCorrectionAsIdentifierInfo();
679     } else {
680       // We found a similarly-named type or interface; suggest that.
681       if (!SS || !SS->isSet()) {
682         diagnoseTypo(Corrected,
683                      PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                           : diag::err_unknown_typename_suggest)
685                          << II, CanRecover);
686       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689                                 II->getName().equals(CorrectedStr);
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName
692                                ? diag::err_no_member_template_suggest
693                                : diag::err_unknown_nested_typename_suggest)
694                          << II << DC << DroppedSpecifier << SS->getRange(),
695                      CanRecover);
696       } else {
697         llvm_unreachable("could not have corrected a typo here");
698       }
699 
700       if (!CanRecover)
701         return;
702 
703       CXXScopeSpec tmpSS;
704       if (Corrected.getCorrectionSpecifier())
705         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706                           SourceRange(IILoc));
707       // FIXME: Support class template argument deduction here.
708       SuggestedType =
709           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711                       /*IsCtorOrDtorName=*/false,
712                       /*NonTrivialTypeSourceInfo=*/true);
713     }
714     return;
715   }
716 
717   if (getLangOpts().CPlusPlus && !IsTemplateName) {
718     // See if II is a class template that the user forgot to pass arguments to.
719     UnqualifiedId Name;
720     Name.setIdentifier(II, IILoc);
721     CXXScopeSpec EmptySS;
722     TemplateTy TemplateResult;
723     bool MemberOfUnknownSpecialization;
724     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725                        Name, nullptr, true, TemplateResult,
726                        MemberOfUnknownSpecialization) == TNK_Type_template) {
727       TemplateName TplName = TemplateResult.get();
728       Diag(IILoc, diag::err_template_missing_args)
729         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732           << TplDecl->getTemplateParameters()->getSourceRange();
733       }
734       return;
735     }
736   }
737 
738   // FIXME: Should we move the logic that tries to recover from a missing tag
739   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741   if (!SS || (!SS->isSet() && !SS->isInvalid()))
742     Diag(IILoc, IsTemplateName ? diag::err_no_template
743                                : diag::err_unknown_typename)
744         << II;
745   else if (DeclContext *DC = computeDeclContext(*SS, false))
746     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747                                : diag::err_typename_nested_not_found)
748         << II << DC << SS->getRange();
749   else if (isDependentScopeSpecifier(*SS)) {
750     unsigned DiagID = diag::err_typename_missing;
751     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752       DiagID = diag::ext_typename_missing;
753 
754     Diag(SS->getRange().getBegin(), DiagID)
755       << SS->getScopeRep() << II->getName()
756       << SourceRange(SS->getRange().getBegin(), IILoc)
757       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758     SuggestedType = ActOnTypenameType(S, SourceLocation(),
759                                       *SS, *II, IILoc).get();
760   } else {
761     assert(SS && SS->isInvalid() &&
762            "Invalid scope specifier has already been diagnosed");
763   }
764 }
765 
766 /// \brief Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770                        NextToken.is(tok::less);
771 
772   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774       return true;
775 
776     if (CheckTemplate && isa<TemplateDecl>(*I))
777       return true;
778   }
779 
780   return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784                                     Scope *S, CXXScopeSpec &SS,
785                                     IdentifierInfo *&Name,
786                                     SourceLocation NameLoc) {
787   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788   SemaRef.LookupParsedName(R, S, &SS);
789   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790     StringRef FixItTagName;
791     switch (Tag->getTagKind()) {
792       case TTK_Class:
793         FixItTagName = "class ";
794         break;
795 
796       case TTK_Enum:
797         FixItTagName = "enum ";
798         break;
799 
800       case TTK_Struct:
801         FixItTagName = "struct ";
802         break;
803 
804       case TTK_Interface:
805         FixItTagName = "__interface ";
806         break;
807 
808       case TTK_Union:
809         FixItTagName = "union ";
810         break;
811     }
812 
813     StringRef TagName = FixItTagName.drop_back();
814     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819          I != IEnd; ++I)
820       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821         << Name << TagName;
822 
823     // Replace lookup results with just the tag decl.
824     Result.clear(Sema::LookupTagName);
825     SemaRef.LookupParsedName(Result, S, &SS);
826     return true;
827   }
828 
829   return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834                                   QualType T, SourceLocation NameLoc) {
835   ASTContext &Context = S.Context;
836 
837   TypeLocBuilder Builder;
838   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840   T = S.getElaboratedType(ETK_None, SS, T);
841   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842   ElabTL.setElaboratedKeywordLoc(SourceLocation());
843   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
847 Sema::NameClassification
848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849                    SourceLocation NameLoc, const Token &NextToken,
850                    bool IsAddressOfOperand,
851                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887 
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890 
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920 
921     // In C, we first see whether there is a tag type by the same name, in
922     // which case it's likely that the user just forgot to write "enum",
923     // "struct", or "union".
924     if (!getLangOpts().CPlusPlus && !SecondTry &&
925         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926       break;
927     }
928 
929     // Perform typo correction to determine if there is another name that is
930     // close to this name.
931     if (!SecondTry && CCC) {
932       SecondTry = true;
933       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934                                                  Result.getLookupKind(), S,
935                                                  &SS, std::move(CCC),
936                                                  CTK_ErrorRecovery)) {
937         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938         unsigned QualifiedDiag = diag::err_no_member_suggest;
939 
940         NamedDecl *FirstDecl = Corrected.getFoundDecl();
941         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944           UnqualifiedDiag = diag::err_no_template_suggest;
945           QualifiedDiag = diag::err_no_member_template_suggest;
946         } else if (UnderlyingFirstDecl &&
947                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950           UnqualifiedDiag = diag::err_unknown_typename_suggest;
951           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952         }
953 
954         if (SS.isEmpty()) {
955           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956         } else {// FIXME: is this even reachable? Test it.
957           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959                                   Name->getName().equals(CorrectedStr);
960           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961                                     << Name << computeDeclContext(SS, false)
962                                     << DroppedSpecifier << SS.getRange());
963         }
964 
965         // Update the name, so that the caller has the new name.
966         Name = Corrected.getCorrectionAsIdentifierInfo();
967 
968         // Typo correction corrected to a keyword.
969         if (Corrected.isKeyword())
970           return Name;
971 
972         // Also update the LookupResult...
973         // FIXME: This should probably go away at some point
974         Result.clear();
975         Result.setLookupName(Corrected.getCorrection());
976         if (FirstDecl)
977           Result.addDecl(FirstDecl);
978 
979         // If we found an Objective-C instance variable, let
980         // LookupInObjCMethod build the appropriate expression to
981         // reference the ivar.
982         // FIXME: This is a gross hack.
983         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984           Result.clear();
985           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986           return E;
987         }
988 
989         goto Corrected;
990       }
991     }
992 
993     // We failed to correct; just fall through and let the parser deal with it.
994     Result.suppressDiagnostics();
995     return NameClassification::Unknown();
996 
997   case LookupResult::NotFoundInCurrentInstantiation: {
998     // We performed name lookup into the current instantiation, and there were
999     // dependent bases, so we treat this result the same way as any other
1000     // dependent nested-name-specifier.
1001 
1002     // C++ [temp.res]p2:
1003     //   A name used in a template declaration or definition and that is
1004     //   dependent on a template-parameter is assumed not to name a type
1005     //   unless the applicable name lookup finds a type name or the name is
1006     //   qualified by the keyword typename.
1007     //
1008     // FIXME: If the next token is '<', we might want to ask the parser to
1009     // perform some heroics to see if we actually have a
1010     // template-argument-list, which would indicate a missing 'template'
1011     // keyword here.
1012     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013                                       NameInfo, IsAddressOfOperand,
1014                                       /*TemplateArgs=*/nullptr);
1015   }
1016 
1017   case LookupResult::Found:
1018   case LookupResult::FoundOverloaded:
1019   case LookupResult::FoundUnresolvedValue:
1020     break;
1021 
1022   case LookupResult::Ambiguous:
1023     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024         hasAnyAcceptableTemplateNames(Result)) {
1025       // C++ [temp.local]p3:
1026       //   A lookup that finds an injected-class-name (10.2) can result in an
1027       //   ambiguity in certain cases (for example, if it is found in more than
1028       //   one base class). If all of the injected-class-names that are found
1029       //   refer to specializations of the same class template, and if the name
1030       //   is followed by a template-argument-list, the reference refers to the
1031       //   class template itself and not a specialization thereof, and is not
1032       //   ambiguous.
1033       //
1034       // This filtering can make an ambiguous result into an unambiguous one,
1035       // so try again after filtering out template names.
1036       FilterAcceptableTemplateNames(Result);
1037       if (!Result.isAmbiguous()) {
1038         IsFilteredTemplateName = true;
1039         break;
1040       }
1041     }
1042 
1043     // Diagnose the ambiguity and return an error.
1044     return NameClassification::Error();
1045   }
1046 
1047   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049     // C++ [temp.names]p3:
1050     //   After name lookup (3.4) finds that a name is a template-name or that
1051     //   an operator-function-id or a literal- operator-id refers to a set of
1052     //   overloaded functions any member of which is a function template if
1053     //   this is followed by a <, the < is always taken as the delimiter of a
1054     //   template-argument-list and never as the less-than operator.
1055     if (!IsFilteredTemplateName)
1056       FilterAcceptableTemplateNames(Result);
1057 
1058     if (!Result.empty()) {
1059       bool IsFunctionTemplate;
1060       bool IsVarTemplate;
1061       TemplateName Template;
1062       if (Result.end() - Result.begin() > 1) {
1063         IsFunctionTemplate = true;
1064         Template = Context.getOverloadedTemplateName(Result.begin(),
1065                                                      Result.end());
1066       } else {
1067         TemplateDecl *TD
1068           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074                                                     /*TemplateKeyword=*/false,
1075                                                       TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// \brief Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 /// 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->duplicatesAllowed() || !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 /// MergeFunctionDecl - We just parsed a function 'New' from
2933 /// declarator D which has the same name and scope as a previous
2934 /// declaration 'Old'.  Figure out how to resolve this situation,
2935 /// merging decls or emitting diagnostics as appropriate.
2936 ///
2937 /// In C++, New and Old must be declarations that are not
2938 /// overloaded. Use IsOverload to determine whether New and Old are
2939 /// overloaded, and to select the Old declaration that New should be
2940 /// merged with.
2941 ///
2942 /// Returns true if there was an error, false otherwise.
2943 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2944                              Scope *S, bool MergeTypeWithOld) {
2945   // Verify the old decl was also a function.
2946   FunctionDecl *Old = OldD->getAsFunction();
2947   if (!Old) {
2948     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2949       if (New->getFriendObjectKind()) {
2950         Diag(New->getLocation(), diag::err_using_decl_friend);
2951         Diag(Shadow->getTargetDecl()->getLocation(),
2952              diag::note_using_decl_target);
2953         Diag(Shadow->getUsingDecl()->getLocation(),
2954              diag::note_using_decl) << 0;
2955         return true;
2956       }
2957 
2958       // Check whether the two declarations might declare the same function.
2959       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2960         return true;
2961       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2962     } else {
2963       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2964         << New->getDeclName();
2965       notePreviousDefinition(OldD, New->getLocation());
2966       return true;
2967     }
2968   }
2969 
2970   // If the old declaration is invalid, just give up here.
2971   if (Old->isInvalidDecl())
2972     return true;
2973 
2974   diag::kind PrevDiag;
2975   SourceLocation OldLocation;
2976   std::tie(PrevDiag, OldLocation) =
2977       getNoteDiagForInvalidRedeclaration(Old, New);
2978 
2979   // Don't complain about this if we're in GNU89 mode and the old function
2980   // is an extern inline function.
2981   // Don't complain about specializations. They are not supposed to have
2982   // storage classes.
2983   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2984       New->getStorageClass() == SC_Static &&
2985       Old->hasExternalFormalLinkage() &&
2986       !New->getTemplateSpecializationInfo() &&
2987       !canRedefineFunction(Old, getLangOpts())) {
2988     if (getLangOpts().MicrosoftExt) {
2989       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2990       Diag(OldLocation, PrevDiag);
2991     } else {
2992       Diag(New->getLocation(), diag::err_static_non_static) << New;
2993       Diag(OldLocation, PrevDiag);
2994       return true;
2995     }
2996   }
2997 
2998   if (New->hasAttr<InternalLinkageAttr>() &&
2999       !Old->hasAttr<InternalLinkageAttr>()) {
3000     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3001         << New->getDeclName();
3002     notePreviousDefinition(Old, New->getLocation());
3003     New->dropAttr<InternalLinkageAttr>();
3004   }
3005 
3006   if (CheckRedeclarationModuleOwnership(New, Old))
3007     return true;
3008 
3009   if (!getLangOpts().CPlusPlus) {
3010     bool OldOvl = Old->hasAttr<OverloadableAttr>();
3011     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3012       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3013         << New << OldOvl;
3014 
3015       // Try our best to find a decl that actually has the overloadable
3016       // attribute for the note. In most cases (e.g. programs with only one
3017       // broken declaration/definition), this won't matter.
3018       //
3019       // FIXME: We could do this if we juggled some extra state in
3020       // OverloadableAttr, rather than just removing it.
3021       const Decl *DiagOld = Old;
3022       if (OldOvl) {
3023         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3024           const auto *A = D->getAttr<OverloadableAttr>();
3025           return A && !A->isImplicit();
3026         });
3027         // If we've implicitly added *all* of the overloadable attrs to this
3028         // chain, emitting a "previous redecl" note is pointless.
3029         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3030       }
3031 
3032       if (DiagOld)
3033         Diag(DiagOld->getLocation(),
3034              diag::note_attribute_overloadable_prev_overload)
3035           << OldOvl;
3036 
3037       if (OldOvl)
3038         New->addAttr(OverloadableAttr::CreateImplicit(Context));
3039       else
3040         New->dropAttr<OverloadableAttr>();
3041     }
3042   }
3043 
3044   // If a function is first declared with a calling convention, but is later
3045   // declared or defined without one, all following decls assume the calling
3046   // convention of the first.
3047   //
3048   // It's OK if a function is first declared without a calling convention,
3049   // but is later declared or defined with the default calling convention.
3050   //
3051   // To test if either decl has an explicit calling convention, we look for
3052   // AttributedType sugar nodes on the type as written.  If they are missing or
3053   // were canonicalized away, we assume the calling convention was implicit.
3054   //
3055   // Note also that we DO NOT return at this point, because we still have
3056   // other tests to run.
3057   QualType OldQType = Context.getCanonicalType(Old->getType());
3058   QualType NewQType = Context.getCanonicalType(New->getType());
3059   const FunctionType *OldType = cast<FunctionType>(OldQType);
3060   const FunctionType *NewType = cast<FunctionType>(NewQType);
3061   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3062   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3063   bool RequiresAdjustment = false;
3064 
3065   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3066     FunctionDecl *First = Old->getFirstDecl();
3067     const FunctionType *FT =
3068         First->getType().getCanonicalType()->castAs<FunctionType>();
3069     FunctionType::ExtInfo FI = FT->getExtInfo();
3070     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3071     if (!NewCCExplicit) {
3072       // Inherit the CC from the previous declaration if it was specified
3073       // there but not here.
3074       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3075       RequiresAdjustment = true;
3076     } else {
3077       // Calling conventions aren't compatible, so complain.
3078       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3079       Diag(New->getLocation(), diag::err_cconv_change)
3080         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3081         << !FirstCCExplicit
3082         << (!FirstCCExplicit ? "" :
3083             FunctionType::getNameForCallConv(FI.getCC()));
3084 
3085       // Put the note on the first decl, since it is the one that matters.
3086       Diag(First->getLocation(), diag::note_previous_declaration);
3087       return true;
3088     }
3089   }
3090 
3091   // FIXME: diagnose the other way around?
3092   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3093     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3094     RequiresAdjustment = true;
3095   }
3096 
3097   // Merge regparm attribute.
3098   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3099       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3100     if (NewTypeInfo.getHasRegParm()) {
3101       Diag(New->getLocation(), diag::err_regparm_mismatch)
3102         << NewType->getRegParmType()
3103         << OldType->getRegParmType();
3104       Diag(OldLocation, diag::note_previous_declaration);
3105       return true;
3106     }
3107 
3108     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3109     RequiresAdjustment = true;
3110   }
3111 
3112   // Merge ns_returns_retained attribute.
3113   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3114     if (NewTypeInfo.getProducesResult()) {
3115       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3116           << "'ns_returns_retained'";
3117       Diag(OldLocation, diag::note_previous_declaration);
3118       return true;
3119     }
3120 
3121     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3122     RequiresAdjustment = true;
3123   }
3124 
3125   if (OldTypeInfo.getNoCallerSavedRegs() !=
3126       NewTypeInfo.getNoCallerSavedRegs()) {
3127     if (NewTypeInfo.getNoCallerSavedRegs()) {
3128       AnyX86NoCallerSavedRegistersAttr *Attr =
3129         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3130       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3131       Diag(OldLocation, diag::note_previous_declaration);
3132       return true;
3133     }
3134 
3135     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3136     RequiresAdjustment = true;
3137   }
3138 
3139   if (RequiresAdjustment) {
3140     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3141     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3142     New->setType(QualType(AdjustedType, 0));
3143     NewQType = Context.getCanonicalType(New->getType());
3144     NewType = cast<FunctionType>(NewQType);
3145   }
3146 
3147   // If this redeclaration makes the function inline, we may need to add it to
3148   // UndefinedButUsed.
3149   if (!Old->isInlined() && New->isInlined() &&
3150       !New->hasAttr<GNUInlineAttr>() &&
3151       !getLangOpts().GNUInline &&
3152       Old->isUsed(false) &&
3153       !Old->isDefined() && !New->isThisDeclarationADefinition())
3154     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3155                                            SourceLocation()));
3156 
3157   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3158   // about it.
3159   if (New->hasAttr<GNUInlineAttr>() &&
3160       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3161     UndefinedButUsed.erase(Old->getCanonicalDecl());
3162   }
3163 
3164   // If pass_object_size params don't match up perfectly, this isn't a valid
3165   // redeclaration.
3166   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3167       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3168     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3169         << New->getDeclName();
3170     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3171     return true;
3172   }
3173 
3174   if (getLangOpts().CPlusPlus) {
3175     // C++1z [over.load]p2
3176     //   Certain function declarations cannot be overloaded:
3177     //     -- Function declarations that differ only in the return type,
3178     //        the exception specification, or both cannot be overloaded.
3179 
3180     // Check the exception specifications match. This may recompute the type of
3181     // both Old and New if it resolved exception specifications, so grab the
3182     // types again after this. Because this updates the type, we do this before
3183     // any of the other checks below, which may update the "de facto" NewQType
3184     // but do not necessarily update the type of New.
3185     if (CheckEquivalentExceptionSpec(Old, New))
3186       return true;
3187     OldQType = Context.getCanonicalType(Old->getType());
3188     NewQType = Context.getCanonicalType(New->getType());
3189 
3190     // Go back to the type source info to compare the declared return types,
3191     // per C++1y [dcl.type.auto]p13:
3192     //   Redeclarations or specializations of a function or function template
3193     //   with a declared return type that uses a placeholder type shall also
3194     //   use that placeholder, not a deduced type.
3195     QualType OldDeclaredReturnType =
3196         (Old->getTypeSourceInfo()
3197              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3198              : OldType)->getReturnType();
3199     QualType NewDeclaredReturnType =
3200         (New->getTypeSourceInfo()
3201              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3202              : NewType)->getReturnType();
3203     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3204         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3205           New->isLocalExternDecl())) {
3206       QualType ResQT;
3207       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3208           OldDeclaredReturnType->isObjCObjectPointerType())
3209         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3210       if (ResQT.isNull()) {
3211         if (New->isCXXClassMember() && New->isOutOfLine())
3212           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3213               << New << New->getReturnTypeSourceRange();
3214         else
3215           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3216               << New->getReturnTypeSourceRange();
3217         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3218                                     << Old->getReturnTypeSourceRange();
3219         return true;
3220       }
3221       else
3222         NewQType = ResQT;
3223     }
3224 
3225     QualType OldReturnType = OldType->getReturnType();
3226     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3227     if (OldReturnType != NewReturnType) {
3228       // If this function has a deduced return type and has already been
3229       // defined, copy the deduced value from the old declaration.
3230       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3231       if (OldAT && OldAT->isDeduced()) {
3232         New->setType(
3233             SubstAutoType(New->getType(),
3234                           OldAT->isDependentType() ? Context.DependentTy
3235                                                    : OldAT->getDeducedType()));
3236         NewQType = Context.getCanonicalType(
3237             SubstAutoType(NewQType,
3238                           OldAT->isDependentType() ? Context.DependentTy
3239                                                    : OldAT->getDeducedType()));
3240       }
3241     }
3242 
3243     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3244     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3245     if (OldMethod && NewMethod) {
3246       // Preserve triviality.
3247       NewMethod->setTrivial(OldMethod->isTrivial());
3248 
3249       // MSVC allows explicit template specialization at class scope:
3250       // 2 CXXMethodDecls referring to the same function will be injected.
3251       // We don't want a redeclaration error.
3252       bool IsClassScopeExplicitSpecialization =
3253                               OldMethod->isFunctionTemplateSpecialization() &&
3254                               NewMethod->isFunctionTemplateSpecialization();
3255       bool isFriend = NewMethod->getFriendObjectKind();
3256 
3257       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3258           !IsClassScopeExplicitSpecialization) {
3259         //    -- Member function declarations with the same name and the
3260         //       same parameter types cannot be overloaded if any of them
3261         //       is a static member function declaration.
3262         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3263           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3264           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3265           return true;
3266         }
3267 
3268         // C++ [class.mem]p1:
3269         //   [...] A member shall not be declared twice in the
3270         //   member-specification, except that a nested class or member
3271         //   class template can be declared and then later defined.
3272         if (!inTemplateInstantiation()) {
3273           unsigned NewDiag;
3274           if (isa<CXXConstructorDecl>(OldMethod))
3275             NewDiag = diag::err_constructor_redeclared;
3276           else if (isa<CXXDestructorDecl>(NewMethod))
3277             NewDiag = diag::err_destructor_redeclared;
3278           else if (isa<CXXConversionDecl>(NewMethod))
3279             NewDiag = diag::err_conv_function_redeclared;
3280           else
3281             NewDiag = diag::err_member_redeclared;
3282 
3283           Diag(New->getLocation(), NewDiag);
3284         } else {
3285           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3286             << New << New->getType();
3287         }
3288         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3289         return true;
3290 
3291       // Complain if this is an explicit declaration of a special
3292       // member that was initially declared implicitly.
3293       //
3294       // As an exception, it's okay to befriend such methods in order
3295       // to permit the implicit constructor/destructor/operator calls.
3296       } else if (OldMethod->isImplicit()) {
3297         if (isFriend) {
3298           NewMethod->setImplicit();
3299         } else {
3300           Diag(NewMethod->getLocation(),
3301                diag::err_definition_of_implicitly_declared_member)
3302             << New << getSpecialMember(OldMethod);
3303           return true;
3304         }
3305       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3306         Diag(NewMethod->getLocation(),
3307              diag::err_definition_of_explicitly_defaulted_member)
3308           << getSpecialMember(OldMethod);
3309         return true;
3310       }
3311     }
3312 
3313     // C++11 [dcl.attr.noreturn]p1:
3314     //   The first declaration of a function shall specify the noreturn
3315     //   attribute if any declaration of that function specifies the noreturn
3316     //   attribute.
3317     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3318     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3319       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3320       Diag(Old->getFirstDecl()->getLocation(),
3321            diag::note_noreturn_missing_first_decl);
3322     }
3323 
3324     // C++11 [dcl.attr.depend]p2:
3325     //   The first declaration of a function shall specify the
3326     //   carries_dependency attribute for its declarator-id if any declaration
3327     //   of the function specifies the carries_dependency attribute.
3328     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3329     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3330       Diag(CDA->getLocation(),
3331            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3332       Diag(Old->getFirstDecl()->getLocation(),
3333            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3334     }
3335 
3336     // (C++98 8.3.5p3):
3337     //   All declarations for a function shall agree exactly in both the
3338     //   return type and the parameter-type-list.
3339     // We also want to respect all the extended bits except noreturn.
3340 
3341     // noreturn should now match unless the old type info didn't have it.
3342     QualType OldQTypeForComparison = OldQType;
3343     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3344       auto *OldType = OldQType->castAs<FunctionProtoType>();
3345       const FunctionType *OldTypeForComparison
3346         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3347       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3348       assert(OldQTypeForComparison.isCanonical());
3349     }
3350 
3351     if (haveIncompatibleLanguageLinkages(Old, New)) {
3352       // As a special case, retain the language linkage from previous
3353       // declarations of a friend function as an extension.
3354       //
3355       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3356       // and is useful because there's otherwise no way to specify language
3357       // linkage within class scope.
3358       //
3359       // Check cautiously as the friend object kind isn't yet complete.
3360       if (New->getFriendObjectKind() != Decl::FOK_None) {
3361         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3362         Diag(OldLocation, PrevDiag);
3363       } else {
3364         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3365         Diag(OldLocation, PrevDiag);
3366         return true;
3367       }
3368     }
3369 
3370     if (OldQTypeForComparison == NewQType)
3371       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3372 
3373     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3374         New->isLocalExternDecl()) {
3375       // It's OK if we couldn't merge types for a local function declaraton
3376       // if either the old or new type is dependent. We'll merge the types
3377       // when we instantiate the function.
3378       return false;
3379     }
3380 
3381     // Fall through for conflicting redeclarations and redefinitions.
3382   }
3383 
3384   // C: Function types need to be compatible, not identical. This handles
3385   // duplicate function decls like "void f(int); void f(enum X);" properly.
3386   if (!getLangOpts().CPlusPlus &&
3387       Context.typesAreCompatible(OldQType, NewQType)) {
3388     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3389     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3390     const FunctionProtoType *OldProto = nullptr;
3391     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3392         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3393       // The old declaration provided a function prototype, but the
3394       // new declaration does not. Merge in the prototype.
3395       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3396       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3397       NewQType =
3398           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3399                                   OldProto->getExtProtoInfo());
3400       New->setType(NewQType);
3401       New->setHasInheritedPrototype();
3402 
3403       // Synthesize parameters with the same types.
3404       SmallVector<ParmVarDecl*, 16> Params;
3405       for (const auto &ParamType : OldProto->param_types()) {
3406         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3407                                                  SourceLocation(), nullptr,
3408                                                  ParamType, /*TInfo=*/nullptr,
3409                                                  SC_None, nullptr);
3410         Param->setScopeInfo(0, Params.size());
3411         Param->setImplicit();
3412         Params.push_back(Param);
3413       }
3414 
3415       New->setParams(Params);
3416     }
3417 
3418     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3419   }
3420 
3421   // GNU C permits a K&R definition to follow a prototype declaration
3422   // if the declared types of the parameters in the K&R definition
3423   // match the types in the prototype declaration, even when the
3424   // promoted types of the parameters from the K&R definition differ
3425   // from the types in the prototype. GCC then keeps the types from
3426   // the prototype.
3427   //
3428   // If a variadic prototype is followed by a non-variadic K&R definition,
3429   // the K&R definition becomes variadic.  This is sort of an edge case, but
3430   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3431   // C99 6.9.1p8.
3432   if (!getLangOpts().CPlusPlus &&
3433       Old->hasPrototype() && !New->hasPrototype() &&
3434       New->getType()->getAs<FunctionProtoType>() &&
3435       Old->getNumParams() == New->getNumParams()) {
3436     SmallVector<QualType, 16> ArgTypes;
3437     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3438     const FunctionProtoType *OldProto
3439       = Old->getType()->getAs<FunctionProtoType>();
3440     const FunctionProtoType *NewProto
3441       = New->getType()->getAs<FunctionProtoType>();
3442 
3443     // Determine whether this is the GNU C extension.
3444     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3445                                                NewProto->getReturnType());
3446     bool LooseCompatible = !MergedReturn.isNull();
3447     for (unsigned Idx = 0, End = Old->getNumParams();
3448          LooseCompatible && Idx != End; ++Idx) {
3449       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3450       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3451       if (Context.typesAreCompatible(OldParm->getType(),
3452                                      NewProto->getParamType(Idx))) {
3453         ArgTypes.push_back(NewParm->getType());
3454       } else if (Context.typesAreCompatible(OldParm->getType(),
3455                                             NewParm->getType(),
3456                                             /*CompareUnqualified=*/true)) {
3457         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3458                                            NewProto->getParamType(Idx) };
3459         Warnings.push_back(Warn);
3460         ArgTypes.push_back(NewParm->getType());
3461       } else
3462         LooseCompatible = false;
3463     }
3464 
3465     if (LooseCompatible) {
3466       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3467         Diag(Warnings[Warn].NewParm->getLocation(),
3468              diag::ext_param_promoted_not_compatible_with_prototype)
3469           << Warnings[Warn].PromotedType
3470           << Warnings[Warn].OldParm->getType();
3471         if (Warnings[Warn].OldParm->getLocation().isValid())
3472           Diag(Warnings[Warn].OldParm->getLocation(),
3473                diag::note_previous_declaration);
3474       }
3475 
3476       if (MergeTypeWithOld)
3477         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3478                                              OldProto->getExtProtoInfo()));
3479       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3480     }
3481 
3482     // Fall through to diagnose conflicting types.
3483   }
3484 
3485   // A function that has already been declared has been redeclared or
3486   // defined with a different type; show an appropriate diagnostic.
3487 
3488   // If the previous declaration was an implicitly-generated builtin
3489   // declaration, then at the very least we should use a specialized note.
3490   unsigned BuiltinID;
3491   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3492     // If it's actually a library-defined builtin function like 'malloc'
3493     // or 'printf', just warn about the incompatible redeclaration.
3494     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3495       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3496       Diag(OldLocation, diag::note_previous_builtin_declaration)
3497         << Old << Old->getType();
3498 
3499       // If this is a global redeclaration, just forget hereafter
3500       // about the "builtin-ness" of the function.
3501       //
3502       // Doing this for local extern declarations is problematic.  If
3503       // the builtin declaration remains visible, a second invalid
3504       // local declaration will produce a hard error; if it doesn't
3505       // remain visible, a single bogus local redeclaration (which is
3506       // actually only a warning) could break all the downstream code.
3507       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3508         New->getIdentifier()->revertBuiltin();
3509 
3510       return false;
3511     }
3512 
3513     PrevDiag = diag::note_previous_builtin_declaration;
3514   }
3515 
3516   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3517   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3518   return true;
3519 }
3520 
3521 /// \brief Completes the merge of two function declarations that are
3522 /// known to be compatible.
3523 ///
3524 /// This routine handles the merging of attributes and other
3525 /// properties of function declarations from the old declaration to
3526 /// the new declaration, once we know that New is in fact a
3527 /// redeclaration of Old.
3528 ///
3529 /// \returns false
3530 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3531                                         Scope *S, bool MergeTypeWithOld) {
3532   // Merge the attributes
3533   mergeDeclAttributes(New, Old);
3534 
3535   // Merge "pure" flag.
3536   if (Old->isPure())
3537     New->setPure();
3538 
3539   // Merge "used" flag.
3540   if (Old->getMostRecentDecl()->isUsed(false))
3541     New->setIsUsed();
3542 
3543   // Merge attributes from the parameters.  These can mismatch with K&R
3544   // declarations.
3545   if (New->getNumParams() == Old->getNumParams())
3546       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3547         ParmVarDecl *NewParam = New->getParamDecl(i);
3548         ParmVarDecl *OldParam = Old->getParamDecl(i);
3549         mergeParamDeclAttributes(NewParam, OldParam, *this);
3550         mergeParamDeclTypes(NewParam, OldParam, *this);
3551       }
3552 
3553   if (getLangOpts().CPlusPlus)
3554     return MergeCXXFunctionDecl(New, Old, S);
3555 
3556   // Merge the function types so the we get the composite types for the return
3557   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3558   // was visible.
3559   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3560   if (!Merged.isNull() && MergeTypeWithOld)
3561     New->setType(Merged);
3562 
3563   return false;
3564 }
3565 
3566 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3567                                 ObjCMethodDecl *oldMethod) {
3568   // Merge the attributes, including deprecated/unavailable
3569   AvailabilityMergeKind MergeKind =
3570     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3571       ? AMK_ProtocolImplementation
3572       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3573                                                        : AMK_Override;
3574 
3575   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3576 
3577   // Merge attributes from the parameters.
3578   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3579                                        oe = oldMethod->param_end();
3580   for (ObjCMethodDecl::param_iterator
3581          ni = newMethod->param_begin(), ne = newMethod->param_end();
3582        ni != ne && oi != oe; ++ni, ++oi)
3583     mergeParamDeclAttributes(*ni, *oi, *this);
3584 }
3585 
3586 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3587   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3588 
3589   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3590          ? diag::err_redefinition_different_type
3591          : diag::err_redeclaration_different_type)
3592     << New->getDeclName() << New->getType() << Old->getType();
3593 
3594   diag::kind PrevDiag;
3595   SourceLocation OldLocation;
3596   std::tie(PrevDiag, OldLocation)
3597     = getNoteDiagForInvalidRedeclaration(Old, New);
3598   S.Diag(OldLocation, PrevDiag);
3599   New->setInvalidDecl();
3600 }
3601 
3602 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3603 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3604 /// emitting diagnostics as appropriate.
3605 ///
3606 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3607 /// to here in AddInitializerToDecl. We can't check them before the initializer
3608 /// is attached.
3609 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3610                              bool MergeTypeWithOld) {
3611   if (New->isInvalidDecl() || Old->isInvalidDecl())
3612     return;
3613 
3614   QualType MergedT;
3615   if (getLangOpts().CPlusPlus) {
3616     if (New->getType()->isUndeducedType()) {
3617       // We don't know what the new type is until the initializer is attached.
3618       return;
3619     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3620       // These could still be something that needs exception specs checked.
3621       return MergeVarDeclExceptionSpecs(New, Old);
3622     }
3623     // C++ [basic.link]p10:
3624     //   [...] the types specified by all declarations referring to a given
3625     //   object or function shall be identical, except that declarations for an
3626     //   array object can specify array types that differ by the presence or
3627     //   absence of a major array bound (8.3.4).
3628     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3629       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3630       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3631 
3632       // We are merging a variable declaration New into Old. If it has an array
3633       // bound, and that bound differs from Old's bound, we should diagnose the
3634       // mismatch.
3635       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3636         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3637              PrevVD = PrevVD->getPreviousDecl()) {
3638           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3639           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3640             continue;
3641 
3642           if (!Context.hasSameType(NewArray, PrevVDTy))
3643             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3644         }
3645       }
3646 
3647       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3648         if (Context.hasSameType(OldArray->getElementType(),
3649                                 NewArray->getElementType()))
3650           MergedT = New->getType();
3651       }
3652       // FIXME: Check visibility. New is hidden but has a complete type. If New
3653       // has no array bound, it should not inherit one from Old, if Old is not
3654       // visible.
3655       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3656         if (Context.hasSameType(OldArray->getElementType(),
3657                                 NewArray->getElementType()))
3658           MergedT = Old->getType();
3659       }
3660     }
3661     else if (New->getType()->isObjCObjectPointerType() &&
3662                Old->getType()->isObjCObjectPointerType()) {
3663       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3664                                               Old->getType());
3665     }
3666   } else {
3667     // C 6.2.7p2:
3668     //   All declarations that refer to the same object or function shall have
3669     //   compatible type.
3670     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3671   }
3672   if (MergedT.isNull()) {
3673     // It's OK if we couldn't merge types if either type is dependent, for a
3674     // block-scope variable. In other cases (static data members of class
3675     // templates, variable templates, ...), we require the types to be
3676     // equivalent.
3677     // FIXME: The C++ standard doesn't say anything about this.
3678     if ((New->getType()->isDependentType() ||
3679          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3680       // If the old type was dependent, we can't merge with it, so the new type
3681       // becomes dependent for now. We'll reproduce the original type when we
3682       // instantiate the TypeSourceInfo for the variable.
3683       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3684         New->setType(Context.DependentTy);
3685       return;
3686     }
3687     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3688   }
3689 
3690   // Don't actually update the type on the new declaration if the old
3691   // declaration was an extern declaration in a different scope.
3692   if (MergeTypeWithOld)
3693     New->setType(MergedT);
3694 }
3695 
3696 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3697                                   LookupResult &Previous) {
3698   // C11 6.2.7p4:
3699   //   For an identifier with internal or external linkage declared
3700   //   in a scope in which a prior declaration of that identifier is
3701   //   visible, if the prior declaration specifies internal or
3702   //   external linkage, the type of the identifier at the later
3703   //   declaration becomes the composite type.
3704   //
3705   // If the variable isn't visible, we do not merge with its type.
3706   if (Previous.isShadowed())
3707     return false;
3708 
3709   if (S.getLangOpts().CPlusPlus) {
3710     // C++11 [dcl.array]p3:
3711     //   If there is a preceding declaration of the entity in the same
3712     //   scope in which the bound was specified, an omitted array bound
3713     //   is taken to be the same as in that earlier declaration.
3714     return NewVD->isPreviousDeclInSameBlockScope() ||
3715            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3716             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3717   } else {
3718     // If the old declaration was function-local, don't merge with its
3719     // type unless we're in the same function.
3720     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3721            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3722   }
3723 }
3724 
3725 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3726 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3727 /// situation, merging decls or emitting diagnostics as appropriate.
3728 ///
3729 /// Tentative definition rules (C99 6.9.2p2) are checked by
3730 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3731 /// definitions here, since the initializer hasn't been attached.
3732 ///
3733 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3734   // If the new decl is already invalid, don't do any other checking.
3735   if (New->isInvalidDecl())
3736     return;
3737 
3738   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3739     return;
3740 
3741   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3742 
3743   // Verify the old decl was also a variable or variable template.
3744   VarDecl *Old = nullptr;
3745   VarTemplateDecl *OldTemplate = nullptr;
3746   if (Previous.isSingleResult()) {
3747     if (NewTemplate) {
3748       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3749       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3750 
3751       if (auto *Shadow =
3752               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3753         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3754           return New->setInvalidDecl();
3755     } else {
3756       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3757 
3758       if (auto *Shadow =
3759               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3760         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3761           return New->setInvalidDecl();
3762     }
3763   }
3764   if (!Old) {
3765     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3766         << New->getDeclName();
3767     notePreviousDefinition(Previous.getRepresentativeDecl(),
3768                            New->getLocation());
3769     return New->setInvalidDecl();
3770   }
3771 
3772   // Ensure the template parameters are compatible.
3773   if (NewTemplate &&
3774       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3775                                       OldTemplate->getTemplateParameters(),
3776                                       /*Complain=*/true, TPL_TemplateMatch))
3777     return New->setInvalidDecl();
3778 
3779   // C++ [class.mem]p1:
3780   //   A member shall not be declared twice in the member-specification [...]
3781   //
3782   // Here, we need only consider static data members.
3783   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3784     Diag(New->getLocation(), diag::err_duplicate_member)
3785       << New->getIdentifier();
3786     Diag(Old->getLocation(), diag::note_previous_declaration);
3787     New->setInvalidDecl();
3788   }
3789 
3790   mergeDeclAttributes(New, Old);
3791   // Warn if an already-declared variable is made a weak_import in a subsequent
3792   // declaration
3793   if (New->hasAttr<WeakImportAttr>() &&
3794       Old->getStorageClass() == SC_None &&
3795       !Old->hasAttr<WeakImportAttr>()) {
3796     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3797     notePreviousDefinition(Old, New->getLocation());
3798     // Remove weak_import attribute on new declaration.
3799     New->dropAttr<WeakImportAttr>();
3800   }
3801 
3802   if (New->hasAttr<InternalLinkageAttr>() &&
3803       !Old->hasAttr<InternalLinkageAttr>()) {
3804     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3805         << New->getDeclName();
3806     notePreviousDefinition(Old, New->getLocation());
3807     New->dropAttr<InternalLinkageAttr>();
3808   }
3809 
3810   // Merge the types.
3811   VarDecl *MostRecent = Old->getMostRecentDecl();
3812   if (MostRecent != Old) {
3813     MergeVarDeclTypes(New, MostRecent,
3814                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3815     if (New->isInvalidDecl())
3816       return;
3817   }
3818 
3819   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3820   if (New->isInvalidDecl())
3821     return;
3822 
3823   diag::kind PrevDiag;
3824   SourceLocation OldLocation;
3825   std::tie(PrevDiag, OldLocation) =
3826       getNoteDiagForInvalidRedeclaration(Old, New);
3827 
3828   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3829   if (New->getStorageClass() == SC_Static &&
3830       !New->isStaticDataMember() &&
3831       Old->hasExternalFormalLinkage()) {
3832     if (getLangOpts().MicrosoftExt) {
3833       Diag(New->getLocation(), diag::ext_static_non_static)
3834           << New->getDeclName();
3835       Diag(OldLocation, PrevDiag);
3836     } else {
3837       Diag(New->getLocation(), diag::err_static_non_static)
3838           << New->getDeclName();
3839       Diag(OldLocation, PrevDiag);
3840       return New->setInvalidDecl();
3841     }
3842   }
3843   // C99 6.2.2p4:
3844   //   For an identifier declared with the storage-class specifier
3845   //   extern in a scope in which a prior declaration of that
3846   //   identifier is visible,23) if the prior declaration specifies
3847   //   internal or external linkage, the linkage of the identifier at
3848   //   the later declaration is the same as the linkage specified at
3849   //   the prior declaration. If no prior declaration is visible, or
3850   //   if the prior declaration specifies no linkage, then the
3851   //   identifier has external linkage.
3852   if (New->hasExternalStorage() && Old->hasLinkage())
3853     /* Okay */;
3854   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3855            !New->isStaticDataMember() &&
3856            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3857     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3858     Diag(OldLocation, PrevDiag);
3859     return New->setInvalidDecl();
3860   }
3861 
3862   // Check if extern is followed by non-extern and vice-versa.
3863   if (New->hasExternalStorage() &&
3864       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3865     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3866     Diag(OldLocation, PrevDiag);
3867     return New->setInvalidDecl();
3868   }
3869   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3870       !New->hasExternalStorage()) {
3871     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3872     Diag(OldLocation, PrevDiag);
3873     return New->setInvalidDecl();
3874   }
3875 
3876   if (CheckRedeclarationModuleOwnership(New, Old))
3877     return;
3878 
3879   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3880 
3881   // FIXME: The test for external storage here seems wrong? We still
3882   // need to check for mismatches.
3883   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3884       // Don't complain about out-of-line definitions of static members.
3885       !(Old->getLexicalDeclContext()->isRecord() &&
3886         !New->getLexicalDeclContext()->isRecord())) {
3887     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3888     Diag(OldLocation, PrevDiag);
3889     return New->setInvalidDecl();
3890   }
3891 
3892   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3893     if (VarDecl *Def = Old->getDefinition()) {
3894       // C++1z [dcl.fcn.spec]p4:
3895       //   If the definition of a variable appears in a translation unit before
3896       //   its first declaration as inline, the program is ill-formed.
3897       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3898       Diag(Def->getLocation(), diag::note_previous_definition);
3899     }
3900   }
3901 
3902   // If this redeclaration makes the variable inline, we may need to add it to
3903   // UndefinedButUsed.
3904   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3905       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3906     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3907                                            SourceLocation()));
3908 
3909   if (New->getTLSKind() != Old->getTLSKind()) {
3910     if (!Old->getTLSKind()) {
3911       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3912       Diag(OldLocation, PrevDiag);
3913     } else if (!New->getTLSKind()) {
3914       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3915       Diag(OldLocation, PrevDiag);
3916     } else {
3917       // Do not allow redeclaration to change the variable between requiring
3918       // static and dynamic initialization.
3919       // FIXME: GCC allows this, but uses the TLS keyword on the first
3920       // declaration to determine the kind. Do we need to be compatible here?
3921       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3922         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3923       Diag(OldLocation, PrevDiag);
3924     }
3925   }
3926 
3927   // C++ doesn't have tentative definitions, so go right ahead and check here.
3928   if (getLangOpts().CPlusPlus &&
3929       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3930     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3931         Old->getCanonicalDecl()->isConstexpr()) {
3932       // This definition won't be a definition any more once it's been merged.
3933       Diag(New->getLocation(),
3934            diag::warn_deprecated_redundant_constexpr_static_def);
3935     } else if (VarDecl *Def = Old->getDefinition()) {
3936       if (checkVarDeclRedefinition(Def, New))
3937         return;
3938     }
3939   }
3940 
3941   if (haveIncompatibleLanguageLinkages(Old, New)) {
3942     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3943     Diag(OldLocation, PrevDiag);
3944     New->setInvalidDecl();
3945     return;
3946   }
3947 
3948   // Merge "used" flag.
3949   if (Old->getMostRecentDecl()->isUsed(false))
3950     New->setIsUsed();
3951 
3952   // Keep a chain of previous declarations.
3953   New->setPreviousDecl(Old);
3954   if (NewTemplate)
3955     NewTemplate->setPreviousDecl(OldTemplate);
3956 
3957   // Inherit access appropriately.
3958   New->setAccess(Old->getAccess());
3959   if (NewTemplate)
3960     NewTemplate->setAccess(New->getAccess());
3961 
3962   if (Old->isInline())
3963     New->setImplicitlyInline();
3964 }
3965 
3966 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3967   SourceManager &SrcMgr = getSourceManager();
3968   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3969   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3970   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3971   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3972   auto &HSI = PP.getHeaderSearchInfo();
3973   StringRef HdrFilename =
3974       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3975 
3976   auto noteFromModuleOrInclude = [&](Module *Mod,
3977                                      SourceLocation IncLoc) -> bool {
3978     // Redefinition errors with modules are common with non modular mapped
3979     // headers, example: a non-modular header H in module A that also gets
3980     // included directly in a TU. Pointing twice to the same header/definition
3981     // is confusing, try to get better diagnostics when modules is on.
3982     if (IncLoc.isValid()) {
3983       if (Mod) {
3984         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3985             << HdrFilename.str() << Mod->getFullModuleName();
3986         if (!Mod->DefinitionLoc.isInvalid())
3987           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3988               << Mod->getFullModuleName();
3989       } else {
3990         Diag(IncLoc, diag::note_redefinition_include_same_file)
3991             << HdrFilename.str();
3992       }
3993       return true;
3994     }
3995 
3996     return false;
3997   };
3998 
3999   // Is it the same file and same offset? Provide more information on why
4000   // this leads to a redefinition error.
4001   bool EmittedDiag = false;
4002   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4003     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4004     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4005     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4006     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4007 
4008     // If the header has no guards, emit a note suggesting one.
4009     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4010       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4011 
4012     if (EmittedDiag)
4013       return;
4014   }
4015 
4016   // Redefinition coming from different files or couldn't do better above.
4017   Diag(Old->getLocation(), diag::note_previous_definition);
4018 }
4019 
4020 /// We've just determined that \p Old and \p New both appear to be definitions
4021 /// of the same variable. Either diagnose or fix the problem.
4022 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4023   if (!hasVisibleDefinition(Old) &&
4024       (New->getFormalLinkage() == InternalLinkage ||
4025        New->isInline() ||
4026        New->getDescribedVarTemplate() ||
4027        New->getNumTemplateParameterLists() ||
4028        New->getDeclContext()->isDependentContext())) {
4029     // The previous definition is hidden, and multiple definitions are
4030     // permitted (in separate TUs). Demote this to a declaration.
4031     New->demoteThisDefinitionToDeclaration();
4032 
4033     // Make the canonical definition visible.
4034     if (auto *OldTD = Old->getDescribedVarTemplate())
4035       makeMergedDefinitionVisible(OldTD);
4036     makeMergedDefinitionVisible(Old);
4037     return false;
4038   } else {
4039     Diag(New->getLocation(), diag::err_redefinition) << New;
4040     notePreviousDefinition(Old, New->getLocation());
4041     New->setInvalidDecl();
4042     return true;
4043   }
4044 }
4045 
4046 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4047 /// no declarator (e.g. "struct foo;") is parsed.
4048 Decl *
4049 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4050                                  RecordDecl *&AnonRecord) {
4051   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4052                                     AnonRecord);
4053 }
4054 
4055 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4056 // disambiguate entities defined in different scopes.
4057 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4058 // compatibility.
4059 // We will pick our mangling number depending on which version of MSVC is being
4060 // targeted.
4061 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4062   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4063              ? S->getMSCurManglingNumber()
4064              : S->getMSLastManglingNumber();
4065 }
4066 
4067 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4068   if (!Context.getLangOpts().CPlusPlus)
4069     return;
4070 
4071   if (isa<CXXRecordDecl>(Tag->getParent())) {
4072     // If this tag is the direct child of a class, number it if
4073     // it is anonymous.
4074     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4075       return;
4076     MangleNumberingContext &MCtx =
4077         Context.getManglingNumberContext(Tag->getParent());
4078     Context.setManglingNumber(
4079         Tag, MCtx.getManglingNumber(
4080                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4081     return;
4082   }
4083 
4084   // If this tag isn't a direct child of a class, number it if it is local.
4085   Decl *ManglingContextDecl;
4086   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4087           Tag->getDeclContext(), ManglingContextDecl)) {
4088     Context.setManglingNumber(
4089         Tag, MCtx->getManglingNumber(
4090                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4091   }
4092 }
4093 
4094 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4095                                         TypedefNameDecl *NewTD) {
4096   if (TagFromDeclSpec->isInvalidDecl())
4097     return;
4098 
4099   // Do nothing if the tag already has a name for linkage purposes.
4100   if (TagFromDeclSpec->hasNameForLinkage())
4101     return;
4102 
4103   // A well-formed anonymous tag must always be a TUK_Definition.
4104   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4105 
4106   // The type must match the tag exactly;  no qualifiers allowed.
4107   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4108                            Context.getTagDeclType(TagFromDeclSpec))) {
4109     if (getLangOpts().CPlusPlus)
4110       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4111     return;
4112   }
4113 
4114   // If we've already computed linkage for the anonymous tag, then
4115   // adding a typedef name for the anonymous decl can change that
4116   // linkage, which might be a serious problem.  Diagnose this as
4117   // unsupported and ignore the typedef name.  TODO: we should
4118   // pursue this as a language defect and establish a formal rule
4119   // for how to handle it.
4120   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4121     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4122 
4123     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4124     tagLoc = getLocForEndOfToken(tagLoc);
4125 
4126     llvm::SmallString<40> textToInsert;
4127     textToInsert += ' ';
4128     textToInsert += NewTD->getIdentifier()->getName();
4129     Diag(tagLoc, diag::note_typedef_changes_linkage)
4130         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4131     return;
4132   }
4133 
4134   // Otherwise, set this is the anon-decl typedef for the tag.
4135   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4136 }
4137 
4138 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4139   switch (T) {
4140   case DeclSpec::TST_class:
4141     return 0;
4142   case DeclSpec::TST_struct:
4143     return 1;
4144   case DeclSpec::TST_interface:
4145     return 2;
4146   case DeclSpec::TST_union:
4147     return 3;
4148   case DeclSpec::TST_enum:
4149     return 4;
4150   default:
4151     llvm_unreachable("unexpected type specifier");
4152   }
4153 }
4154 
4155 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4156 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4157 /// parameters to cope with template friend declarations.
4158 Decl *
4159 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4160                                  MultiTemplateParamsArg TemplateParams,
4161                                  bool IsExplicitInstantiation,
4162                                  RecordDecl *&AnonRecord) {
4163   Decl *TagD = nullptr;
4164   TagDecl *Tag = nullptr;
4165   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4166       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4167       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4168       DS.getTypeSpecType() == DeclSpec::TST_union ||
4169       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4170     TagD = DS.getRepAsDecl();
4171 
4172     if (!TagD) // We probably had an error
4173       return nullptr;
4174 
4175     // Note that the above type specs guarantee that the
4176     // type rep is a Decl, whereas in many of the others
4177     // it's a Type.
4178     if (isa<TagDecl>(TagD))
4179       Tag = cast<TagDecl>(TagD);
4180     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4181       Tag = CTD->getTemplatedDecl();
4182   }
4183 
4184   if (Tag) {
4185     handleTagNumbering(Tag, S);
4186     Tag->setFreeStanding();
4187     if (Tag->isInvalidDecl())
4188       return Tag;
4189   }
4190 
4191   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4192     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4193     // or incomplete types shall not be restrict-qualified."
4194     if (TypeQuals & DeclSpec::TQ_restrict)
4195       Diag(DS.getRestrictSpecLoc(),
4196            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4197            << DS.getSourceRange();
4198   }
4199 
4200   if (DS.isInlineSpecified())
4201     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4202         << getLangOpts().CPlusPlus1z;
4203 
4204   if (DS.isConstexprSpecified()) {
4205     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4206     // and definitions of functions and variables.
4207     if (Tag)
4208       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4209           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4210     else
4211       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4212     // Don't emit warnings after this error.
4213     return TagD;
4214   }
4215 
4216   if (DS.isConceptSpecified()) {
4217     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4218     // either a function concept and its definition or a variable concept and
4219     // its initializer.
4220     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4221     return TagD;
4222   }
4223 
4224   DiagnoseFunctionSpecifiers(DS);
4225 
4226   if (DS.isFriendSpecified()) {
4227     // If we're dealing with a decl but not a TagDecl, assume that
4228     // whatever routines created it handled the friendship aspect.
4229     if (TagD && !Tag)
4230       return nullptr;
4231     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4232   }
4233 
4234   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4235   bool IsExplicitSpecialization =
4236     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4237   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4238       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4239       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4240     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4241     // nested-name-specifier unless it is an explicit instantiation
4242     // or an explicit specialization.
4243     //
4244     // FIXME: We allow class template partial specializations here too, per the
4245     // obvious intent of DR1819.
4246     //
4247     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4248     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4249         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4250     return nullptr;
4251   }
4252 
4253   // Track whether this decl-specifier declares anything.
4254   bool DeclaresAnything = true;
4255 
4256   // Handle anonymous struct definitions.
4257   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4258     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4259         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4260       if (getLangOpts().CPlusPlus ||
4261           Record->getDeclContext()->isRecord()) {
4262         // If CurContext is a DeclContext that can contain statements,
4263         // RecursiveASTVisitor won't visit the decls that
4264         // BuildAnonymousStructOrUnion() will put into CurContext.
4265         // Also store them here so that they can be part of the
4266         // DeclStmt that gets created in this case.
4267         // FIXME: Also return the IndirectFieldDecls created by
4268         // BuildAnonymousStructOr union, for the same reason?
4269         if (CurContext->isFunctionOrMethod())
4270           AnonRecord = Record;
4271         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4272                                            Context.getPrintingPolicy());
4273       }
4274 
4275       DeclaresAnything = false;
4276     }
4277   }
4278 
4279   // C11 6.7.2.1p2:
4280   //   A struct-declaration that does not declare an anonymous structure or
4281   //   anonymous union shall contain a struct-declarator-list.
4282   //
4283   // This rule also existed in C89 and C99; the grammar for struct-declaration
4284   // did not permit a struct-declaration without a struct-declarator-list.
4285   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4286       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4287     // Check for Microsoft C extension: anonymous struct/union member.
4288     // Handle 2 kinds of anonymous struct/union:
4289     //   struct STRUCT;
4290     //   union UNION;
4291     // and
4292     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4293     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4294     if ((Tag && Tag->getDeclName()) ||
4295         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4296       RecordDecl *Record = nullptr;
4297       if (Tag)
4298         Record = dyn_cast<RecordDecl>(Tag);
4299       else if (const RecordType *RT =
4300                    DS.getRepAsType().get()->getAsStructureType())
4301         Record = RT->getDecl();
4302       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4303         Record = UT->getDecl();
4304 
4305       if (Record && getLangOpts().MicrosoftExt) {
4306         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4307           << Record->isUnion() << DS.getSourceRange();
4308         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4309       }
4310 
4311       DeclaresAnything = false;
4312     }
4313   }
4314 
4315   // Skip all the checks below if we have a type error.
4316   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4317       (TagD && TagD->isInvalidDecl()))
4318     return TagD;
4319 
4320   if (getLangOpts().CPlusPlus &&
4321       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4322     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4323       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4324           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4325         DeclaresAnything = false;
4326 
4327   if (!DS.isMissingDeclaratorOk()) {
4328     // Customize diagnostic for a typedef missing a name.
4329     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4330       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4331         << DS.getSourceRange();
4332     else
4333       DeclaresAnything = false;
4334   }
4335 
4336   if (DS.isModulePrivateSpecified() &&
4337       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4338     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4339       << Tag->getTagKind()
4340       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4341 
4342   ActOnDocumentableDecl(TagD);
4343 
4344   // C 6.7/2:
4345   //   A declaration [...] shall declare at least a declarator [...], a tag,
4346   //   or the members of an enumeration.
4347   // C++ [dcl.dcl]p3:
4348   //   [If there are no declarators], and except for the declaration of an
4349   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4350   //   names into the program, or shall redeclare a name introduced by a
4351   //   previous declaration.
4352   if (!DeclaresAnything) {
4353     // In C, we allow this as a (popular) extension / bug. Don't bother
4354     // producing further diagnostics for redundant qualifiers after this.
4355     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4356     return TagD;
4357   }
4358 
4359   // C++ [dcl.stc]p1:
4360   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4361   //   init-declarator-list of the declaration shall not be empty.
4362   // C++ [dcl.fct.spec]p1:
4363   //   If a cv-qualifier appears in a decl-specifier-seq, the
4364   //   init-declarator-list of the declaration shall not be empty.
4365   //
4366   // Spurious qualifiers here appear to be valid in C.
4367   unsigned DiagID = diag::warn_standalone_specifier;
4368   if (getLangOpts().CPlusPlus)
4369     DiagID = diag::ext_standalone_specifier;
4370 
4371   // Note that a linkage-specification sets a storage class, but
4372   // 'extern "C" struct foo;' is actually valid and not theoretically
4373   // useless.
4374   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4375     if (SCS == DeclSpec::SCS_mutable)
4376       // Since mutable is not a viable storage class specifier in C, there is
4377       // no reason to treat it as an extension. Instead, diagnose as an error.
4378       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4379     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4380       Diag(DS.getStorageClassSpecLoc(), DiagID)
4381         << DeclSpec::getSpecifierName(SCS);
4382   }
4383 
4384   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4385     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4386       << DeclSpec::getSpecifierName(TSCS);
4387   if (DS.getTypeQualifiers()) {
4388     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4389       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4390     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4391       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4392     // Restrict is covered above.
4393     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4394       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4395     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4396       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4397   }
4398 
4399   // Warn about ignored type attributes, for example:
4400   // __attribute__((aligned)) struct A;
4401   // Attributes should be placed after tag to apply to type declaration.
4402   if (!DS.getAttributes().empty()) {
4403     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4404     if (TypeSpecType == DeclSpec::TST_class ||
4405         TypeSpecType == DeclSpec::TST_struct ||
4406         TypeSpecType == DeclSpec::TST_interface ||
4407         TypeSpecType == DeclSpec::TST_union ||
4408         TypeSpecType == DeclSpec::TST_enum) {
4409       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4410            attrs = attrs->getNext())
4411         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4412             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4413     }
4414   }
4415 
4416   return TagD;
4417 }
4418 
4419 /// We are trying to inject an anonymous member into the given scope;
4420 /// check if there's an existing declaration that can't be overloaded.
4421 ///
4422 /// \return true if this is a forbidden redeclaration
4423 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4424                                          Scope *S,
4425                                          DeclContext *Owner,
4426                                          DeclarationName Name,
4427                                          SourceLocation NameLoc,
4428                                          bool IsUnion) {
4429   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4430                  Sema::ForVisibleRedeclaration);
4431   if (!SemaRef.LookupName(R, S)) return false;
4432 
4433   // Pick a representative declaration.
4434   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4435   assert(PrevDecl && "Expected a non-null Decl");
4436 
4437   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4438     return false;
4439 
4440   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4441     << IsUnion << Name;
4442   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4443 
4444   return true;
4445 }
4446 
4447 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4448 /// anonymous struct or union AnonRecord into the owning context Owner
4449 /// and scope S. This routine will be invoked just after we realize
4450 /// that an unnamed union or struct is actually an anonymous union or
4451 /// struct, e.g.,
4452 ///
4453 /// @code
4454 /// union {
4455 ///   int i;
4456 ///   float f;
4457 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4458 ///    // f into the surrounding scope.x
4459 /// @endcode
4460 ///
4461 /// This routine is recursive, injecting the names of nested anonymous
4462 /// structs/unions into the owning context and scope as well.
4463 static bool
4464 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4465                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4466                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4467   bool Invalid = false;
4468 
4469   // Look every FieldDecl and IndirectFieldDecl with a name.
4470   for (auto *D : AnonRecord->decls()) {
4471     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4472         cast<NamedDecl>(D)->getDeclName()) {
4473       ValueDecl *VD = cast<ValueDecl>(D);
4474       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4475                                        VD->getLocation(),
4476                                        AnonRecord->isUnion())) {
4477         // C++ [class.union]p2:
4478         //   The names of the members of an anonymous union shall be
4479         //   distinct from the names of any other entity in the
4480         //   scope in which the anonymous union is declared.
4481         Invalid = true;
4482       } else {
4483         // C++ [class.union]p2:
4484         //   For the purpose of name lookup, after the anonymous union
4485         //   definition, the members of the anonymous union are
4486         //   considered to have been defined in the scope in which the
4487         //   anonymous union is declared.
4488         unsigned OldChainingSize = Chaining.size();
4489         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4490           Chaining.append(IF->chain_begin(), IF->chain_end());
4491         else
4492           Chaining.push_back(VD);
4493 
4494         assert(Chaining.size() >= 2);
4495         NamedDecl **NamedChain =
4496           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4497         for (unsigned i = 0; i < Chaining.size(); i++)
4498           NamedChain[i] = Chaining[i];
4499 
4500         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4501             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4502             VD->getType(), {NamedChain, Chaining.size()});
4503 
4504         for (const auto *Attr : VD->attrs())
4505           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4506 
4507         IndirectField->setAccess(AS);
4508         IndirectField->setImplicit();
4509         SemaRef.PushOnScopeChains(IndirectField, S);
4510 
4511         // That includes picking up the appropriate access specifier.
4512         if (AS != AS_none) IndirectField->setAccess(AS);
4513 
4514         Chaining.resize(OldChainingSize);
4515       }
4516     }
4517   }
4518 
4519   return Invalid;
4520 }
4521 
4522 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4523 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4524 /// illegal input values are mapped to SC_None.
4525 static StorageClass
4526 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4527   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4528   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4529          "Parser allowed 'typedef' as storage class VarDecl.");
4530   switch (StorageClassSpec) {
4531   case DeclSpec::SCS_unspecified:    return SC_None;
4532   case DeclSpec::SCS_extern:
4533     if (DS.isExternInLinkageSpec())
4534       return SC_None;
4535     return SC_Extern;
4536   case DeclSpec::SCS_static:         return SC_Static;
4537   case DeclSpec::SCS_auto:           return SC_Auto;
4538   case DeclSpec::SCS_register:       return SC_Register;
4539   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4540     // Illegal SCSs map to None: error reporting is up to the caller.
4541   case DeclSpec::SCS_mutable:        // Fall through.
4542   case DeclSpec::SCS_typedef:        return SC_None;
4543   }
4544   llvm_unreachable("unknown storage class specifier");
4545 }
4546 
4547 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4548   assert(Record->hasInClassInitializer());
4549 
4550   for (const auto *I : Record->decls()) {
4551     const auto *FD = dyn_cast<FieldDecl>(I);
4552     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4553       FD = IFD->getAnonField();
4554     if (FD && FD->hasInClassInitializer())
4555       return FD->getLocation();
4556   }
4557 
4558   llvm_unreachable("couldn't find in-class initializer");
4559 }
4560 
4561 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4562                                       SourceLocation DefaultInitLoc) {
4563   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4564     return;
4565 
4566   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4567   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4568 }
4569 
4570 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4571                                       CXXRecordDecl *AnonUnion) {
4572   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4573     return;
4574 
4575   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4576 }
4577 
4578 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4579 /// anonymous structure or union. Anonymous unions are a C++ feature
4580 /// (C++ [class.union]) and a C11 feature; anonymous structures
4581 /// are a C11 feature and GNU C++ extension.
4582 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4583                                         AccessSpecifier AS,
4584                                         RecordDecl *Record,
4585                                         const PrintingPolicy &Policy) {
4586   DeclContext *Owner = Record->getDeclContext();
4587 
4588   // Diagnose whether this anonymous struct/union is an extension.
4589   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4590     Diag(Record->getLocation(), diag::ext_anonymous_union);
4591   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4592     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4593   else if (!Record->isUnion() && !getLangOpts().C11)
4594     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4595 
4596   // C and C++ require different kinds of checks for anonymous
4597   // structs/unions.
4598   bool Invalid = false;
4599   if (getLangOpts().CPlusPlus) {
4600     const char *PrevSpec = nullptr;
4601     unsigned DiagID;
4602     if (Record->isUnion()) {
4603       // C++ [class.union]p6:
4604       //   Anonymous unions declared in a named namespace or in the
4605       //   global namespace shall be declared static.
4606       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4607           (isa<TranslationUnitDecl>(Owner) ||
4608            (isa<NamespaceDecl>(Owner) &&
4609             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4610         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4611           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4612 
4613         // Recover by adding 'static'.
4614         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4615                                PrevSpec, DiagID, Policy);
4616       }
4617       // C++ [class.union]p6:
4618       //   A storage class is not allowed in a declaration of an
4619       //   anonymous union in a class scope.
4620       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4621                isa<RecordDecl>(Owner)) {
4622         Diag(DS.getStorageClassSpecLoc(),
4623              diag::err_anonymous_union_with_storage_spec)
4624           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4625 
4626         // Recover by removing the storage specifier.
4627         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4628                                SourceLocation(),
4629                                PrevSpec, DiagID, Context.getPrintingPolicy());
4630       }
4631     }
4632 
4633     // Ignore const/volatile/restrict qualifiers.
4634     if (DS.getTypeQualifiers()) {
4635       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4636         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4637           << Record->isUnion() << "const"
4638           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4639       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4640         Diag(DS.getVolatileSpecLoc(),
4641              diag::ext_anonymous_struct_union_qualified)
4642           << Record->isUnion() << "volatile"
4643           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4644       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4645         Diag(DS.getRestrictSpecLoc(),
4646              diag::ext_anonymous_struct_union_qualified)
4647           << Record->isUnion() << "restrict"
4648           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4649       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4650         Diag(DS.getAtomicSpecLoc(),
4651              diag::ext_anonymous_struct_union_qualified)
4652           << Record->isUnion() << "_Atomic"
4653           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4654       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4655         Diag(DS.getUnalignedSpecLoc(),
4656              diag::ext_anonymous_struct_union_qualified)
4657           << Record->isUnion() << "__unaligned"
4658           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4659 
4660       DS.ClearTypeQualifiers();
4661     }
4662 
4663     // C++ [class.union]p2:
4664     //   The member-specification of an anonymous union shall only
4665     //   define non-static data members. [Note: nested types and
4666     //   functions cannot be declared within an anonymous union. ]
4667     for (auto *Mem : Record->decls()) {
4668       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4669         // C++ [class.union]p3:
4670         //   An anonymous union shall not have private or protected
4671         //   members (clause 11).
4672         assert(FD->getAccess() != AS_none);
4673         if (FD->getAccess() != AS_public) {
4674           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4675             << Record->isUnion() << (FD->getAccess() == AS_protected);
4676           Invalid = true;
4677         }
4678 
4679         // C++ [class.union]p1
4680         //   An object of a class with a non-trivial constructor, a non-trivial
4681         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4682         //   assignment operator cannot be a member of a union, nor can an
4683         //   array of such objects.
4684         if (CheckNontrivialField(FD))
4685           Invalid = true;
4686       } else if (Mem->isImplicit()) {
4687         // Any implicit members are fine.
4688       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4689         // This is a type that showed up in an
4690         // elaborated-type-specifier inside the anonymous struct or
4691         // union, but which actually declares a type outside of the
4692         // anonymous struct or union. It's okay.
4693       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4694         if (!MemRecord->isAnonymousStructOrUnion() &&
4695             MemRecord->getDeclName()) {
4696           // Visual C++ allows type definition in anonymous struct or union.
4697           if (getLangOpts().MicrosoftExt)
4698             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4699               << Record->isUnion();
4700           else {
4701             // This is a nested type declaration.
4702             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4703               << Record->isUnion();
4704             Invalid = true;
4705           }
4706         } else {
4707           // This is an anonymous type definition within another anonymous type.
4708           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4709           // not part of standard C++.
4710           Diag(MemRecord->getLocation(),
4711                diag::ext_anonymous_record_with_anonymous_type)
4712             << Record->isUnion();
4713         }
4714       } else if (isa<AccessSpecDecl>(Mem)) {
4715         // Any access specifier is fine.
4716       } else if (isa<StaticAssertDecl>(Mem)) {
4717         // In C++1z, static_assert declarations are also fine.
4718       } else {
4719         // We have something that isn't a non-static data
4720         // member. Complain about it.
4721         unsigned DK = diag::err_anonymous_record_bad_member;
4722         if (isa<TypeDecl>(Mem))
4723           DK = diag::err_anonymous_record_with_type;
4724         else if (isa<FunctionDecl>(Mem))
4725           DK = diag::err_anonymous_record_with_function;
4726         else if (isa<VarDecl>(Mem))
4727           DK = diag::err_anonymous_record_with_static;
4728 
4729         // Visual C++ allows type definition in anonymous struct or union.
4730         if (getLangOpts().MicrosoftExt &&
4731             DK == diag::err_anonymous_record_with_type)
4732           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4733             << Record->isUnion();
4734         else {
4735           Diag(Mem->getLocation(), DK) << Record->isUnion();
4736           Invalid = true;
4737         }
4738       }
4739     }
4740 
4741     // C++11 [class.union]p8 (DR1460):
4742     //   At most one variant member of a union may have a
4743     //   brace-or-equal-initializer.
4744     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4745         Owner->isRecord())
4746       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4747                                 cast<CXXRecordDecl>(Record));
4748   }
4749 
4750   if (!Record->isUnion() && !Owner->isRecord()) {
4751     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4752       << getLangOpts().CPlusPlus;
4753     Invalid = true;
4754   }
4755 
4756   // Mock up a declarator.
4757   Declarator Dc(DS, Declarator::MemberContext);
4758   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4759   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4760 
4761   // Create a declaration for this anonymous struct/union.
4762   NamedDecl *Anon = nullptr;
4763   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4764     Anon = FieldDecl::Create(Context, OwningClass,
4765                              DS.getLocStart(),
4766                              Record->getLocation(),
4767                              /*IdentifierInfo=*/nullptr,
4768                              Context.getTypeDeclType(Record),
4769                              TInfo,
4770                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4771                              /*InitStyle=*/ICIS_NoInit);
4772     Anon->setAccess(AS);
4773     if (getLangOpts().CPlusPlus)
4774       FieldCollector->Add(cast<FieldDecl>(Anon));
4775   } else {
4776     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4777     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4778     if (SCSpec == DeclSpec::SCS_mutable) {
4779       // mutable can only appear on non-static class members, so it's always
4780       // an error here
4781       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4782       Invalid = true;
4783       SC = SC_None;
4784     }
4785 
4786     Anon = VarDecl::Create(Context, Owner,
4787                            DS.getLocStart(),
4788                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4789                            Context.getTypeDeclType(Record),
4790                            TInfo, SC);
4791 
4792     // Default-initialize the implicit variable. This initialization will be
4793     // trivial in almost all cases, except if a union member has an in-class
4794     // initializer:
4795     //   union { int n = 0; };
4796     ActOnUninitializedDecl(Anon);
4797   }
4798   Anon->setImplicit();
4799 
4800   // Mark this as an anonymous struct/union type.
4801   Record->setAnonymousStructOrUnion(true);
4802 
4803   // Add the anonymous struct/union object to the current
4804   // context. We'll be referencing this object when we refer to one of
4805   // its members.
4806   Owner->addDecl(Anon);
4807 
4808   // Inject the members of the anonymous struct/union into the owning
4809   // context and into the identifier resolver chain for name lookup
4810   // purposes.
4811   SmallVector<NamedDecl*, 2> Chain;
4812   Chain.push_back(Anon);
4813 
4814   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4815     Invalid = true;
4816 
4817   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4818     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4819       Decl *ManglingContextDecl;
4820       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4821               NewVD->getDeclContext(), ManglingContextDecl)) {
4822         Context.setManglingNumber(
4823             NewVD, MCtx->getManglingNumber(
4824                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4825         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4826       }
4827     }
4828   }
4829 
4830   if (Invalid)
4831     Anon->setInvalidDecl();
4832 
4833   return Anon;
4834 }
4835 
4836 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4837 /// Microsoft C anonymous structure.
4838 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4839 /// Example:
4840 ///
4841 /// struct A { int a; };
4842 /// struct B { struct A; int b; };
4843 ///
4844 /// void foo() {
4845 ///   B var;
4846 ///   var.a = 3;
4847 /// }
4848 ///
4849 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4850                                            RecordDecl *Record) {
4851   assert(Record && "expected a record!");
4852 
4853   // Mock up a declarator.
4854   Declarator Dc(DS, Declarator::TypeNameContext);
4855   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4856   assert(TInfo && "couldn't build declarator info for anonymous struct");
4857 
4858   auto *ParentDecl = cast<RecordDecl>(CurContext);
4859   QualType RecTy = Context.getTypeDeclType(Record);
4860 
4861   // Create a declaration for this anonymous struct.
4862   NamedDecl *Anon = FieldDecl::Create(Context,
4863                              ParentDecl,
4864                              DS.getLocStart(),
4865                              DS.getLocStart(),
4866                              /*IdentifierInfo=*/nullptr,
4867                              RecTy,
4868                              TInfo,
4869                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4870                              /*InitStyle=*/ICIS_NoInit);
4871   Anon->setImplicit();
4872 
4873   // Add the anonymous struct object to the current context.
4874   CurContext->addDecl(Anon);
4875 
4876   // Inject the members of the anonymous struct into the current
4877   // context and into the identifier resolver chain for name lookup
4878   // purposes.
4879   SmallVector<NamedDecl*, 2> Chain;
4880   Chain.push_back(Anon);
4881 
4882   RecordDecl *RecordDef = Record->getDefinition();
4883   if (RequireCompleteType(Anon->getLocation(), RecTy,
4884                           diag::err_field_incomplete) ||
4885       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4886                                           AS_none, Chain)) {
4887     Anon->setInvalidDecl();
4888     ParentDecl->setInvalidDecl();
4889   }
4890 
4891   return Anon;
4892 }
4893 
4894 /// GetNameForDeclarator - Determine the full declaration name for the
4895 /// given Declarator.
4896 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4897   return GetNameFromUnqualifiedId(D.getName());
4898 }
4899 
4900 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4901 DeclarationNameInfo
4902 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4903   DeclarationNameInfo NameInfo;
4904   NameInfo.setLoc(Name.StartLocation);
4905 
4906   switch (Name.getKind()) {
4907 
4908   case UnqualifiedId::IK_ImplicitSelfParam:
4909   case UnqualifiedId::IK_Identifier:
4910     NameInfo.setName(Name.Identifier);
4911     NameInfo.setLoc(Name.StartLocation);
4912     return NameInfo;
4913 
4914   case UnqualifiedId::IK_DeductionGuideName: {
4915     // C++ [temp.deduct.guide]p3:
4916     //   The simple-template-id shall name a class template specialization.
4917     //   The template-name shall be the same identifier as the template-name
4918     //   of the simple-template-id.
4919     // These together intend to imply that the template-name shall name a
4920     // class template.
4921     // FIXME: template<typename T> struct X {};
4922     //        template<typename T> using Y = X<T>;
4923     //        Y(int) -> Y<int>;
4924     //   satisfies these rules but does not name a class template.
4925     TemplateName TN = Name.TemplateName.get().get();
4926     auto *Template = TN.getAsTemplateDecl();
4927     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4928       Diag(Name.StartLocation,
4929            diag::err_deduction_guide_name_not_class_template)
4930         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4931       if (Template)
4932         Diag(Template->getLocation(), diag::note_template_decl_here);
4933       return DeclarationNameInfo();
4934     }
4935 
4936     NameInfo.setName(
4937         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4938     NameInfo.setLoc(Name.StartLocation);
4939     return NameInfo;
4940   }
4941 
4942   case UnqualifiedId::IK_OperatorFunctionId:
4943     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4944                                            Name.OperatorFunctionId.Operator));
4945     NameInfo.setLoc(Name.StartLocation);
4946     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4947       = Name.OperatorFunctionId.SymbolLocations[0];
4948     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4949       = Name.EndLocation.getRawEncoding();
4950     return NameInfo;
4951 
4952   case UnqualifiedId::IK_LiteralOperatorId:
4953     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4954                                                            Name.Identifier));
4955     NameInfo.setLoc(Name.StartLocation);
4956     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4957     return NameInfo;
4958 
4959   case UnqualifiedId::IK_ConversionFunctionId: {
4960     TypeSourceInfo *TInfo;
4961     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4962     if (Ty.isNull())
4963       return DeclarationNameInfo();
4964     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4965                                                Context.getCanonicalType(Ty)));
4966     NameInfo.setLoc(Name.StartLocation);
4967     NameInfo.setNamedTypeInfo(TInfo);
4968     return NameInfo;
4969   }
4970 
4971   case UnqualifiedId::IK_ConstructorName: {
4972     TypeSourceInfo *TInfo;
4973     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4974     if (Ty.isNull())
4975       return DeclarationNameInfo();
4976     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4977                                               Context.getCanonicalType(Ty)));
4978     NameInfo.setLoc(Name.StartLocation);
4979     NameInfo.setNamedTypeInfo(TInfo);
4980     return NameInfo;
4981   }
4982 
4983   case UnqualifiedId::IK_ConstructorTemplateId: {
4984     // In well-formed code, we can only have a constructor
4985     // template-id that refers to the current context, so go there
4986     // to find the actual type being constructed.
4987     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4988     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4989       return DeclarationNameInfo();
4990 
4991     // Determine the type of the class being constructed.
4992     QualType CurClassType = Context.getTypeDeclType(CurClass);
4993 
4994     // FIXME: Check two things: that the template-id names the same type as
4995     // CurClassType, and that the template-id does not occur when the name
4996     // was qualified.
4997 
4998     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4999                                     Context.getCanonicalType(CurClassType)));
5000     NameInfo.setLoc(Name.StartLocation);
5001     // FIXME: should we retrieve TypeSourceInfo?
5002     NameInfo.setNamedTypeInfo(nullptr);
5003     return NameInfo;
5004   }
5005 
5006   case UnqualifiedId::IK_DestructorName: {
5007     TypeSourceInfo *TInfo;
5008     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5009     if (Ty.isNull())
5010       return DeclarationNameInfo();
5011     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5012                                               Context.getCanonicalType(Ty)));
5013     NameInfo.setLoc(Name.StartLocation);
5014     NameInfo.setNamedTypeInfo(TInfo);
5015     return NameInfo;
5016   }
5017 
5018   case UnqualifiedId::IK_TemplateId: {
5019     TemplateName TName = Name.TemplateId->Template.get();
5020     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5021     return Context.getNameForTemplate(TName, TNameLoc);
5022   }
5023 
5024   } // switch (Name.getKind())
5025 
5026   llvm_unreachable("Unknown name kind");
5027 }
5028 
5029 static QualType getCoreType(QualType Ty) {
5030   do {
5031     if (Ty->isPointerType() || Ty->isReferenceType())
5032       Ty = Ty->getPointeeType();
5033     else if (Ty->isArrayType())
5034       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5035     else
5036       return Ty.withoutLocalFastQualifiers();
5037   } while (true);
5038 }
5039 
5040 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5041 /// and Definition have "nearly" matching parameters. This heuristic is
5042 /// used to improve diagnostics in the case where an out-of-line function
5043 /// definition doesn't match any declaration within the class or namespace.
5044 /// Also sets Params to the list of indices to the parameters that differ
5045 /// between the declaration and the definition. If hasSimilarParameters
5046 /// returns true and Params is empty, then all of the parameters match.
5047 static bool hasSimilarParameters(ASTContext &Context,
5048                                      FunctionDecl *Declaration,
5049                                      FunctionDecl *Definition,
5050                                      SmallVectorImpl<unsigned> &Params) {
5051   Params.clear();
5052   if (Declaration->param_size() != Definition->param_size())
5053     return false;
5054   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5055     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5056     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5057 
5058     // The parameter types are identical
5059     if (Context.hasSameType(DefParamTy, DeclParamTy))
5060       continue;
5061 
5062     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5063     QualType DefParamBaseTy = getCoreType(DefParamTy);
5064     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5065     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5066 
5067     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5068         (DeclTyName && DeclTyName == DefTyName))
5069       Params.push_back(Idx);
5070     else  // The two parameters aren't even close
5071       return false;
5072   }
5073 
5074   return true;
5075 }
5076 
5077 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5078 /// declarator needs to be rebuilt in the current instantiation.
5079 /// Any bits of declarator which appear before the name are valid for
5080 /// consideration here.  That's specifically the type in the decl spec
5081 /// and the base type in any member-pointer chunks.
5082 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5083                                                     DeclarationName Name) {
5084   // The types we specifically need to rebuild are:
5085   //   - typenames, typeofs, and decltypes
5086   //   - types which will become injected class names
5087   // Of course, we also need to rebuild any type referencing such a
5088   // type.  It's safest to just say "dependent", but we call out a
5089   // few cases here.
5090 
5091   DeclSpec &DS = D.getMutableDeclSpec();
5092   switch (DS.getTypeSpecType()) {
5093   case DeclSpec::TST_typename:
5094   case DeclSpec::TST_typeofType:
5095   case DeclSpec::TST_underlyingType:
5096   case DeclSpec::TST_atomic: {
5097     // Grab the type from the parser.
5098     TypeSourceInfo *TSI = nullptr;
5099     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5100     if (T.isNull() || !T->isDependentType()) break;
5101 
5102     // Make sure there's a type source info.  This isn't really much
5103     // of a waste; most dependent types should have type source info
5104     // attached already.
5105     if (!TSI)
5106       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5107 
5108     // Rebuild the type in the current instantiation.
5109     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5110     if (!TSI) return true;
5111 
5112     // Store the new type back in the decl spec.
5113     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5114     DS.UpdateTypeRep(LocType);
5115     break;
5116   }
5117 
5118   case DeclSpec::TST_decltype:
5119   case DeclSpec::TST_typeofExpr: {
5120     Expr *E = DS.getRepAsExpr();
5121     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5122     if (Result.isInvalid()) return true;
5123     DS.UpdateExprRep(Result.get());
5124     break;
5125   }
5126 
5127   default:
5128     // Nothing to do for these decl specs.
5129     break;
5130   }
5131 
5132   // It doesn't matter what order we do this in.
5133   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5134     DeclaratorChunk &Chunk = D.getTypeObject(I);
5135 
5136     // The only type information in the declarator which can come
5137     // before the declaration name is the base type of a member
5138     // pointer.
5139     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5140       continue;
5141 
5142     // Rebuild the scope specifier in-place.
5143     CXXScopeSpec &SS = Chunk.Mem.Scope();
5144     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5145       return true;
5146   }
5147 
5148   return false;
5149 }
5150 
5151 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5152   D.setFunctionDefinitionKind(FDK_Declaration);
5153   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5154 
5155   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5156       Dcl && Dcl->getDeclContext()->isFileContext())
5157     Dcl->setTopLevelDeclInObjCContainer();
5158 
5159   if (getLangOpts().OpenCL)
5160     setCurrentOpenCLExtensionForDecl(Dcl);
5161 
5162   return Dcl;
5163 }
5164 
5165 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5166 ///   If T is the name of a class, then each of the following shall have a
5167 ///   name different from T:
5168 ///     - every static data member of class T;
5169 ///     - every member function of class T
5170 ///     - every member of class T that is itself a type;
5171 /// \returns true if the declaration name violates these rules.
5172 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5173                                    DeclarationNameInfo NameInfo) {
5174   DeclarationName Name = NameInfo.getName();
5175 
5176   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5177   while (Record && Record->isAnonymousStructOrUnion())
5178     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5179   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5180     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5181     return true;
5182   }
5183 
5184   return false;
5185 }
5186 
5187 /// \brief Diagnose a declaration whose declarator-id has the given
5188 /// nested-name-specifier.
5189 ///
5190 /// \param SS The nested-name-specifier of the declarator-id.
5191 ///
5192 /// \param DC The declaration context to which the nested-name-specifier
5193 /// resolves.
5194 ///
5195 /// \param Name The name of the entity being declared.
5196 ///
5197 /// \param Loc The location of the name of the entity being declared.
5198 ///
5199 /// \returns true if we cannot safely recover from this error, false otherwise.
5200 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5201                                         DeclarationName Name,
5202                                         SourceLocation Loc) {
5203   DeclContext *Cur = CurContext;
5204   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5205     Cur = Cur->getParent();
5206 
5207   // If the user provided a superfluous scope specifier that refers back to the
5208   // class in which the entity is already declared, diagnose and ignore it.
5209   //
5210   // class X {
5211   //   void X::f();
5212   // };
5213   //
5214   // Note, it was once ill-formed to give redundant qualification in all
5215   // contexts, but that rule was removed by DR482.
5216   if (Cur->Equals(DC)) {
5217     if (Cur->isRecord()) {
5218       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5219                                       : diag::err_member_extra_qualification)
5220         << Name << FixItHint::CreateRemoval(SS.getRange());
5221       SS.clear();
5222     } else {
5223       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5224     }
5225     return false;
5226   }
5227 
5228   // Check whether the qualifying scope encloses the scope of the original
5229   // declaration.
5230   if (!Cur->Encloses(DC)) {
5231     if (Cur->isRecord())
5232       Diag(Loc, diag::err_member_qualification)
5233         << Name << SS.getRange();
5234     else if (isa<TranslationUnitDecl>(DC))
5235       Diag(Loc, diag::err_invalid_declarator_global_scope)
5236         << Name << SS.getRange();
5237     else if (isa<FunctionDecl>(Cur))
5238       Diag(Loc, diag::err_invalid_declarator_in_function)
5239         << Name << SS.getRange();
5240     else if (isa<BlockDecl>(Cur))
5241       Diag(Loc, diag::err_invalid_declarator_in_block)
5242         << Name << SS.getRange();
5243     else
5244       Diag(Loc, diag::err_invalid_declarator_scope)
5245       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5246 
5247     return true;
5248   }
5249 
5250   if (Cur->isRecord()) {
5251     // Cannot qualify members within a class.
5252     Diag(Loc, diag::err_member_qualification)
5253       << Name << SS.getRange();
5254     SS.clear();
5255 
5256     // C++ constructors and destructors with incorrect scopes can break
5257     // our AST invariants by having the wrong underlying types. If
5258     // that's the case, then drop this declaration entirely.
5259     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5260          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5261         !Context.hasSameType(Name.getCXXNameType(),
5262                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5263       return true;
5264 
5265     return false;
5266   }
5267 
5268   // C++11 [dcl.meaning]p1:
5269   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5270   //   not begin with a decltype-specifer"
5271   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5272   while (SpecLoc.getPrefix())
5273     SpecLoc = SpecLoc.getPrefix();
5274   if (dyn_cast_or_null<DecltypeType>(
5275         SpecLoc.getNestedNameSpecifier()->getAsType()))
5276     Diag(Loc, diag::err_decltype_in_declarator)
5277       << SpecLoc.getTypeLoc().getSourceRange();
5278 
5279   return false;
5280 }
5281 
5282 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5283                                   MultiTemplateParamsArg TemplateParamLists) {
5284   // TODO: consider using NameInfo for diagnostic.
5285   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5286   DeclarationName Name = NameInfo.getName();
5287 
5288   // All of these full declarators require an identifier.  If it doesn't have
5289   // one, the ParsedFreeStandingDeclSpec action should be used.
5290   if (D.isDecompositionDeclarator()) {
5291     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5292   } else if (!Name) {
5293     if (!D.isInvalidType())  // Reject this if we think it is valid.
5294       Diag(D.getDeclSpec().getLocStart(),
5295            diag::err_declarator_need_ident)
5296         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5297     return nullptr;
5298   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5299     return nullptr;
5300 
5301   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5302   // we find one that is.
5303   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5304          (S->getFlags() & Scope::TemplateParamScope) != 0)
5305     S = S->getParent();
5306 
5307   DeclContext *DC = CurContext;
5308   if (D.getCXXScopeSpec().isInvalid())
5309     D.setInvalidType();
5310   else if (D.getCXXScopeSpec().isSet()) {
5311     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5312                                         UPPC_DeclarationQualifier))
5313       return nullptr;
5314 
5315     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5316     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5317     if (!DC || isa<EnumDecl>(DC)) {
5318       // If we could not compute the declaration context, it's because the
5319       // declaration context is dependent but does not refer to a class,
5320       // class template, or class template partial specialization. Complain
5321       // and return early, to avoid the coming semantic disaster.
5322       Diag(D.getIdentifierLoc(),
5323            diag::err_template_qualified_declarator_no_match)
5324         << D.getCXXScopeSpec().getScopeRep()
5325         << D.getCXXScopeSpec().getRange();
5326       return nullptr;
5327     }
5328     bool IsDependentContext = DC->isDependentContext();
5329 
5330     if (!IsDependentContext &&
5331         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5332       return nullptr;
5333 
5334     // If a class is incomplete, do not parse entities inside it.
5335     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5336       Diag(D.getIdentifierLoc(),
5337            diag::err_member_def_undefined_record)
5338         << Name << DC << D.getCXXScopeSpec().getRange();
5339       return nullptr;
5340     }
5341     if (!D.getDeclSpec().isFriendSpecified()) {
5342       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5343                                       Name, D.getIdentifierLoc())) {
5344         if (DC->isRecord())
5345           return nullptr;
5346 
5347         D.setInvalidType();
5348       }
5349     }
5350 
5351     // Check whether we need to rebuild the type of the given
5352     // declaration in the current instantiation.
5353     if (EnteringContext && IsDependentContext &&
5354         TemplateParamLists.size() != 0) {
5355       ContextRAII SavedContext(*this, DC);
5356       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5357         D.setInvalidType();
5358     }
5359   }
5360 
5361   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5362   QualType R = TInfo->getType();
5363 
5364   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5365                                       UPPC_DeclarationType))
5366     D.setInvalidType();
5367 
5368   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5369                         forRedeclarationInCurContext());
5370 
5371   // See if this is a redefinition of a variable in the same scope.
5372   if (!D.getCXXScopeSpec().isSet()) {
5373     bool IsLinkageLookup = false;
5374     bool CreateBuiltins = false;
5375 
5376     // If the declaration we're planning to build will be a function
5377     // or object with linkage, then look for another declaration with
5378     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5379     //
5380     // If the declaration we're planning to build will be declared with
5381     // external linkage in the translation unit, create any builtin with
5382     // the same name.
5383     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5384       /* Do nothing*/;
5385     else if (CurContext->isFunctionOrMethod() &&
5386              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5387               R->isFunctionType())) {
5388       IsLinkageLookup = true;
5389       CreateBuiltins =
5390           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5391     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5392                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5393       CreateBuiltins = true;
5394 
5395     if (IsLinkageLookup) {
5396       Previous.clear(LookupRedeclarationWithLinkage);
5397       Previous.setRedeclarationKind(ForExternalRedeclaration);
5398     }
5399 
5400     LookupName(Previous, S, CreateBuiltins);
5401   } else { // Something like "int foo::x;"
5402     LookupQualifiedName(Previous, DC);
5403 
5404     // C++ [dcl.meaning]p1:
5405     //   When the declarator-id is qualified, the declaration shall refer to a
5406     //  previously declared member of the class or namespace to which the
5407     //  qualifier refers (or, in the case of a namespace, of an element of the
5408     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5409     //  thereof; [...]
5410     //
5411     // Note that we already checked the context above, and that we do not have
5412     // enough information to make sure that Previous contains the declaration
5413     // we want to match. For example, given:
5414     //
5415     //   class X {
5416     //     void f();
5417     //     void f(float);
5418     //   };
5419     //
5420     //   void X::f(int) { } // ill-formed
5421     //
5422     // In this case, Previous will point to the overload set
5423     // containing the two f's declared in X, but neither of them
5424     // matches.
5425 
5426     // C++ [dcl.meaning]p1:
5427     //   [...] the member shall not merely have been introduced by a
5428     //   using-declaration in the scope of the class or namespace nominated by
5429     //   the nested-name-specifier of the declarator-id.
5430     RemoveUsingDecls(Previous);
5431   }
5432 
5433   if (Previous.isSingleResult() &&
5434       Previous.getFoundDecl()->isTemplateParameter()) {
5435     // Maybe we will complain about the shadowed template parameter.
5436     if (!D.isInvalidType())
5437       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5438                                       Previous.getFoundDecl());
5439 
5440     // Just pretend that we didn't see the previous declaration.
5441     Previous.clear();
5442   }
5443 
5444   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5445     // Forget that the previous declaration is the injected-class-name.
5446     Previous.clear();
5447 
5448   // In C++, the previous declaration we find might be a tag type
5449   // (class or enum). In this case, the new declaration will hide the
5450   // tag type. Note that this applies to functions, function templates, and
5451   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5452   if (Previous.isSingleTagDecl() &&
5453       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5454       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5455     Previous.clear();
5456 
5457   // Check that there are no default arguments other than in the parameters
5458   // of a function declaration (C++ only).
5459   if (getLangOpts().CPlusPlus)
5460     CheckExtraCXXDefaultArguments(D);
5461 
5462   if (D.getDeclSpec().isConceptSpecified()) {
5463     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5464     // applied only to the definition of a function template or variable
5465     // template, declared in namespace scope
5466     if (!TemplateParamLists.size()) {
5467       Diag(D.getDeclSpec().getConceptSpecLoc(),
5468            diag:: err_concept_wrong_decl_kind);
5469       return nullptr;
5470     }
5471 
5472     if (!DC->getRedeclContext()->isFileContext()) {
5473       Diag(D.getIdentifierLoc(),
5474            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5475       return nullptr;
5476     }
5477   }
5478 
5479   NamedDecl *New;
5480 
5481   bool AddToScope = true;
5482   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5483     if (TemplateParamLists.size()) {
5484       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5485       return nullptr;
5486     }
5487 
5488     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5489   } else if (R->isFunctionType()) {
5490     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5491                                   TemplateParamLists,
5492                                   AddToScope);
5493   } else {
5494     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5495                                   AddToScope);
5496   }
5497 
5498   if (!New)
5499     return nullptr;
5500 
5501   // If this has an identifier and is not a function template specialization,
5502   // add it to the scope stack.
5503   if (New->getDeclName() && AddToScope) {
5504     // Only make a locally-scoped extern declaration visible if it is the first
5505     // declaration of this entity. Qualified lookup for such an entity should
5506     // only find this declaration if there is no visible declaration of it.
5507     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5508     PushOnScopeChains(New, S, AddToContext);
5509     if (!AddToContext)
5510       CurContext->addHiddenDecl(New);
5511   }
5512 
5513   if (isInOpenMPDeclareTargetContext())
5514     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5515 
5516   return New;
5517 }
5518 
5519 /// Helper method to turn variable array types into constant array
5520 /// types in certain situations which would otherwise be errors (for
5521 /// GCC compatibility).
5522 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5523                                                     ASTContext &Context,
5524                                                     bool &SizeIsNegative,
5525                                                     llvm::APSInt &Oversized) {
5526   // This method tries to turn a variable array into a constant
5527   // array even when the size isn't an ICE.  This is necessary
5528   // for compatibility with code that depends on gcc's buggy
5529   // constant expression folding, like struct {char x[(int)(char*)2];}
5530   SizeIsNegative = false;
5531   Oversized = 0;
5532 
5533   if (T->isDependentType())
5534     return QualType();
5535 
5536   QualifierCollector Qs;
5537   const Type *Ty = Qs.strip(T);
5538 
5539   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5540     QualType Pointee = PTy->getPointeeType();
5541     QualType FixedType =
5542         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5543                                             Oversized);
5544     if (FixedType.isNull()) return FixedType;
5545     FixedType = Context.getPointerType(FixedType);
5546     return Qs.apply(Context, FixedType);
5547   }
5548   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5549     QualType Inner = PTy->getInnerType();
5550     QualType FixedType =
5551         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5552                                             Oversized);
5553     if (FixedType.isNull()) return FixedType;
5554     FixedType = Context.getParenType(FixedType);
5555     return Qs.apply(Context, FixedType);
5556   }
5557 
5558   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5559   if (!VLATy)
5560     return QualType();
5561   // FIXME: We should probably handle this case
5562   if (VLATy->getElementType()->isVariablyModifiedType())
5563     return QualType();
5564 
5565   llvm::APSInt Res;
5566   if (!VLATy->getSizeExpr() ||
5567       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5568     return QualType();
5569 
5570   // Check whether the array size is negative.
5571   if (Res.isSigned() && Res.isNegative()) {
5572     SizeIsNegative = true;
5573     return QualType();
5574   }
5575 
5576   // Check whether the array is too large to be addressed.
5577   unsigned ActiveSizeBits
5578     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5579                                               Res);
5580   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5581     Oversized = Res;
5582     return QualType();
5583   }
5584 
5585   return Context.getConstantArrayType(VLATy->getElementType(),
5586                                       Res, ArrayType::Normal, 0);
5587 }
5588 
5589 static void
5590 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5591   SrcTL = SrcTL.getUnqualifiedLoc();
5592   DstTL = DstTL.getUnqualifiedLoc();
5593   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5594     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5595     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5596                                       DstPTL.getPointeeLoc());
5597     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5598     return;
5599   }
5600   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5601     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5602     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5603                                       DstPTL.getInnerLoc());
5604     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5605     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5606     return;
5607   }
5608   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5609   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5610   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5611   TypeLoc DstElemTL = DstATL.getElementLoc();
5612   DstElemTL.initializeFullCopy(SrcElemTL);
5613   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5614   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5615   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5616 }
5617 
5618 /// Helper method to turn variable array types into constant array
5619 /// types in certain situations which would otherwise be errors (for
5620 /// GCC compatibility).
5621 static TypeSourceInfo*
5622 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5623                                               ASTContext &Context,
5624                                               bool &SizeIsNegative,
5625                                               llvm::APSInt &Oversized) {
5626   QualType FixedTy
5627     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5628                                           SizeIsNegative, Oversized);
5629   if (FixedTy.isNull())
5630     return nullptr;
5631   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5632   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5633                                     FixedTInfo->getTypeLoc());
5634   return FixedTInfo;
5635 }
5636 
5637 /// \brief Register the given locally-scoped extern "C" declaration so
5638 /// that it can be found later for redeclarations. We include any extern "C"
5639 /// declaration that is not visible in the translation unit here, not just
5640 /// function-scope declarations.
5641 void
5642 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5643   if (!getLangOpts().CPlusPlus &&
5644       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5645     // Don't need to track declarations in the TU in C.
5646     return;
5647 
5648   // Note that we have a locally-scoped external with this name.
5649   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5650 }
5651 
5652 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5653   // FIXME: We can have multiple results via __attribute__((overloadable)).
5654   auto Result = Context.getExternCContextDecl()->lookup(Name);
5655   return Result.empty() ? nullptr : *Result.begin();
5656 }
5657 
5658 /// \brief Diagnose function specifiers on a declaration of an identifier that
5659 /// does not identify a function.
5660 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5661   // FIXME: We should probably indicate the identifier in question to avoid
5662   // confusion for constructs like "virtual int a(), b;"
5663   if (DS.isVirtualSpecified())
5664     Diag(DS.getVirtualSpecLoc(),
5665          diag::err_virtual_non_function);
5666 
5667   if (DS.isExplicitSpecified())
5668     Diag(DS.getExplicitSpecLoc(),
5669          diag::err_explicit_non_function);
5670 
5671   if (DS.isNoreturnSpecified())
5672     Diag(DS.getNoreturnSpecLoc(),
5673          diag::err_noreturn_non_function);
5674 }
5675 
5676 NamedDecl*
5677 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5678                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5679   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5680   if (D.getCXXScopeSpec().isSet()) {
5681     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5682       << D.getCXXScopeSpec().getRange();
5683     D.setInvalidType();
5684     // Pretend we didn't see the scope specifier.
5685     DC = CurContext;
5686     Previous.clear();
5687   }
5688 
5689   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5690 
5691   if (D.getDeclSpec().isInlineSpecified())
5692     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5693         << getLangOpts().CPlusPlus1z;
5694   if (D.getDeclSpec().isConstexprSpecified())
5695     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5696       << 1;
5697   if (D.getDeclSpec().isConceptSpecified())
5698     Diag(D.getDeclSpec().getConceptSpecLoc(),
5699          diag::err_concept_wrong_decl_kind);
5700 
5701   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5702     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5703       Diag(D.getName().StartLocation,
5704            diag::err_deduction_guide_invalid_specifier)
5705           << "typedef";
5706     else
5707       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5708           << D.getName().getSourceRange();
5709     return nullptr;
5710   }
5711 
5712   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5713   if (!NewTD) return nullptr;
5714 
5715   // Handle attributes prior to checking for duplicates in MergeVarDecl
5716   ProcessDeclAttributes(S, NewTD, D);
5717 
5718   CheckTypedefForVariablyModifiedType(S, NewTD);
5719 
5720   bool Redeclaration = D.isRedeclaration();
5721   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5722   D.setRedeclaration(Redeclaration);
5723   return ND;
5724 }
5725 
5726 void
5727 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5728   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5729   // then it shall have block scope.
5730   // Note that variably modified types must be fixed before merging the decl so
5731   // that redeclarations will match.
5732   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5733   QualType T = TInfo->getType();
5734   if (T->isVariablyModifiedType()) {
5735     getCurFunction()->setHasBranchProtectedScope();
5736 
5737     if (S->getFnParent() == nullptr) {
5738       bool SizeIsNegative;
5739       llvm::APSInt Oversized;
5740       TypeSourceInfo *FixedTInfo =
5741         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5742                                                       SizeIsNegative,
5743                                                       Oversized);
5744       if (FixedTInfo) {
5745         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5746         NewTD->setTypeSourceInfo(FixedTInfo);
5747       } else {
5748         if (SizeIsNegative)
5749           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5750         else if (T->isVariableArrayType())
5751           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5752         else if (Oversized.getBoolValue())
5753           Diag(NewTD->getLocation(), diag::err_array_too_large)
5754             << Oversized.toString(10);
5755         else
5756           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5757         NewTD->setInvalidDecl();
5758       }
5759     }
5760   }
5761 }
5762 
5763 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5764 /// declares a typedef-name, either using the 'typedef' type specifier or via
5765 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5766 NamedDecl*
5767 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5768                            LookupResult &Previous, bool &Redeclaration) {
5769 
5770   // Find the shadowed declaration before filtering for scope.
5771   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5772 
5773   // Merge the decl with the existing one if appropriate. If the decl is
5774   // in an outer scope, it isn't the same thing.
5775   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5776                        /*AllowInlineNamespace*/false);
5777   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5778   if (!Previous.empty()) {
5779     Redeclaration = true;
5780     MergeTypedefNameDecl(S, NewTD, Previous);
5781   }
5782 
5783   if (ShadowedDecl && !Redeclaration)
5784     CheckShadow(NewTD, ShadowedDecl, Previous);
5785 
5786   // If this is the C FILE type, notify the AST context.
5787   if (IdentifierInfo *II = NewTD->getIdentifier())
5788     if (!NewTD->isInvalidDecl() &&
5789         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5790       if (II->isStr("FILE"))
5791         Context.setFILEDecl(NewTD);
5792       else if (II->isStr("jmp_buf"))
5793         Context.setjmp_bufDecl(NewTD);
5794       else if (II->isStr("sigjmp_buf"))
5795         Context.setsigjmp_bufDecl(NewTD);
5796       else if (II->isStr("ucontext_t"))
5797         Context.setucontext_tDecl(NewTD);
5798     }
5799 
5800   return NewTD;
5801 }
5802 
5803 /// \brief Determines whether the given declaration is an out-of-scope
5804 /// previous declaration.
5805 ///
5806 /// This routine should be invoked when name lookup has found a
5807 /// previous declaration (PrevDecl) that is not in the scope where a
5808 /// new declaration by the same name is being introduced. If the new
5809 /// declaration occurs in a local scope, previous declarations with
5810 /// linkage may still be considered previous declarations (C99
5811 /// 6.2.2p4-5, C++ [basic.link]p6).
5812 ///
5813 /// \param PrevDecl the previous declaration found by name
5814 /// lookup
5815 ///
5816 /// \param DC the context in which the new declaration is being
5817 /// declared.
5818 ///
5819 /// \returns true if PrevDecl is an out-of-scope previous declaration
5820 /// for a new delcaration with the same name.
5821 static bool
5822 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5823                                 ASTContext &Context) {
5824   if (!PrevDecl)
5825     return false;
5826 
5827   if (!PrevDecl->hasLinkage())
5828     return false;
5829 
5830   if (Context.getLangOpts().CPlusPlus) {
5831     // C++ [basic.link]p6:
5832     //   If there is a visible declaration of an entity with linkage
5833     //   having the same name and type, ignoring entities declared
5834     //   outside the innermost enclosing namespace scope, the block
5835     //   scope declaration declares that same entity and receives the
5836     //   linkage of the previous declaration.
5837     DeclContext *OuterContext = DC->getRedeclContext();
5838     if (!OuterContext->isFunctionOrMethod())
5839       // This rule only applies to block-scope declarations.
5840       return false;
5841 
5842     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5843     if (PrevOuterContext->isRecord())
5844       // We found a member function: ignore it.
5845       return false;
5846 
5847     // Find the innermost enclosing namespace for the new and
5848     // previous declarations.
5849     OuterContext = OuterContext->getEnclosingNamespaceContext();
5850     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5851 
5852     // The previous declaration is in a different namespace, so it
5853     // isn't the same function.
5854     if (!OuterContext->Equals(PrevOuterContext))
5855       return false;
5856   }
5857 
5858   return true;
5859 }
5860 
5861 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5862   CXXScopeSpec &SS = D.getCXXScopeSpec();
5863   if (!SS.isSet()) return;
5864   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5865 }
5866 
5867 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5868   QualType type = decl->getType();
5869   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5870   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5871     // Various kinds of declaration aren't allowed to be __autoreleasing.
5872     unsigned kind = -1U;
5873     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5874       if (var->hasAttr<BlocksAttr>())
5875         kind = 0; // __block
5876       else if (!var->hasLocalStorage())
5877         kind = 1; // global
5878     } else if (isa<ObjCIvarDecl>(decl)) {
5879       kind = 3; // ivar
5880     } else if (isa<FieldDecl>(decl)) {
5881       kind = 2; // field
5882     }
5883 
5884     if (kind != -1U) {
5885       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5886         << kind;
5887     }
5888   } else if (lifetime == Qualifiers::OCL_None) {
5889     // Try to infer lifetime.
5890     if (!type->isObjCLifetimeType())
5891       return false;
5892 
5893     lifetime = type->getObjCARCImplicitLifetime();
5894     type = Context.getLifetimeQualifiedType(type, lifetime);
5895     decl->setType(type);
5896   }
5897 
5898   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5899     // Thread-local variables cannot have lifetime.
5900     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5901         var->getTLSKind()) {
5902       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5903         << var->getType();
5904       return true;
5905     }
5906   }
5907 
5908   return false;
5909 }
5910 
5911 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5912   // Ensure that an auto decl is deduced otherwise the checks below might cache
5913   // the wrong linkage.
5914   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5915 
5916   // 'weak' only applies to declarations with external linkage.
5917   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5918     if (!ND.isExternallyVisible()) {
5919       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5920       ND.dropAttr<WeakAttr>();
5921     }
5922   }
5923   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5924     if (ND.isExternallyVisible()) {
5925       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5926       ND.dropAttr<WeakRefAttr>();
5927       ND.dropAttr<AliasAttr>();
5928     }
5929   }
5930 
5931   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5932     if (VD->hasInit()) {
5933       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5934         assert(VD->isThisDeclarationADefinition() &&
5935                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5936         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5937         VD->dropAttr<AliasAttr>();
5938       }
5939     }
5940   }
5941 
5942   // 'selectany' only applies to externally visible variable declarations.
5943   // It does not apply to functions.
5944   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5945     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5946       S.Diag(Attr->getLocation(),
5947              diag::err_attribute_selectany_non_extern_data);
5948       ND.dropAttr<SelectAnyAttr>();
5949     }
5950   }
5951 
5952   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5953     // dll attributes require external linkage. Static locals may have external
5954     // linkage but still cannot be explicitly imported or exported.
5955     auto *VD = dyn_cast<VarDecl>(&ND);
5956     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5957       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5958         << &ND << Attr;
5959       ND.setInvalidDecl();
5960     }
5961   }
5962 
5963   // Virtual functions cannot be marked as 'notail'.
5964   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5965     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5966       if (MD->isVirtual()) {
5967         S.Diag(ND.getLocation(),
5968                diag::err_invalid_attribute_on_virtual_function)
5969             << Attr;
5970         ND.dropAttr<NotTailCalledAttr>();
5971       }
5972 }
5973 
5974 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5975                                            NamedDecl *NewDecl,
5976                                            bool IsSpecialization,
5977                                            bool IsDefinition) {
5978   if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
5979     return;
5980 
5981   bool IsTemplate = false;
5982   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5983     OldDecl = OldTD->getTemplatedDecl();
5984     IsTemplate = true;
5985     if (!IsSpecialization)
5986       IsDefinition = false;
5987   }
5988   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5989     NewDecl = NewTD->getTemplatedDecl();
5990     IsTemplate = true;
5991   }
5992 
5993   if (!OldDecl || !NewDecl)
5994     return;
5995 
5996   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5997   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5998   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5999   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6000 
6001   // dllimport and dllexport are inheritable attributes so we have to exclude
6002   // inherited attribute instances.
6003   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6004                     (NewExportAttr && !NewExportAttr->isInherited());
6005 
6006   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6007   // the only exception being explicit specializations.
6008   // Implicitly generated declarations are also excluded for now because there
6009   // is no other way to switch these to use dllimport or dllexport.
6010   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6011 
6012   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6013     // Allow with a warning for free functions and global variables.
6014     bool JustWarn = false;
6015     if (!OldDecl->isCXXClassMember()) {
6016       auto *VD = dyn_cast<VarDecl>(OldDecl);
6017       if (VD && !VD->getDescribedVarTemplate())
6018         JustWarn = true;
6019       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6020       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6021         JustWarn = true;
6022     }
6023 
6024     // We cannot change a declaration that's been used because IR has already
6025     // been emitted. Dllimported functions will still work though (modulo
6026     // address equality) as they can use the thunk.
6027     if (OldDecl->isUsed())
6028       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6029         JustWarn = false;
6030 
6031     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6032                                : diag::err_attribute_dll_redeclaration;
6033     S.Diag(NewDecl->getLocation(), DiagID)
6034         << NewDecl
6035         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6036     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6037     if (!JustWarn) {
6038       NewDecl->setInvalidDecl();
6039       return;
6040     }
6041   }
6042 
6043   // A redeclaration is not allowed to drop a dllimport attribute, the only
6044   // exceptions being inline function definitions (except for function
6045   // templates), local extern declarations, qualified friend declarations or
6046   // special MSVC extension: in the last case, the declaration is treated as if
6047   // it were marked dllexport.
6048   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6049   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6050   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6051     // Ignore static data because out-of-line definitions are diagnosed
6052     // separately.
6053     IsStaticDataMember = VD->isStaticDataMember();
6054     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6055                    VarDecl::DeclarationOnly;
6056   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6057     IsInline = FD->isInlined();
6058     IsQualifiedFriend = FD->getQualifier() &&
6059                         FD->getFriendObjectKind() == Decl::FOK_Declared;
6060   }
6061 
6062   if (OldImportAttr && !HasNewAttr &&
6063       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6064       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6065     if (IsMicrosoft && IsDefinition) {
6066       S.Diag(NewDecl->getLocation(),
6067              diag::warn_redeclaration_without_import_attribute)
6068           << NewDecl;
6069       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6070       NewDecl->dropAttr<DLLImportAttr>();
6071       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6072           NewImportAttr->getRange(), S.Context,
6073           NewImportAttr->getSpellingListIndex()));
6074     } else {
6075       S.Diag(NewDecl->getLocation(),
6076              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6077           << NewDecl << OldImportAttr;
6078       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6079       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6080       OldDecl->dropAttr<DLLImportAttr>();
6081       NewDecl->dropAttr<DLLImportAttr>();
6082     }
6083   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6084     // In MinGW, seeing a function declared inline drops the dllimport
6085     // attribute.
6086     OldDecl->dropAttr<DLLImportAttr>();
6087     NewDecl->dropAttr<DLLImportAttr>();
6088     S.Diag(NewDecl->getLocation(),
6089            diag::warn_dllimport_dropped_from_inline_function)
6090         << NewDecl << OldImportAttr;
6091   }
6092 
6093   // A specialization of a class template member function is processed here
6094   // since it's a redeclaration. If the parent class is dllexport, the
6095   // specialization inherits that attribute. This doesn't happen automatically
6096   // since the parent class isn't instantiated until later.
6097   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6098     if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6099         !NewImportAttr && !NewExportAttr) {
6100       if (const DLLExportAttr *ParentExportAttr =
6101               MD->getParent()->getAttr<DLLExportAttr>()) {
6102         DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6103         NewAttr->setInherited(true);
6104         NewDecl->addAttr(NewAttr);
6105       }
6106     }
6107   }
6108 }
6109 
6110 /// Given that we are within the definition of the given function,
6111 /// will that definition behave like C99's 'inline', where the
6112 /// definition is discarded except for optimization purposes?
6113 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6114   // Try to avoid calling GetGVALinkageForFunction.
6115 
6116   // All cases of this require the 'inline' keyword.
6117   if (!FD->isInlined()) return false;
6118 
6119   // This is only possible in C++ with the gnu_inline attribute.
6120   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6121     return false;
6122 
6123   // Okay, go ahead and call the relatively-more-expensive function.
6124   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6125 }
6126 
6127 /// Determine whether a variable is extern "C" prior to attaching
6128 /// an initializer. We can't just call isExternC() here, because that
6129 /// will also compute and cache whether the declaration is externally
6130 /// visible, which might change when we attach the initializer.
6131 ///
6132 /// This can only be used if the declaration is known to not be a
6133 /// redeclaration of an internal linkage declaration.
6134 ///
6135 /// For instance:
6136 ///
6137 ///   auto x = []{};
6138 ///
6139 /// Attaching the initializer here makes this declaration not externally
6140 /// visible, because its type has internal linkage.
6141 ///
6142 /// FIXME: This is a hack.
6143 template<typename T>
6144 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6145   if (S.getLangOpts().CPlusPlus) {
6146     // In C++, the overloadable attribute negates the effects of extern "C".
6147     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6148       return false;
6149 
6150     // So do CUDA's host/device attributes.
6151     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6152                                  D->template hasAttr<CUDAHostAttr>()))
6153       return false;
6154   }
6155   return D->isExternC();
6156 }
6157 
6158 static bool shouldConsiderLinkage(const VarDecl *VD) {
6159   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6160   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6161     return VD->hasExternalStorage();
6162   if (DC->isFileContext())
6163     return true;
6164   if (DC->isRecord())
6165     return false;
6166   llvm_unreachable("Unexpected context");
6167 }
6168 
6169 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6170   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6171   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6172       isa<OMPDeclareReductionDecl>(DC))
6173     return true;
6174   if (DC->isRecord())
6175     return false;
6176   llvm_unreachable("Unexpected context");
6177 }
6178 
6179 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6180                           AttributeList::Kind Kind) {
6181   for (const AttributeList *L = AttrList; L; L = L->getNext())
6182     if (L->getKind() == Kind)
6183       return true;
6184   return false;
6185 }
6186 
6187 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6188                           AttributeList::Kind Kind) {
6189   // Check decl attributes on the DeclSpec.
6190   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6191     return true;
6192 
6193   // Walk the declarator structure, checking decl attributes that were in a type
6194   // position to the decl itself.
6195   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6196     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6197       return true;
6198   }
6199 
6200   // Finally, check attributes on the decl itself.
6201   return hasParsedAttr(S, PD.getAttributes(), Kind);
6202 }
6203 
6204 /// Adjust the \c DeclContext for a function or variable that might be a
6205 /// function-local external declaration.
6206 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6207   if (!DC->isFunctionOrMethod())
6208     return false;
6209 
6210   // If this is a local extern function or variable declared within a function
6211   // template, don't add it into the enclosing namespace scope until it is
6212   // instantiated; it might have a dependent type right now.
6213   if (DC->isDependentContext())
6214     return true;
6215 
6216   // C++11 [basic.link]p7:
6217   //   When a block scope declaration of an entity with linkage is not found to
6218   //   refer to some other declaration, then that entity is a member of the
6219   //   innermost enclosing namespace.
6220   //
6221   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6222   // semantically-enclosing namespace, not a lexically-enclosing one.
6223   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6224     DC = DC->getParent();
6225   return true;
6226 }
6227 
6228 /// \brief Returns true if given declaration has external C language linkage.
6229 static bool isDeclExternC(const Decl *D) {
6230   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6231     return FD->isExternC();
6232   if (const auto *VD = dyn_cast<VarDecl>(D))
6233     return VD->isExternC();
6234 
6235   llvm_unreachable("Unknown type of decl!");
6236 }
6237 
6238 NamedDecl *Sema::ActOnVariableDeclarator(
6239     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6240     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6241     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6242   QualType R = TInfo->getType();
6243   DeclarationName Name = GetNameForDeclarator(D).getName();
6244 
6245   IdentifierInfo *II = Name.getAsIdentifierInfo();
6246 
6247   if (D.isDecompositionDeclarator()) {
6248     // Take the name of the first declarator as our name for diagnostic
6249     // purposes.
6250     auto &Decomp = D.getDecompositionDeclarator();
6251     if (!Decomp.bindings().empty()) {
6252       II = Decomp.bindings()[0].Name;
6253       Name = II;
6254     }
6255   } else if (!II) {
6256     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6257     return nullptr;
6258   }
6259 
6260   if (getLangOpts().OpenCL) {
6261     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6262     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6263     // argument.
6264     if (R->isImageType() || R->isPipeType()) {
6265       Diag(D.getIdentifierLoc(),
6266            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6267           << R;
6268       D.setInvalidType();
6269       return nullptr;
6270     }
6271 
6272     // OpenCL v1.2 s6.9.r:
6273     // The event type cannot be used to declare a program scope variable.
6274     // OpenCL v2.0 s6.9.q:
6275     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6276     if (NULL == S->getParent()) {
6277       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6278         Diag(D.getIdentifierLoc(),
6279              diag::err_invalid_type_for_program_scope_var) << R;
6280         D.setInvalidType();
6281         return nullptr;
6282       }
6283     }
6284 
6285     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6286     QualType NR = R;
6287     while (NR->isPointerType()) {
6288       if (NR->isFunctionPointerType()) {
6289         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6290         D.setInvalidType();
6291         break;
6292       }
6293       NR = NR->getPointeeType();
6294     }
6295 
6296     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6297       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6298       // half array type (unless the cl_khr_fp16 extension is enabled).
6299       if (Context.getBaseElementType(R)->isHalfType()) {
6300         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6301         D.setInvalidType();
6302       }
6303     }
6304 
6305     if (R->isSamplerT()) {
6306       // OpenCL v1.2 s6.9.b p4:
6307       // The sampler type cannot be used with the __local and __global address
6308       // space qualifiers.
6309       if (R.getAddressSpace() == LangAS::opencl_local ||
6310           R.getAddressSpace() == LangAS::opencl_global) {
6311         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6312       }
6313 
6314       // OpenCL v1.2 s6.12.14.1:
6315       // A global sampler must be declared with either the constant address
6316       // space qualifier or with the const qualifier.
6317       if (DC->isTranslationUnit() &&
6318           !(R.getAddressSpace() == LangAS::opencl_constant ||
6319           R.isConstQualified())) {
6320         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6321         D.setInvalidType();
6322       }
6323     }
6324 
6325     // OpenCL v1.2 s6.9.r:
6326     // The event type cannot be used with the __local, __constant and __global
6327     // address space qualifiers.
6328     if (R->isEventT()) {
6329       if (R.getAddressSpace() != LangAS::opencl_private) {
6330         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6331         D.setInvalidType();
6332       }
6333     }
6334   }
6335 
6336   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6337   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6338 
6339   // dllimport globals without explicit storage class are treated as extern. We
6340   // have to change the storage class this early to get the right DeclContext.
6341   if (SC == SC_None && !DC->isRecord() &&
6342       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6343       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6344     SC = SC_Extern;
6345 
6346   DeclContext *OriginalDC = DC;
6347   bool IsLocalExternDecl = SC == SC_Extern &&
6348                            adjustContextForLocalExternDecl(DC);
6349 
6350   if (SCSpec == DeclSpec::SCS_mutable) {
6351     // mutable can only appear on non-static class members, so it's always
6352     // an error here
6353     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6354     D.setInvalidType();
6355     SC = SC_None;
6356   }
6357 
6358   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6359       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6360                               D.getDeclSpec().getStorageClassSpecLoc())) {
6361     // In C++11, the 'register' storage class specifier is deprecated.
6362     // Suppress the warning in system macros, it's used in macros in some
6363     // popular C system headers, such as in glibc's htonl() macro.
6364     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6365          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6366                                    : diag::warn_deprecated_register)
6367       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6368   }
6369 
6370   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6371 
6372   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6373     // C99 6.9p2: The storage-class specifiers auto and register shall not
6374     // appear in the declaration specifiers in an external declaration.
6375     // Global Register+Asm is a GNU extension we support.
6376     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6377       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6378       D.setInvalidType();
6379     }
6380   }
6381 
6382   bool IsMemberSpecialization = false;
6383   bool IsVariableTemplateSpecialization = false;
6384   bool IsPartialSpecialization = false;
6385   bool IsVariableTemplate = false;
6386   VarDecl *NewVD = nullptr;
6387   VarTemplateDecl *NewTemplate = nullptr;
6388   TemplateParameterList *TemplateParams = nullptr;
6389   if (!getLangOpts().CPlusPlus) {
6390     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6391                             D.getIdentifierLoc(), II,
6392                             R, TInfo, SC);
6393 
6394     if (R->getContainedDeducedType())
6395       ParsingInitForAutoVars.insert(NewVD);
6396 
6397     if (D.isInvalidType())
6398       NewVD->setInvalidDecl();
6399   } else {
6400     bool Invalid = false;
6401 
6402     if (DC->isRecord() && !CurContext->isRecord()) {
6403       // This is an out-of-line definition of a static data member.
6404       switch (SC) {
6405       case SC_None:
6406         break;
6407       case SC_Static:
6408         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6409              diag::err_static_out_of_line)
6410           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6411         break;
6412       case SC_Auto:
6413       case SC_Register:
6414       case SC_Extern:
6415         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6416         // to names of variables declared in a block or to function parameters.
6417         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6418         // of class members
6419 
6420         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6421              diag::err_storage_class_for_static_member)
6422           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6423         break;
6424       case SC_PrivateExtern:
6425         llvm_unreachable("C storage class in c++!");
6426       }
6427     }
6428 
6429     if (SC == SC_Static && CurContext->isRecord()) {
6430       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6431         if (RD->isLocalClass())
6432           Diag(D.getIdentifierLoc(),
6433                diag::err_static_data_member_not_allowed_in_local_class)
6434             << Name << RD->getDeclName();
6435 
6436         // C++98 [class.union]p1: If a union contains a static data member,
6437         // the program is ill-formed. C++11 drops this restriction.
6438         if (RD->isUnion())
6439           Diag(D.getIdentifierLoc(),
6440                getLangOpts().CPlusPlus11
6441                  ? diag::warn_cxx98_compat_static_data_member_in_union
6442                  : diag::ext_static_data_member_in_union) << Name;
6443         // We conservatively disallow static data members in anonymous structs.
6444         else if (!RD->getDeclName())
6445           Diag(D.getIdentifierLoc(),
6446                diag::err_static_data_member_not_allowed_in_anon_struct)
6447             << Name << RD->isUnion();
6448       }
6449     }
6450 
6451     // Match up the template parameter lists with the scope specifier, then
6452     // determine whether we have a template or a template specialization.
6453     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6454         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6455         D.getCXXScopeSpec(),
6456         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6457             ? D.getName().TemplateId
6458             : nullptr,
6459         TemplateParamLists,
6460         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6461 
6462     if (TemplateParams) {
6463       if (!TemplateParams->size() &&
6464           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6465         // There is an extraneous 'template<>' for this variable. Complain
6466         // about it, but allow the declaration of the variable.
6467         Diag(TemplateParams->getTemplateLoc(),
6468              diag::err_template_variable_noparams)
6469           << II
6470           << SourceRange(TemplateParams->getTemplateLoc(),
6471                          TemplateParams->getRAngleLoc());
6472         TemplateParams = nullptr;
6473       } else {
6474         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6475           // This is an explicit specialization or a partial specialization.
6476           // FIXME: Check that we can declare a specialization here.
6477           IsVariableTemplateSpecialization = true;
6478           IsPartialSpecialization = TemplateParams->size() > 0;
6479         } else { // if (TemplateParams->size() > 0)
6480           // This is a template declaration.
6481           IsVariableTemplate = true;
6482 
6483           // Check that we can declare a template here.
6484           if (CheckTemplateDeclScope(S, TemplateParams))
6485             return nullptr;
6486 
6487           // Only C++1y supports variable templates (N3651).
6488           Diag(D.getIdentifierLoc(),
6489                getLangOpts().CPlusPlus14
6490                    ? diag::warn_cxx11_compat_variable_template
6491                    : diag::ext_variable_template);
6492         }
6493       }
6494     } else {
6495       assert(
6496           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6497           "should have a 'template<>' for this decl");
6498     }
6499 
6500     if (IsVariableTemplateSpecialization) {
6501       SourceLocation TemplateKWLoc =
6502           TemplateParamLists.size() > 0
6503               ? TemplateParamLists[0]->getTemplateLoc()
6504               : SourceLocation();
6505       DeclResult Res = ActOnVarTemplateSpecialization(
6506           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6507           IsPartialSpecialization);
6508       if (Res.isInvalid())
6509         return nullptr;
6510       NewVD = cast<VarDecl>(Res.get());
6511       AddToScope = false;
6512     } else if (D.isDecompositionDeclarator()) {
6513       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6514                                         D.getIdentifierLoc(), R, TInfo, SC,
6515                                         Bindings);
6516     } else
6517       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6518                               D.getIdentifierLoc(), II, R, TInfo, SC);
6519 
6520     // If this is supposed to be a variable template, create it as such.
6521     if (IsVariableTemplate) {
6522       NewTemplate =
6523           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6524                                   TemplateParams, NewVD);
6525       NewVD->setDescribedVarTemplate(NewTemplate);
6526     }
6527 
6528     // If this decl has an auto type in need of deduction, make a note of the
6529     // Decl so we can diagnose uses of it in its own initializer.
6530     if (R->getContainedDeducedType())
6531       ParsingInitForAutoVars.insert(NewVD);
6532 
6533     if (D.isInvalidType() || Invalid) {
6534       NewVD->setInvalidDecl();
6535       if (NewTemplate)
6536         NewTemplate->setInvalidDecl();
6537     }
6538 
6539     SetNestedNameSpecifier(NewVD, D);
6540 
6541     // If we have any template parameter lists that don't directly belong to
6542     // the variable (matching the scope specifier), store them.
6543     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6544     if (TemplateParamLists.size() > VDTemplateParamLists)
6545       NewVD->setTemplateParameterListsInfo(
6546           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6547 
6548     if (D.getDeclSpec().isConstexprSpecified()) {
6549       NewVD->setConstexpr(true);
6550       // C++1z [dcl.spec.constexpr]p1:
6551       //   A static data member declared with the constexpr specifier is
6552       //   implicitly an inline variable.
6553       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6554         NewVD->setImplicitlyInline();
6555     }
6556 
6557     if (D.getDeclSpec().isConceptSpecified()) {
6558       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6559         VTD->setConcept();
6560 
6561       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6562       // be declared with the thread_local, inline, friend, or constexpr
6563       // specifiers, [...]
6564       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6565         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6566              diag::err_concept_decl_invalid_specifiers)
6567             << 0 << 0;
6568         NewVD->setInvalidDecl(true);
6569       }
6570 
6571       if (D.getDeclSpec().isConstexprSpecified()) {
6572         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6573              diag::err_concept_decl_invalid_specifiers)
6574             << 0 << 3;
6575         NewVD->setInvalidDecl(true);
6576       }
6577 
6578       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6579       // applied only to the definition of a function template or variable
6580       // template, declared in namespace scope.
6581       if (IsVariableTemplateSpecialization) {
6582         Diag(D.getDeclSpec().getConceptSpecLoc(),
6583              diag::err_concept_specified_specialization)
6584             << (IsPartialSpecialization ? 2 : 1);
6585       }
6586 
6587       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6588       // following restrictions:
6589       // - The declared type shall have the type bool.
6590       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6591           !NewVD->isInvalidDecl()) {
6592         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6593         NewVD->setInvalidDecl(true);
6594       }
6595     }
6596   }
6597 
6598   if (D.getDeclSpec().isInlineSpecified()) {
6599     if (!getLangOpts().CPlusPlus) {
6600       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6601           << 0;
6602     } else if (CurContext->isFunctionOrMethod()) {
6603       // 'inline' is not allowed on block scope variable declaration.
6604       Diag(D.getDeclSpec().getInlineSpecLoc(),
6605            diag::err_inline_declaration_block_scope) << Name
6606         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6607     } else {
6608       Diag(D.getDeclSpec().getInlineSpecLoc(),
6609            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6610                                      : diag::ext_inline_variable);
6611       NewVD->setInlineSpecified();
6612     }
6613   }
6614 
6615   // Set the lexical context. If the declarator has a C++ scope specifier, the
6616   // lexical context will be different from the semantic context.
6617   NewVD->setLexicalDeclContext(CurContext);
6618   if (NewTemplate)
6619     NewTemplate->setLexicalDeclContext(CurContext);
6620 
6621   if (IsLocalExternDecl) {
6622     if (D.isDecompositionDeclarator())
6623       for (auto *B : Bindings)
6624         B->setLocalExternDecl();
6625     else
6626       NewVD->setLocalExternDecl();
6627   }
6628 
6629   bool EmitTLSUnsupportedError = false;
6630   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6631     // C++11 [dcl.stc]p4:
6632     //   When thread_local is applied to a variable of block scope the
6633     //   storage-class-specifier static is implied if it does not appear
6634     //   explicitly.
6635     // Core issue: 'static' is not implied if the variable is declared
6636     //   'extern'.
6637     if (NewVD->hasLocalStorage() &&
6638         (SCSpec != DeclSpec::SCS_unspecified ||
6639          TSCS != DeclSpec::TSCS_thread_local ||
6640          !DC->isFunctionOrMethod()))
6641       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6642            diag::err_thread_non_global)
6643         << DeclSpec::getSpecifierName(TSCS);
6644     else if (!Context.getTargetInfo().isTLSSupported()) {
6645       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6646         // Postpone error emission until we've collected attributes required to
6647         // figure out whether it's a host or device variable and whether the
6648         // error should be ignored.
6649         EmitTLSUnsupportedError = true;
6650         // We still need to mark the variable as TLS so it shows up in AST with
6651         // proper storage class for other tools to use even if we're not going
6652         // to emit any code for it.
6653         NewVD->setTSCSpec(TSCS);
6654       } else
6655         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6656              diag::err_thread_unsupported);
6657     } else
6658       NewVD->setTSCSpec(TSCS);
6659   }
6660 
6661   // C99 6.7.4p3
6662   //   An inline definition of a function with external linkage shall
6663   //   not contain a definition of a modifiable object with static or
6664   //   thread storage duration...
6665   // We only apply this when the function is required to be defined
6666   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6667   // that a local variable with thread storage duration still has to
6668   // be marked 'static'.  Also note that it's possible to get these
6669   // semantics in C++ using __attribute__((gnu_inline)).
6670   if (SC == SC_Static && S->getFnParent() != nullptr &&
6671       !NewVD->getType().isConstQualified()) {
6672     FunctionDecl *CurFD = getCurFunctionDecl();
6673     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6674       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6675            diag::warn_static_local_in_extern_inline);
6676       MaybeSuggestAddingStaticToDecl(CurFD);
6677     }
6678   }
6679 
6680   if (D.getDeclSpec().isModulePrivateSpecified()) {
6681     if (IsVariableTemplateSpecialization)
6682       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6683           << (IsPartialSpecialization ? 1 : 0)
6684           << FixItHint::CreateRemoval(
6685                  D.getDeclSpec().getModulePrivateSpecLoc());
6686     else if (IsMemberSpecialization)
6687       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6688         << 2
6689         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6690     else if (NewVD->hasLocalStorage())
6691       Diag(NewVD->getLocation(), diag::err_module_private_local)
6692         << 0 << NewVD->getDeclName()
6693         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6694         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6695     else {
6696       NewVD->setModulePrivate();
6697       if (NewTemplate)
6698         NewTemplate->setModulePrivate();
6699       for (auto *B : Bindings)
6700         B->setModulePrivate();
6701     }
6702   }
6703 
6704   // Handle attributes prior to checking for duplicates in MergeVarDecl
6705   ProcessDeclAttributes(S, NewVD, D);
6706 
6707   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6708     if (EmitTLSUnsupportedError &&
6709         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6710          (getLangOpts().OpenMPIsDevice &&
6711           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6712       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6713            diag::err_thread_unsupported);
6714     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6715     // storage [duration]."
6716     if (SC == SC_None && S->getFnParent() != nullptr &&
6717         (NewVD->hasAttr<CUDASharedAttr>() ||
6718          NewVD->hasAttr<CUDAConstantAttr>())) {
6719       NewVD->setStorageClass(SC_Static);
6720     }
6721   }
6722 
6723   // Ensure that dllimport globals without explicit storage class are treated as
6724   // extern. The storage class is set above using parsed attributes. Now we can
6725   // check the VarDecl itself.
6726   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6727          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6728          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6729 
6730   // In auto-retain/release, infer strong retension for variables of
6731   // retainable type.
6732   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6733     NewVD->setInvalidDecl();
6734 
6735   // Handle GNU asm-label extension (encoded as an attribute).
6736   if (Expr *E = (Expr*)D.getAsmLabel()) {
6737     // The parser guarantees this is a string.
6738     StringLiteral *SE = cast<StringLiteral>(E);
6739     StringRef Label = SE->getString();
6740     if (S->getFnParent() != nullptr) {
6741       switch (SC) {
6742       case SC_None:
6743       case SC_Auto:
6744         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6745         break;
6746       case SC_Register:
6747         // Local Named register
6748         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6749             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6750           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6751         break;
6752       case SC_Static:
6753       case SC_Extern:
6754       case SC_PrivateExtern:
6755         break;
6756       }
6757     } else if (SC == SC_Register) {
6758       // Global Named register
6759       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6760         const auto &TI = Context.getTargetInfo();
6761         bool HasSizeMismatch;
6762 
6763         if (!TI.isValidGCCRegisterName(Label))
6764           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6765         else if (!TI.validateGlobalRegisterVariable(Label,
6766                                                     Context.getTypeSize(R),
6767                                                     HasSizeMismatch))
6768           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6769         else if (HasSizeMismatch)
6770           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6771       }
6772 
6773       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6774         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6775         NewVD->setInvalidDecl(true);
6776       }
6777     }
6778 
6779     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6780                                                 Context, Label, 0));
6781   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6782     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6783       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6784     if (I != ExtnameUndeclaredIdentifiers.end()) {
6785       if (isDeclExternC(NewVD)) {
6786         NewVD->addAttr(I->second);
6787         ExtnameUndeclaredIdentifiers.erase(I);
6788       } else
6789         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6790             << /*Variable*/1 << NewVD;
6791     }
6792   }
6793 
6794   // Find the shadowed declaration before filtering for scope.
6795   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6796                                 ? getShadowedDeclaration(NewVD, Previous)
6797                                 : nullptr;
6798 
6799   // Don't consider existing declarations that are in a different
6800   // scope and are out-of-semantic-context declarations (if the new
6801   // declaration has linkage).
6802   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6803                        D.getCXXScopeSpec().isNotEmpty() ||
6804                        IsMemberSpecialization ||
6805                        IsVariableTemplateSpecialization);
6806 
6807   // Check whether the previous declaration is in the same block scope. This
6808   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6809   if (getLangOpts().CPlusPlus &&
6810       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6811     NewVD->setPreviousDeclInSameBlockScope(
6812         Previous.isSingleResult() && !Previous.isShadowed() &&
6813         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6814 
6815   if (!getLangOpts().CPlusPlus) {
6816     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6817   } else {
6818     // If this is an explicit specialization of a static data member, check it.
6819     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6820         CheckMemberSpecialization(NewVD, Previous))
6821       NewVD->setInvalidDecl();
6822 
6823     // Merge the decl with the existing one if appropriate.
6824     if (!Previous.empty()) {
6825       if (Previous.isSingleResult() &&
6826           isa<FieldDecl>(Previous.getFoundDecl()) &&
6827           D.getCXXScopeSpec().isSet()) {
6828         // The user tried to define a non-static data member
6829         // out-of-line (C++ [dcl.meaning]p1).
6830         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6831           << D.getCXXScopeSpec().getRange();
6832         Previous.clear();
6833         NewVD->setInvalidDecl();
6834       }
6835     } else if (D.getCXXScopeSpec().isSet()) {
6836       // No previous declaration in the qualifying scope.
6837       Diag(D.getIdentifierLoc(), diag::err_no_member)
6838         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6839         << D.getCXXScopeSpec().getRange();
6840       NewVD->setInvalidDecl();
6841     }
6842 
6843     if (!IsVariableTemplateSpecialization)
6844       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6845 
6846     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6847     // an explicit specialization (14.8.3) or a partial specialization of a
6848     // concept definition.
6849     if (IsVariableTemplateSpecialization &&
6850         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6851         Previous.isSingleResult()) {
6852       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6853       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6854         if (VarTmpl->isConcept()) {
6855           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6856               << 1                            /*variable*/
6857               << (IsPartialSpecialization ? 2 /*partially specialized*/
6858                                           : 1 /*explicitly specialized*/);
6859           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6860           NewVD->setInvalidDecl();
6861         }
6862       }
6863     }
6864 
6865     if (NewTemplate) {
6866       VarTemplateDecl *PrevVarTemplate =
6867           NewVD->getPreviousDecl()
6868               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6869               : nullptr;
6870 
6871       // Check the template parameter list of this declaration, possibly
6872       // merging in the template parameter list from the previous variable
6873       // template declaration.
6874       if (CheckTemplateParameterList(
6875               TemplateParams,
6876               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6877                               : nullptr,
6878               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6879                DC->isDependentContext())
6880                   ? TPC_ClassTemplateMember
6881                   : TPC_VarTemplate))
6882         NewVD->setInvalidDecl();
6883 
6884       // If we are providing an explicit specialization of a static variable
6885       // template, make a note of that.
6886       if (PrevVarTemplate &&
6887           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6888         PrevVarTemplate->setMemberSpecialization();
6889     }
6890   }
6891 
6892   // Diagnose shadowed variables iff this isn't a redeclaration.
6893   if (ShadowedDecl && !D.isRedeclaration())
6894     CheckShadow(NewVD, ShadowedDecl, Previous);
6895 
6896   ProcessPragmaWeak(S, NewVD);
6897 
6898   // If this is the first declaration of an extern C variable, update
6899   // the map of such variables.
6900   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6901       isIncompleteDeclExternC(*this, NewVD))
6902     RegisterLocallyScopedExternCDecl(NewVD, S);
6903 
6904   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6905     Decl *ManglingContextDecl;
6906     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6907             NewVD->getDeclContext(), ManglingContextDecl)) {
6908       Context.setManglingNumber(
6909           NewVD, MCtx->getManglingNumber(
6910                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6911       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6912     }
6913   }
6914 
6915   // Special handling of variable named 'main'.
6916   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6917       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6918       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6919 
6920     // C++ [basic.start.main]p3
6921     // A program that declares a variable main at global scope is ill-formed.
6922     if (getLangOpts().CPlusPlus)
6923       Diag(D.getLocStart(), diag::err_main_global_variable);
6924 
6925     // In C, and external-linkage variable named main results in undefined
6926     // behavior.
6927     else if (NewVD->hasExternalFormalLinkage())
6928       Diag(D.getLocStart(), diag::warn_main_redefined);
6929   }
6930 
6931   if (D.isRedeclaration() && !Previous.empty()) {
6932     checkDLLAttributeRedeclaration(
6933         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6934         IsMemberSpecialization, D.isFunctionDefinition());
6935   }
6936 
6937   if (NewTemplate) {
6938     if (NewVD->isInvalidDecl())
6939       NewTemplate->setInvalidDecl();
6940     ActOnDocumentableDecl(NewTemplate);
6941     return NewTemplate;
6942   }
6943 
6944   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6945     CompleteMemberSpecialization(NewVD, Previous);
6946 
6947   return NewVD;
6948 }
6949 
6950 /// Enum describing the %select options in diag::warn_decl_shadow.
6951 enum ShadowedDeclKind {
6952   SDK_Local,
6953   SDK_Global,
6954   SDK_StaticMember,
6955   SDK_Field,
6956   SDK_Typedef,
6957   SDK_Using
6958 };
6959 
6960 /// Determine what kind of declaration we're shadowing.
6961 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6962                                                 const DeclContext *OldDC) {
6963   if (isa<TypeAliasDecl>(ShadowedDecl))
6964     return SDK_Using;
6965   else if (isa<TypedefDecl>(ShadowedDecl))
6966     return SDK_Typedef;
6967   else if (isa<RecordDecl>(OldDC))
6968     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6969 
6970   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6971 }
6972 
6973 /// Return the location of the capture if the given lambda captures the given
6974 /// variable \p VD, or an invalid source location otherwise.
6975 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6976                                          const VarDecl *VD) {
6977   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6978     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6979       return Capture.getLocation();
6980   }
6981   return SourceLocation();
6982 }
6983 
6984 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6985                                      const LookupResult &R) {
6986   // Only diagnose if we're shadowing an unambiguous field or variable.
6987   if (R.getResultKind() != LookupResult::Found)
6988     return false;
6989 
6990   // Return false if warning is ignored.
6991   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6992 }
6993 
6994 /// \brief Return the declaration shadowed by the given variable \p D, or null
6995 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6996 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6997                                         const LookupResult &R) {
6998   if (!shouldWarnIfShadowedDecl(Diags, R))
6999     return nullptr;
7000 
7001   // Don't diagnose declarations at file scope.
7002   if (D->hasGlobalStorage())
7003     return nullptr;
7004 
7005   NamedDecl *ShadowedDecl = R.getFoundDecl();
7006   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7007              ? ShadowedDecl
7008              : nullptr;
7009 }
7010 
7011 /// \brief Return the declaration shadowed by the given typedef \p D, or null
7012 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7013 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7014                                         const LookupResult &R) {
7015   // Don't warn if typedef declaration is part of a class
7016   if (D->getDeclContext()->isRecord())
7017     return nullptr;
7018 
7019   if (!shouldWarnIfShadowedDecl(Diags, R))
7020     return nullptr;
7021 
7022   NamedDecl *ShadowedDecl = R.getFoundDecl();
7023   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7024 }
7025 
7026 /// \brief Diagnose variable or built-in function shadowing.  Implements
7027 /// -Wshadow.
7028 ///
7029 /// This method is called whenever a VarDecl is added to a "useful"
7030 /// scope.
7031 ///
7032 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7033 /// \param R the lookup of the name
7034 ///
7035 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7036                        const LookupResult &R) {
7037   DeclContext *NewDC = D->getDeclContext();
7038 
7039   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7040     // Fields are not shadowed by variables in C++ static methods.
7041     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7042       if (MD->isStatic())
7043         return;
7044 
7045     // Fields shadowed by constructor parameters are a special case. Usually
7046     // the constructor initializes the field with the parameter.
7047     if (isa<CXXConstructorDecl>(NewDC))
7048       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7049         // Remember that this was shadowed so we can either warn about its
7050         // modification or its existence depending on warning settings.
7051         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7052         return;
7053       }
7054   }
7055 
7056   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7057     if (shadowedVar->isExternC()) {
7058       // For shadowing external vars, make sure that we point to the global
7059       // declaration, not a locally scoped extern declaration.
7060       for (auto I : shadowedVar->redecls())
7061         if (I->isFileVarDecl()) {
7062           ShadowedDecl = I;
7063           break;
7064         }
7065     }
7066 
7067   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7068 
7069   unsigned WarningDiag = diag::warn_decl_shadow;
7070   SourceLocation CaptureLoc;
7071   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7072       isa<CXXMethodDecl>(NewDC)) {
7073     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7074       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7075         if (RD->getLambdaCaptureDefault() == LCD_None) {
7076           // Try to avoid warnings for lambdas with an explicit capture list.
7077           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7078           // Warn only when the lambda captures the shadowed decl explicitly.
7079           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7080           if (CaptureLoc.isInvalid())
7081             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7082         } else {
7083           // Remember that this was shadowed so we can avoid the warning if the
7084           // shadowed decl isn't captured and the warning settings allow it.
7085           cast<LambdaScopeInfo>(getCurFunction())
7086               ->ShadowingDecls.push_back(
7087                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7088           return;
7089         }
7090       }
7091 
7092       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7093         // A variable can't shadow a local variable in an enclosing scope, if
7094         // they are separated by a non-capturing declaration context.
7095         for (DeclContext *ParentDC = NewDC;
7096              ParentDC && !ParentDC->Equals(OldDC);
7097              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7098           // Only block literals, captured statements, and lambda expressions
7099           // can capture; other scopes don't.
7100           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7101               !isLambdaCallOperator(ParentDC)) {
7102             return;
7103           }
7104         }
7105       }
7106     }
7107   }
7108 
7109   // Only warn about certain kinds of shadowing for class members.
7110   if (NewDC && NewDC->isRecord()) {
7111     // In particular, don't warn about shadowing non-class members.
7112     if (!OldDC->isRecord())
7113       return;
7114 
7115     // TODO: should we warn about static data members shadowing
7116     // static data members from base classes?
7117 
7118     // TODO: don't diagnose for inaccessible shadowed members.
7119     // This is hard to do perfectly because we might friend the
7120     // shadowing context, but that's just a false negative.
7121   }
7122 
7123 
7124   DeclarationName Name = R.getLookupName();
7125 
7126   // Emit warning and note.
7127   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7128     return;
7129   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7130   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7131   if (!CaptureLoc.isInvalid())
7132     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7133         << Name << /*explicitly*/ 1;
7134   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7135 }
7136 
7137 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7138 /// when these variables are captured by the lambda.
7139 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7140   for (const auto &Shadow : LSI->ShadowingDecls) {
7141     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7142     // Try to avoid the warning when the shadowed decl isn't captured.
7143     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7144     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7145     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7146                                        ? diag::warn_decl_shadow_uncaptured_local
7147                                        : diag::warn_decl_shadow)
7148         << Shadow.VD->getDeclName()
7149         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7150     if (!CaptureLoc.isInvalid())
7151       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7152           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7153     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7154   }
7155 }
7156 
7157 /// \brief Check -Wshadow without the advantage of a previous lookup.
7158 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7159   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7160     return;
7161 
7162   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7163                  Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7164   LookupName(R, S);
7165   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7166     CheckShadow(D, ShadowedDecl, R);
7167 }
7168 
7169 /// Check if 'E', which is an expression that is about to be modified, refers
7170 /// to a constructor parameter that shadows a field.
7171 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7172   // Quickly ignore expressions that can't be shadowing ctor parameters.
7173   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7174     return;
7175   E = E->IgnoreParenImpCasts();
7176   auto *DRE = dyn_cast<DeclRefExpr>(E);
7177   if (!DRE)
7178     return;
7179   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7180   auto I = ShadowingDecls.find(D);
7181   if (I == ShadowingDecls.end())
7182     return;
7183   const NamedDecl *ShadowedDecl = I->second;
7184   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7185   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7186   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7187   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7188 
7189   // Avoid issuing multiple warnings about the same decl.
7190   ShadowingDecls.erase(I);
7191 }
7192 
7193 /// Check for conflict between this global or extern "C" declaration and
7194 /// previous global or extern "C" declarations. This is only used in C++.
7195 template<typename T>
7196 static bool checkGlobalOrExternCConflict(
7197     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7198   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7199   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7200 
7201   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7202     // The common case: this global doesn't conflict with any extern "C"
7203     // declaration.
7204     return false;
7205   }
7206 
7207   if (Prev) {
7208     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7209       // Both the old and new declarations have C language linkage. This is a
7210       // redeclaration.
7211       Previous.clear();
7212       Previous.addDecl(Prev);
7213       return true;
7214     }
7215 
7216     // This is a global, non-extern "C" declaration, and there is a previous
7217     // non-global extern "C" declaration. Diagnose if this is a variable
7218     // declaration.
7219     if (!isa<VarDecl>(ND))
7220       return false;
7221   } else {
7222     // The declaration is extern "C". Check for any declaration in the
7223     // translation unit which might conflict.
7224     if (IsGlobal) {
7225       // We have already performed the lookup into the translation unit.
7226       IsGlobal = false;
7227       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7228            I != E; ++I) {
7229         if (isa<VarDecl>(*I)) {
7230           Prev = *I;
7231           break;
7232         }
7233       }
7234     } else {
7235       DeclContext::lookup_result R =
7236           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7237       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7238            I != E; ++I) {
7239         if (isa<VarDecl>(*I)) {
7240           Prev = *I;
7241           break;
7242         }
7243         // FIXME: If we have any other entity with this name in global scope,
7244         // the declaration is ill-formed, but that is a defect: it breaks the
7245         // 'stat' hack, for instance. Only variables can have mangled name
7246         // clashes with extern "C" declarations, so only they deserve a
7247         // diagnostic.
7248       }
7249     }
7250 
7251     if (!Prev)
7252       return false;
7253   }
7254 
7255   // Use the first declaration's location to ensure we point at something which
7256   // is lexically inside an extern "C" linkage-spec.
7257   assert(Prev && "should have found a previous declaration to diagnose");
7258   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7259     Prev = FD->getFirstDecl();
7260   else
7261     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7262 
7263   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7264     << IsGlobal << ND;
7265   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7266     << IsGlobal;
7267   return false;
7268 }
7269 
7270 /// Apply special rules for handling extern "C" declarations. Returns \c true
7271 /// if we have found that this is a redeclaration of some prior entity.
7272 ///
7273 /// Per C++ [dcl.link]p6:
7274 ///   Two declarations [for a function or variable] with C language linkage
7275 ///   with the same name that appear in different scopes refer to the same
7276 ///   [entity]. An entity with C language linkage shall not be declared with
7277 ///   the same name as an entity in global scope.
7278 template<typename T>
7279 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7280                                                   LookupResult &Previous) {
7281   if (!S.getLangOpts().CPlusPlus) {
7282     // In C, when declaring a global variable, look for a corresponding 'extern'
7283     // variable declared in function scope. We don't need this in C++, because
7284     // we find local extern decls in the surrounding file-scope DeclContext.
7285     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7286       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7287         Previous.clear();
7288         Previous.addDecl(Prev);
7289         return true;
7290       }
7291     }
7292     return false;
7293   }
7294 
7295   // A declaration in the translation unit can conflict with an extern "C"
7296   // declaration.
7297   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7298     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7299 
7300   // An extern "C" declaration can conflict with a declaration in the
7301   // translation unit or can be a redeclaration of an extern "C" declaration
7302   // in another scope.
7303   if (isIncompleteDeclExternC(S,ND))
7304     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7305 
7306   // Neither global nor extern "C": nothing to do.
7307   return false;
7308 }
7309 
7310 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7311   // If the decl is already known invalid, don't check it.
7312   if (NewVD->isInvalidDecl())
7313     return;
7314 
7315   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7316   QualType T = TInfo->getType();
7317 
7318   // Defer checking an 'auto' type until its initializer is attached.
7319   if (T->isUndeducedType())
7320     return;
7321 
7322   if (NewVD->hasAttrs())
7323     CheckAlignasUnderalignment(NewVD);
7324 
7325   if (T->isObjCObjectType()) {
7326     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7327       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7328     T = Context.getObjCObjectPointerType(T);
7329     NewVD->setType(T);
7330   }
7331 
7332   // Emit an error if an address space was applied to decl with local storage.
7333   // This includes arrays of objects with address space qualifiers, but not
7334   // automatic variables that point to other address spaces.
7335   // ISO/IEC TR 18037 S5.1.2
7336   if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7337       T.getAddressSpace() != LangAS::Default) {
7338     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7339     NewVD->setInvalidDecl();
7340     return;
7341   }
7342 
7343   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7344   // scope.
7345   if (getLangOpts().OpenCLVersion == 120 &&
7346       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7347       NewVD->isStaticLocal()) {
7348     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7349     NewVD->setInvalidDecl();
7350     return;
7351   }
7352 
7353   if (getLangOpts().OpenCL) {
7354     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7355     if (NewVD->hasAttr<BlocksAttr>()) {
7356       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7357       return;
7358     }
7359 
7360     if (T->isBlockPointerType()) {
7361       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7362       // can't use 'extern' storage class.
7363       if (!T.isConstQualified()) {
7364         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7365             << 0 /*const*/;
7366         NewVD->setInvalidDecl();
7367         return;
7368       }
7369       if (NewVD->hasExternalStorage()) {
7370         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7371         NewVD->setInvalidDecl();
7372         return;
7373       }
7374     }
7375     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7376     // __constant address space.
7377     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7378     // variables inside a function can also be declared in the global
7379     // address space.
7380     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7381         NewVD->hasExternalStorage()) {
7382       if (!T->isSamplerT() &&
7383           !(T.getAddressSpace() == LangAS::opencl_constant ||
7384             (T.getAddressSpace() == LangAS::opencl_global &&
7385              getLangOpts().OpenCLVersion == 200))) {
7386         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7387         if (getLangOpts().OpenCLVersion == 200)
7388           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7389               << Scope << "global or constant";
7390         else
7391           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7392               << Scope << "constant";
7393         NewVD->setInvalidDecl();
7394         return;
7395       }
7396     } else {
7397       if (T.getAddressSpace() == LangAS::opencl_global) {
7398         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7399             << 1 /*is any function*/ << "global";
7400         NewVD->setInvalidDecl();
7401         return;
7402       }
7403       if (T.getAddressSpace() == LangAS::opencl_constant ||
7404           T.getAddressSpace() == LangAS::opencl_local) {
7405         FunctionDecl *FD = getCurFunctionDecl();
7406         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7407         // in functions.
7408         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7409           if (T.getAddressSpace() == LangAS::opencl_constant)
7410             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7411                 << 0 /*non-kernel only*/ << "constant";
7412           else
7413             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7414                 << 0 /*non-kernel only*/ << "local";
7415           NewVD->setInvalidDecl();
7416           return;
7417         }
7418         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7419         // in the outermost scope of a kernel function.
7420         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7421           if (!getCurScope()->isFunctionScope()) {
7422             if (T.getAddressSpace() == LangAS::opencl_constant)
7423               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7424                   << "constant";
7425             else
7426               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7427                   << "local";
7428             NewVD->setInvalidDecl();
7429             return;
7430           }
7431         }
7432       } else if (T.getAddressSpace() != LangAS::opencl_private) {
7433         // Do not allow other address spaces on automatic variable.
7434         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7435         NewVD->setInvalidDecl();
7436         return;
7437       }
7438     }
7439   }
7440 
7441   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7442       && !NewVD->hasAttr<BlocksAttr>()) {
7443     if (getLangOpts().getGC() != LangOptions::NonGC)
7444       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7445     else {
7446       assert(!getLangOpts().ObjCAutoRefCount);
7447       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7448     }
7449   }
7450 
7451   bool isVM = T->isVariablyModifiedType();
7452   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7453       NewVD->hasAttr<BlocksAttr>())
7454     getCurFunction()->setHasBranchProtectedScope();
7455 
7456   if ((isVM && NewVD->hasLinkage()) ||
7457       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7458     bool SizeIsNegative;
7459     llvm::APSInt Oversized;
7460     TypeSourceInfo *FixedTInfo =
7461       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7462                                                     SizeIsNegative, Oversized);
7463     if (!FixedTInfo && T->isVariableArrayType()) {
7464       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7465       // FIXME: This won't give the correct result for
7466       // int a[10][n];
7467       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7468 
7469       if (NewVD->isFileVarDecl())
7470         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7471         << SizeRange;
7472       else if (NewVD->isStaticLocal())
7473         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7474         << SizeRange;
7475       else
7476         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7477         << SizeRange;
7478       NewVD->setInvalidDecl();
7479       return;
7480     }
7481 
7482     if (!FixedTInfo) {
7483       if (NewVD->isFileVarDecl())
7484         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7485       else
7486         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7487       NewVD->setInvalidDecl();
7488       return;
7489     }
7490 
7491     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7492     NewVD->setType(FixedTInfo->getType());
7493     NewVD->setTypeSourceInfo(FixedTInfo);
7494   }
7495 
7496   if (T->isVoidType()) {
7497     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7498     //                    of objects and functions.
7499     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7500       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7501         << T;
7502       NewVD->setInvalidDecl();
7503       return;
7504     }
7505   }
7506 
7507   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7508     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7509     NewVD->setInvalidDecl();
7510     return;
7511   }
7512 
7513   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7514     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7515     NewVD->setInvalidDecl();
7516     return;
7517   }
7518 
7519   if (NewVD->isConstexpr() && !T->isDependentType() &&
7520       RequireLiteralType(NewVD->getLocation(), T,
7521                          diag::err_constexpr_var_non_literal)) {
7522     NewVD->setInvalidDecl();
7523     return;
7524   }
7525 }
7526 
7527 /// \brief Perform semantic checking on a newly-created variable
7528 /// declaration.
7529 ///
7530 /// This routine performs all of the type-checking required for a
7531 /// variable declaration once it has been built. It is used both to
7532 /// check variables after they have been parsed and their declarators
7533 /// have been translated into a declaration, and to check variables
7534 /// that have been instantiated from a template.
7535 ///
7536 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7537 ///
7538 /// Returns true if the variable declaration is a redeclaration.
7539 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7540   CheckVariableDeclarationType(NewVD);
7541 
7542   // If the decl is already known invalid, don't check it.
7543   if (NewVD->isInvalidDecl())
7544     return false;
7545 
7546   // If we did not find anything by this name, look for a non-visible
7547   // extern "C" declaration with the same name.
7548   if (Previous.empty() &&
7549       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7550     Previous.setShadowed();
7551 
7552   if (!Previous.empty()) {
7553     MergeVarDecl(NewVD, Previous);
7554     return true;
7555   }
7556   return false;
7557 }
7558 
7559 namespace {
7560 struct FindOverriddenMethod {
7561   Sema *S;
7562   CXXMethodDecl *Method;
7563 
7564   /// Member lookup function that determines whether a given C++
7565   /// method overrides a method in a base class, to be used with
7566   /// CXXRecordDecl::lookupInBases().
7567   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7568     RecordDecl *BaseRecord =
7569         Specifier->getType()->getAs<RecordType>()->getDecl();
7570 
7571     DeclarationName Name = Method->getDeclName();
7572 
7573     // FIXME: Do we care about other names here too?
7574     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7575       // We really want to find the base class destructor here.
7576       QualType T = S->Context.getTypeDeclType(BaseRecord);
7577       CanQualType CT = S->Context.getCanonicalType(T);
7578 
7579       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7580     }
7581 
7582     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7583          Path.Decls = Path.Decls.slice(1)) {
7584       NamedDecl *D = Path.Decls.front();
7585       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7586         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7587           return true;
7588       }
7589     }
7590 
7591     return false;
7592   }
7593 };
7594 
7595 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7596 } // end anonymous namespace
7597 
7598 /// \brief Report an error regarding overriding, along with any relevant
7599 /// overriden methods.
7600 ///
7601 /// \param DiagID the primary error to report.
7602 /// \param MD the overriding method.
7603 /// \param OEK which overrides to include as notes.
7604 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7605                             OverrideErrorKind OEK = OEK_All) {
7606   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7607   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7608                                       E = MD->end_overridden_methods();
7609        I != E; ++I) {
7610     // This check (& the OEK parameter) could be replaced by a predicate, but
7611     // without lambdas that would be overkill. This is still nicer than writing
7612     // out the diag loop 3 times.
7613     if ((OEK == OEK_All) ||
7614         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7615         (OEK == OEK_Deleted && (*I)->isDeleted()))
7616       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7617   }
7618 }
7619 
7620 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7621 /// and if so, check that it's a valid override and remember it.
7622 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7623   // Look for methods in base classes that this method might override.
7624   CXXBasePaths Paths;
7625   FindOverriddenMethod FOM;
7626   FOM.Method = MD;
7627   FOM.S = this;
7628   bool hasDeletedOverridenMethods = false;
7629   bool hasNonDeletedOverridenMethods = false;
7630   bool AddedAny = false;
7631   if (DC->lookupInBases(FOM, Paths)) {
7632     for (auto *I : Paths.found_decls()) {
7633       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7634         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7635         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7636             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7637             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7638             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7639           hasDeletedOverridenMethods |= OldMD->isDeleted();
7640           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7641           AddedAny = true;
7642         }
7643       }
7644     }
7645   }
7646 
7647   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7648     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7649   }
7650   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7651     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7652   }
7653 
7654   return AddedAny;
7655 }
7656 
7657 namespace {
7658   // Struct for holding all of the extra arguments needed by
7659   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7660   struct ActOnFDArgs {
7661     Scope *S;
7662     Declarator &D;
7663     MultiTemplateParamsArg TemplateParamLists;
7664     bool AddToScope;
7665   };
7666 } // end anonymous namespace
7667 
7668 namespace {
7669 
7670 // Callback to only accept typo corrections that have a non-zero edit distance.
7671 // Also only accept corrections that have the same parent decl.
7672 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7673  public:
7674   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7675                             CXXRecordDecl *Parent)
7676       : Context(Context), OriginalFD(TypoFD),
7677         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7678 
7679   bool ValidateCandidate(const TypoCorrection &candidate) override {
7680     if (candidate.getEditDistance() == 0)
7681       return false;
7682 
7683     SmallVector<unsigned, 1> MismatchedParams;
7684     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7685                                           CDeclEnd = candidate.end();
7686          CDecl != CDeclEnd; ++CDecl) {
7687       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7688 
7689       if (FD && !FD->hasBody() &&
7690           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7691         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7692           CXXRecordDecl *Parent = MD->getParent();
7693           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7694             return true;
7695         } else if (!ExpectedParent) {
7696           return true;
7697         }
7698       }
7699     }
7700 
7701     return false;
7702   }
7703 
7704  private:
7705   ASTContext &Context;
7706   FunctionDecl *OriginalFD;
7707   CXXRecordDecl *ExpectedParent;
7708 };
7709 
7710 } // end anonymous namespace
7711 
7712 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7713   TypoCorrectedFunctionDefinitions.insert(F);
7714 }
7715 
7716 /// \brief Generate diagnostics for an invalid function redeclaration.
7717 ///
7718 /// This routine handles generating the diagnostic messages for an invalid
7719 /// function redeclaration, including finding possible similar declarations
7720 /// or performing typo correction if there are no previous declarations with
7721 /// the same name.
7722 ///
7723 /// Returns a NamedDecl iff typo correction was performed and substituting in
7724 /// the new declaration name does not cause new errors.
7725 static NamedDecl *DiagnoseInvalidRedeclaration(
7726     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7727     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7728   DeclarationName Name = NewFD->getDeclName();
7729   DeclContext *NewDC = NewFD->getDeclContext();
7730   SmallVector<unsigned, 1> MismatchedParams;
7731   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7732   TypoCorrection Correction;
7733   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7734   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7735                                    : diag::err_member_decl_does_not_match;
7736   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7737                     IsLocalFriend ? Sema::LookupLocalFriendName
7738                                   : Sema::LookupOrdinaryName,
7739                     Sema::ForVisibleRedeclaration);
7740 
7741   NewFD->setInvalidDecl();
7742   if (IsLocalFriend)
7743     SemaRef.LookupName(Prev, S);
7744   else
7745     SemaRef.LookupQualifiedName(Prev, NewDC);
7746   assert(!Prev.isAmbiguous() &&
7747          "Cannot have an ambiguity in previous-declaration lookup");
7748   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7749   if (!Prev.empty()) {
7750     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7751          Func != FuncEnd; ++Func) {
7752       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7753       if (FD &&
7754           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7755         // Add 1 to the index so that 0 can mean the mismatch didn't
7756         // involve a parameter
7757         unsigned ParamNum =
7758             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7759         NearMatches.push_back(std::make_pair(FD, ParamNum));
7760       }
7761     }
7762   // If the qualified name lookup yielded nothing, try typo correction
7763   } else if ((Correction = SemaRef.CorrectTypo(
7764                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7765                   &ExtraArgs.D.getCXXScopeSpec(),
7766                   llvm::make_unique<DifferentNameValidatorCCC>(
7767                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7768                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7769     // Set up everything for the call to ActOnFunctionDeclarator
7770     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7771                               ExtraArgs.D.getIdentifierLoc());
7772     Previous.clear();
7773     Previous.setLookupName(Correction.getCorrection());
7774     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7775                                     CDeclEnd = Correction.end();
7776          CDecl != CDeclEnd; ++CDecl) {
7777       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7778       if (FD && !FD->hasBody() &&
7779           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7780         Previous.addDecl(FD);
7781       }
7782     }
7783     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7784 
7785     NamedDecl *Result;
7786     // Retry building the function declaration with the new previous
7787     // declarations, and with errors suppressed.
7788     {
7789       // Trap errors.
7790       Sema::SFINAETrap Trap(SemaRef);
7791 
7792       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7793       // pieces need to verify the typo-corrected C++ declaration and hopefully
7794       // eliminate the need for the parameter pack ExtraArgs.
7795       Result = SemaRef.ActOnFunctionDeclarator(
7796           ExtraArgs.S, ExtraArgs.D,
7797           Correction.getCorrectionDecl()->getDeclContext(),
7798           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7799           ExtraArgs.AddToScope);
7800 
7801       if (Trap.hasErrorOccurred())
7802         Result = nullptr;
7803     }
7804 
7805     if (Result) {
7806       // Determine which correction we picked.
7807       Decl *Canonical = Result->getCanonicalDecl();
7808       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7809            I != E; ++I)
7810         if ((*I)->getCanonicalDecl() == Canonical)
7811           Correction.setCorrectionDecl(*I);
7812 
7813       // Let Sema know about the correction.
7814       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7815       SemaRef.diagnoseTypo(
7816           Correction,
7817           SemaRef.PDiag(IsLocalFriend
7818                           ? diag::err_no_matching_local_friend_suggest
7819                           : diag::err_member_decl_does_not_match_suggest)
7820             << Name << NewDC << IsDefinition);
7821       return Result;
7822     }
7823 
7824     // Pretend the typo correction never occurred
7825     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7826                               ExtraArgs.D.getIdentifierLoc());
7827     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7828     Previous.clear();
7829     Previous.setLookupName(Name);
7830   }
7831 
7832   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7833       << Name << NewDC << IsDefinition << NewFD->getLocation();
7834 
7835   bool NewFDisConst = false;
7836   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7837     NewFDisConst = NewMD->isConst();
7838 
7839   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7840        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7841        NearMatch != NearMatchEnd; ++NearMatch) {
7842     FunctionDecl *FD = NearMatch->first;
7843     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7844     bool FDisConst = MD && MD->isConst();
7845     bool IsMember = MD || !IsLocalFriend;
7846 
7847     // FIXME: These notes are poorly worded for the local friend case.
7848     if (unsigned Idx = NearMatch->second) {
7849       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7850       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7851       if (Loc.isInvalid()) Loc = FD->getLocation();
7852       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7853                                  : diag::note_local_decl_close_param_match)
7854         << Idx << FDParam->getType()
7855         << NewFD->getParamDecl(Idx - 1)->getType();
7856     } else if (FDisConst != NewFDisConst) {
7857       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7858           << NewFDisConst << FD->getSourceRange().getEnd();
7859     } else
7860       SemaRef.Diag(FD->getLocation(),
7861                    IsMember ? diag::note_member_def_close_match
7862                             : diag::note_local_decl_close_match);
7863   }
7864   return nullptr;
7865 }
7866 
7867 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7868   switch (D.getDeclSpec().getStorageClassSpec()) {
7869   default: llvm_unreachable("Unknown storage class!");
7870   case DeclSpec::SCS_auto:
7871   case DeclSpec::SCS_register:
7872   case DeclSpec::SCS_mutable:
7873     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7874                  diag::err_typecheck_sclass_func);
7875     D.getMutableDeclSpec().ClearStorageClassSpecs();
7876     D.setInvalidType();
7877     break;
7878   case DeclSpec::SCS_unspecified: break;
7879   case DeclSpec::SCS_extern:
7880     if (D.getDeclSpec().isExternInLinkageSpec())
7881       return SC_None;
7882     return SC_Extern;
7883   case DeclSpec::SCS_static: {
7884     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7885       // C99 6.7.1p5:
7886       //   The declaration of an identifier for a function that has
7887       //   block scope shall have no explicit storage-class specifier
7888       //   other than extern
7889       // See also (C++ [dcl.stc]p4).
7890       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7891                    diag::err_static_block_func);
7892       break;
7893     } else
7894       return SC_Static;
7895   }
7896   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7897   }
7898 
7899   // No explicit storage class has already been returned
7900   return SC_None;
7901 }
7902 
7903 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7904                                            DeclContext *DC, QualType &R,
7905                                            TypeSourceInfo *TInfo,
7906                                            StorageClass SC,
7907                                            bool &IsVirtualOkay) {
7908   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7909   DeclarationName Name = NameInfo.getName();
7910 
7911   FunctionDecl *NewFD = nullptr;
7912   bool isInline = D.getDeclSpec().isInlineSpecified();
7913 
7914   if (!SemaRef.getLangOpts().CPlusPlus) {
7915     // Determine whether the function was written with a
7916     // prototype. This true when:
7917     //   - there is a prototype in the declarator, or
7918     //   - the type R of the function is some kind of typedef or other non-
7919     //     attributed reference to a type name (which eventually refers to a
7920     //     function type).
7921     bool HasPrototype =
7922       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7923       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7924 
7925     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7926                                  D.getLocStart(), NameInfo, R,
7927                                  TInfo, SC, isInline,
7928                                  HasPrototype, false);
7929     if (D.isInvalidType())
7930       NewFD->setInvalidDecl();
7931 
7932     return NewFD;
7933   }
7934 
7935   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7936   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7937 
7938   // Check that the return type is not an abstract class type.
7939   // For record types, this is done by the AbstractClassUsageDiagnoser once
7940   // the class has been completely parsed.
7941   if (!DC->isRecord() &&
7942       SemaRef.RequireNonAbstractType(
7943           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7944           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7945     D.setInvalidType();
7946 
7947   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7948     // This is a C++ constructor declaration.
7949     assert(DC->isRecord() &&
7950            "Constructors can only be declared in a member context");
7951 
7952     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7953     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7954                                       D.getLocStart(), NameInfo,
7955                                       R, TInfo, isExplicit, isInline,
7956                                       /*isImplicitlyDeclared=*/false,
7957                                       isConstexpr);
7958 
7959   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7960     // This is a C++ destructor declaration.
7961     if (DC->isRecord()) {
7962       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7963       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7964       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7965                                         SemaRef.Context, Record,
7966                                         D.getLocStart(),
7967                                         NameInfo, R, TInfo, isInline,
7968                                         /*isImplicitlyDeclared=*/false);
7969 
7970       // If the class is complete, then we now create the implicit exception
7971       // specification. If the class is incomplete or dependent, we can't do
7972       // it yet.
7973       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7974           Record->getDefinition() && !Record->isBeingDefined() &&
7975           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7976         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7977       }
7978 
7979       IsVirtualOkay = true;
7980       return NewDD;
7981 
7982     } else {
7983       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7984       D.setInvalidType();
7985 
7986       // Create a FunctionDecl to satisfy the function definition parsing
7987       // code path.
7988       return FunctionDecl::Create(SemaRef.Context, DC,
7989                                   D.getLocStart(),
7990                                   D.getIdentifierLoc(), Name, R, TInfo,
7991                                   SC, isInline,
7992                                   /*hasPrototype=*/true, isConstexpr);
7993     }
7994 
7995   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7996     if (!DC->isRecord()) {
7997       SemaRef.Diag(D.getIdentifierLoc(),
7998            diag::err_conv_function_not_member);
7999       return nullptr;
8000     }
8001 
8002     SemaRef.CheckConversionDeclarator(D, R, SC);
8003     IsVirtualOkay = true;
8004     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
8005                                      D.getLocStart(), NameInfo,
8006                                      R, TInfo, isInline, isExplicit,
8007                                      isConstexpr, SourceLocation());
8008 
8009   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8010     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8011 
8012     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
8013                                          isExplicit, NameInfo, R, TInfo,
8014                                          D.getLocEnd());
8015   } else if (DC->isRecord()) {
8016     // If the name of the function is the same as the name of the record,
8017     // then this must be an invalid constructor that has a return type.
8018     // (The parser checks for a return type and makes the declarator a
8019     // constructor if it has no return type).
8020     if (Name.getAsIdentifierInfo() &&
8021         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8022       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8023         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8024         << SourceRange(D.getIdentifierLoc());
8025       return nullptr;
8026     }
8027 
8028     // This is a C++ method declaration.
8029     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
8030                                                cast<CXXRecordDecl>(DC),
8031                                                D.getLocStart(), NameInfo, R,
8032                                                TInfo, SC, isInline,
8033                                                isConstexpr, SourceLocation());
8034     IsVirtualOkay = !Ret->isStatic();
8035     return Ret;
8036   } else {
8037     bool isFriend =
8038         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8039     if (!isFriend && SemaRef.CurContext->isRecord())
8040       return nullptr;
8041 
8042     // Determine whether the function was written with a
8043     // prototype. This true when:
8044     //   - we're in C++ (where every function has a prototype),
8045     return FunctionDecl::Create(SemaRef.Context, DC,
8046                                 D.getLocStart(),
8047                                 NameInfo, R, TInfo, SC, isInline,
8048                                 true/*HasPrototype*/, isConstexpr);
8049   }
8050 }
8051 
8052 enum OpenCLParamType {
8053   ValidKernelParam,
8054   PtrPtrKernelParam,
8055   PtrKernelParam,
8056   InvalidAddrSpacePtrKernelParam,
8057   InvalidKernelParam,
8058   RecordKernelParam
8059 };
8060 
8061 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8062   if (PT->isPointerType()) {
8063     QualType PointeeType = PT->getPointeeType();
8064     if (PointeeType->isPointerType())
8065       return PtrPtrKernelParam;
8066     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8067         PointeeType.getAddressSpace() == LangAS::opencl_private ||
8068         PointeeType.getAddressSpace() == LangAS::Default)
8069       return InvalidAddrSpacePtrKernelParam;
8070     return PtrKernelParam;
8071   }
8072 
8073   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8074   // be used as builtin types.
8075 
8076   if (PT->isImageType())
8077     return PtrKernelParam;
8078 
8079   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8080     return InvalidKernelParam;
8081 
8082   // OpenCL extension spec v1.2 s9.5:
8083   // This extension adds support for half scalar and vector types as built-in
8084   // types that can be used for arithmetic operations, conversions etc.
8085   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8086     return InvalidKernelParam;
8087 
8088   if (PT->isRecordType())
8089     return RecordKernelParam;
8090 
8091   return ValidKernelParam;
8092 }
8093 
8094 static void checkIsValidOpenCLKernelParameter(
8095   Sema &S,
8096   Declarator &D,
8097   ParmVarDecl *Param,
8098   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8099   QualType PT = Param->getType();
8100 
8101   // Cache the valid types we encounter to avoid rechecking structs that are
8102   // used again
8103   if (ValidTypes.count(PT.getTypePtr()))
8104     return;
8105 
8106   switch (getOpenCLKernelParameterType(S, PT)) {
8107   case PtrPtrKernelParam:
8108     // OpenCL v1.2 s6.9.a:
8109     // A kernel function argument cannot be declared as a
8110     // pointer to a pointer type.
8111     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8112     D.setInvalidType();
8113     return;
8114 
8115   case InvalidAddrSpacePtrKernelParam:
8116     // OpenCL v1.0 s6.5:
8117     // __kernel function arguments declared to be a pointer of a type can point
8118     // to one of the following address spaces only : __global, __local or
8119     // __constant.
8120     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8121     D.setInvalidType();
8122     return;
8123 
8124     // OpenCL v1.2 s6.9.k:
8125     // Arguments to kernel functions in a program cannot be declared with the
8126     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8127     // uintptr_t or a struct and/or union that contain fields declared to be
8128     // one of these built-in scalar types.
8129 
8130   case InvalidKernelParam:
8131     // OpenCL v1.2 s6.8 n:
8132     // A kernel function argument cannot be declared
8133     // of event_t type.
8134     // Do not diagnose half type since it is diagnosed as invalid argument
8135     // type for any function elsewhere.
8136     if (!PT->isHalfType())
8137       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8138     D.setInvalidType();
8139     return;
8140 
8141   case PtrKernelParam:
8142   case ValidKernelParam:
8143     ValidTypes.insert(PT.getTypePtr());
8144     return;
8145 
8146   case RecordKernelParam:
8147     break;
8148   }
8149 
8150   // Track nested structs we will inspect
8151   SmallVector<const Decl *, 4> VisitStack;
8152 
8153   // Track where we are in the nested structs. Items will migrate from
8154   // VisitStack to HistoryStack as we do the DFS for bad field.
8155   SmallVector<const FieldDecl *, 4> HistoryStack;
8156   HistoryStack.push_back(nullptr);
8157 
8158   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8159   VisitStack.push_back(PD);
8160 
8161   assert(VisitStack.back() && "First decl null?");
8162 
8163   do {
8164     const Decl *Next = VisitStack.pop_back_val();
8165     if (!Next) {
8166       assert(!HistoryStack.empty());
8167       // Found a marker, we have gone up a level
8168       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8169         ValidTypes.insert(Hist->getType().getTypePtr());
8170 
8171       continue;
8172     }
8173 
8174     // Adds everything except the original parameter declaration (which is not a
8175     // field itself) to the history stack.
8176     const RecordDecl *RD;
8177     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8178       HistoryStack.push_back(Field);
8179       RD = Field->getType()->castAs<RecordType>()->getDecl();
8180     } else {
8181       RD = cast<RecordDecl>(Next);
8182     }
8183 
8184     // Add a null marker so we know when we've gone back up a level
8185     VisitStack.push_back(nullptr);
8186 
8187     for (const auto *FD : RD->fields()) {
8188       QualType QT = FD->getType();
8189 
8190       if (ValidTypes.count(QT.getTypePtr()))
8191         continue;
8192 
8193       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8194       if (ParamType == ValidKernelParam)
8195         continue;
8196 
8197       if (ParamType == RecordKernelParam) {
8198         VisitStack.push_back(FD);
8199         continue;
8200       }
8201 
8202       // OpenCL v1.2 s6.9.p:
8203       // Arguments to kernel functions that are declared to be a struct or union
8204       // do not allow OpenCL objects to be passed as elements of the struct or
8205       // union.
8206       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8207           ParamType == InvalidAddrSpacePtrKernelParam) {
8208         S.Diag(Param->getLocation(),
8209                diag::err_record_with_pointers_kernel_param)
8210           << PT->isUnionType()
8211           << PT;
8212       } else {
8213         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8214       }
8215 
8216       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8217         << PD->getDeclName();
8218 
8219       // We have an error, now let's go back up through history and show where
8220       // the offending field came from
8221       for (ArrayRef<const FieldDecl *>::const_iterator
8222                I = HistoryStack.begin() + 1,
8223                E = HistoryStack.end();
8224            I != E; ++I) {
8225         const FieldDecl *OuterField = *I;
8226         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8227           << OuterField->getType();
8228       }
8229 
8230       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8231         << QT->isPointerType()
8232         << QT;
8233       D.setInvalidType();
8234       return;
8235     }
8236   } while (!VisitStack.empty());
8237 }
8238 
8239 /// Find the DeclContext in which a tag is implicitly declared if we see an
8240 /// elaborated type specifier in the specified context, and lookup finds
8241 /// nothing.
8242 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8243   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8244     DC = DC->getParent();
8245   return DC;
8246 }
8247 
8248 /// Find the Scope in which a tag is implicitly declared if we see an
8249 /// elaborated type specifier in the specified context, and lookup finds
8250 /// nothing.
8251 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8252   while (S->isClassScope() ||
8253          (LangOpts.CPlusPlus &&
8254           S->isFunctionPrototypeScope()) ||
8255          ((S->getFlags() & Scope::DeclScope) == 0) ||
8256          (S->getEntity() && S->getEntity()->isTransparentContext()))
8257     S = S->getParent();
8258   return S;
8259 }
8260 
8261 NamedDecl*
8262 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8263                               TypeSourceInfo *TInfo, LookupResult &Previous,
8264                               MultiTemplateParamsArg TemplateParamLists,
8265                               bool &AddToScope) {
8266   QualType R = TInfo->getType();
8267 
8268   assert(R.getTypePtr()->isFunctionType());
8269 
8270   // TODO: consider using NameInfo for diagnostic.
8271   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8272   DeclarationName Name = NameInfo.getName();
8273   StorageClass SC = getFunctionStorageClass(*this, D);
8274 
8275   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8276     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8277          diag::err_invalid_thread)
8278       << DeclSpec::getSpecifierName(TSCS);
8279 
8280   if (D.isFirstDeclarationOfMember())
8281     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8282                            D.getIdentifierLoc());
8283 
8284   bool isFriend = false;
8285   FunctionTemplateDecl *FunctionTemplate = nullptr;
8286   bool isMemberSpecialization = false;
8287   bool isFunctionTemplateSpecialization = false;
8288 
8289   bool isDependentClassScopeExplicitSpecialization = false;
8290   bool HasExplicitTemplateArgs = false;
8291   TemplateArgumentListInfo TemplateArgs;
8292 
8293   bool isVirtualOkay = false;
8294 
8295   DeclContext *OriginalDC = DC;
8296   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8297 
8298   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8299                                               isVirtualOkay);
8300   if (!NewFD) return nullptr;
8301 
8302   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8303     NewFD->setTopLevelDeclInObjCContainer();
8304 
8305   // Set the lexical context. If this is a function-scope declaration, or has a
8306   // C++ scope specifier, or is the object of a friend declaration, the lexical
8307   // context will be different from the semantic context.
8308   NewFD->setLexicalDeclContext(CurContext);
8309 
8310   if (IsLocalExternDecl)
8311     NewFD->setLocalExternDecl();
8312 
8313   if (getLangOpts().CPlusPlus) {
8314     bool isInline = D.getDeclSpec().isInlineSpecified();
8315     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8316     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8317     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8318     bool isConcept = D.getDeclSpec().isConceptSpecified();
8319     isFriend = D.getDeclSpec().isFriendSpecified();
8320     if (isFriend && !isInline && D.isFunctionDefinition()) {
8321       // C++ [class.friend]p5
8322       //   A function can be defined in a friend declaration of a
8323       //   class . . . . Such a function is implicitly inline.
8324       NewFD->setImplicitlyInline();
8325     }
8326 
8327     // If this is a method defined in an __interface, and is not a constructor
8328     // or an overloaded operator, then set the pure flag (isVirtual will already
8329     // return true).
8330     if (const CXXRecordDecl *Parent =
8331           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8332       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8333         NewFD->setPure(true);
8334 
8335       // C++ [class.union]p2
8336       //   A union can have member functions, but not virtual functions.
8337       if (isVirtual && Parent->isUnion())
8338         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8339     }
8340 
8341     SetNestedNameSpecifier(NewFD, D);
8342     isMemberSpecialization = false;
8343     isFunctionTemplateSpecialization = false;
8344     if (D.isInvalidType())
8345       NewFD->setInvalidDecl();
8346 
8347     // Match up the template parameter lists with the scope specifier, then
8348     // determine whether we have a template or a template specialization.
8349     bool Invalid = false;
8350     if (TemplateParameterList *TemplateParams =
8351             MatchTemplateParametersToScopeSpecifier(
8352                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8353                 D.getCXXScopeSpec(),
8354                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8355                     ? D.getName().TemplateId
8356                     : nullptr,
8357                 TemplateParamLists, isFriend, isMemberSpecialization,
8358                 Invalid)) {
8359       if (TemplateParams->size() > 0) {
8360         // This is a function template
8361 
8362         // Check that we can declare a template here.
8363         if (CheckTemplateDeclScope(S, TemplateParams))
8364           NewFD->setInvalidDecl();
8365 
8366         // A destructor cannot be a template.
8367         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8368           Diag(NewFD->getLocation(), diag::err_destructor_template);
8369           NewFD->setInvalidDecl();
8370         }
8371 
8372         // If we're adding a template to a dependent context, we may need to
8373         // rebuilding some of the types used within the template parameter list,
8374         // now that we know what the current instantiation is.
8375         if (DC->isDependentContext()) {
8376           ContextRAII SavedContext(*this, DC);
8377           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8378             Invalid = true;
8379         }
8380 
8381         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8382                                                         NewFD->getLocation(),
8383                                                         Name, TemplateParams,
8384                                                         NewFD);
8385         FunctionTemplate->setLexicalDeclContext(CurContext);
8386         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8387 
8388         // For source fidelity, store the other template param lists.
8389         if (TemplateParamLists.size() > 1) {
8390           NewFD->setTemplateParameterListsInfo(Context,
8391                                                TemplateParamLists.drop_back(1));
8392         }
8393       } else {
8394         // This is a function template specialization.
8395         isFunctionTemplateSpecialization = true;
8396         // For source fidelity, store all the template param lists.
8397         if (TemplateParamLists.size() > 0)
8398           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8399 
8400         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8401         if (isFriend) {
8402           // We want to remove the "template<>", found here.
8403           SourceRange RemoveRange = TemplateParams->getSourceRange();
8404 
8405           // If we remove the template<> and the name is not a
8406           // template-id, we're actually silently creating a problem:
8407           // the friend declaration will refer to an untemplated decl,
8408           // and clearly the user wants a template specialization.  So
8409           // we need to insert '<>' after the name.
8410           SourceLocation InsertLoc;
8411           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8412             InsertLoc = D.getName().getSourceRange().getEnd();
8413             InsertLoc = getLocForEndOfToken(InsertLoc);
8414           }
8415 
8416           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8417             << Name << RemoveRange
8418             << FixItHint::CreateRemoval(RemoveRange)
8419             << FixItHint::CreateInsertion(InsertLoc, "<>");
8420         }
8421       }
8422     }
8423     else {
8424       // All template param lists were matched against the scope specifier:
8425       // this is NOT (an explicit specialization of) a template.
8426       if (TemplateParamLists.size() > 0)
8427         // For source fidelity, store all the template param lists.
8428         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8429     }
8430 
8431     if (Invalid) {
8432       NewFD->setInvalidDecl();
8433       if (FunctionTemplate)
8434         FunctionTemplate->setInvalidDecl();
8435     }
8436 
8437     // C++ [dcl.fct.spec]p5:
8438     //   The virtual specifier shall only be used in declarations of
8439     //   nonstatic class member functions that appear within a
8440     //   member-specification of a class declaration; see 10.3.
8441     //
8442     if (isVirtual && !NewFD->isInvalidDecl()) {
8443       if (!isVirtualOkay) {
8444         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8445              diag::err_virtual_non_function);
8446       } else if (!CurContext->isRecord()) {
8447         // 'virtual' was specified outside of the class.
8448         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8449              diag::err_virtual_out_of_class)
8450           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8451       } else if (NewFD->getDescribedFunctionTemplate()) {
8452         // C++ [temp.mem]p3:
8453         //  A member function template shall not be virtual.
8454         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8455              diag::err_virtual_member_function_template)
8456           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8457       } else {
8458         // Okay: Add virtual to the method.
8459         NewFD->setVirtualAsWritten(true);
8460       }
8461 
8462       if (getLangOpts().CPlusPlus14 &&
8463           NewFD->getReturnType()->isUndeducedType())
8464         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8465     }
8466 
8467     if (getLangOpts().CPlusPlus14 &&
8468         (NewFD->isDependentContext() ||
8469          (isFriend && CurContext->isDependentContext())) &&
8470         NewFD->getReturnType()->isUndeducedType()) {
8471       // If the function template is referenced directly (for instance, as a
8472       // member of the current instantiation), pretend it has a dependent type.
8473       // This is not really justified by the standard, but is the only sane
8474       // thing to do.
8475       // FIXME: For a friend function, we have not marked the function as being
8476       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8477       const FunctionProtoType *FPT =
8478           NewFD->getType()->castAs<FunctionProtoType>();
8479       QualType Result =
8480           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8481       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8482                                              FPT->getExtProtoInfo()));
8483     }
8484 
8485     // C++ [dcl.fct.spec]p3:
8486     //  The inline specifier shall not appear on a block scope function
8487     //  declaration.
8488     if (isInline && !NewFD->isInvalidDecl()) {
8489       if (CurContext->isFunctionOrMethod()) {
8490         // 'inline' is not allowed on block scope function declaration.
8491         Diag(D.getDeclSpec().getInlineSpecLoc(),
8492              diag::err_inline_declaration_block_scope) << Name
8493           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8494       }
8495     }
8496 
8497     // C++ [dcl.fct.spec]p6:
8498     //  The explicit specifier shall be used only in the declaration of a
8499     //  constructor or conversion function within its class definition;
8500     //  see 12.3.1 and 12.3.2.
8501     if (isExplicit && !NewFD->isInvalidDecl() &&
8502         !isa<CXXDeductionGuideDecl>(NewFD)) {
8503       if (!CurContext->isRecord()) {
8504         // 'explicit' was specified outside of the class.
8505         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8506              diag::err_explicit_out_of_class)
8507           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8508       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8509                  !isa<CXXConversionDecl>(NewFD)) {
8510         // 'explicit' was specified on a function that wasn't a constructor
8511         // or conversion function.
8512         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8513              diag::err_explicit_non_ctor_or_conv_function)
8514           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8515       }
8516     }
8517 
8518     if (isConstexpr) {
8519       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8520       // are implicitly inline.
8521       NewFD->setImplicitlyInline();
8522 
8523       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8524       // be either constructors or to return a literal type. Therefore,
8525       // destructors cannot be declared constexpr.
8526       if (isa<CXXDestructorDecl>(NewFD))
8527         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8528     }
8529 
8530     if (isConcept) {
8531       // This is a function concept.
8532       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8533         FTD->setConcept();
8534 
8535       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8536       // applied only to the definition of a function template [...]
8537       if (!D.isFunctionDefinition()) {
8538         Diag(D.getDeclSpec().getConceptSpecLoc(),
8539              diag::err_function_concept_not_defined);
8540         NewFD->setInvalidDecl();
8541       }
8542 
8543       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8544       // have no exception-specification and is treated as if it were specified
8545       // with noexcept(true) (15.4). [...]
8546       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8547         if (FPT->hasExceptionSpec()) {
8548           SourceRange Range;
8549           if (D.isFunctionDeclarator())
8550             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8551           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8552               << FixItHint::CreateRemoval(Range);
8553           NewFD->setInvalidDecl();
8554         } else {
8555           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8556         }
8557 
8558         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8559         // following restrictions:
8560         // - The declared return type shall have the type bool.
8561         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8562           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8563           NewFD->setInvalidDecl();
8564         }
8565 
8566         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8567         // following restrictions:
8568         // - The declaration's parameter list shall be equivalent to an empty
8569         //   parameter list.
8570         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8571           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8572       }
8573 
8574       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8575       // implicity defined to be a constexpr declaration (implicitly inline)
8576       NewFD->setImplicitlyInline();
8577 
8578       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8579       // be declared with the thread_local, inline, friend, or constexpr
8580       // specifiers, [...]
8581       if (isInline) {
8582         Diag(D.getDeclSpec().getInlineSpecLoc(),
8583              diag::err_concept_decl_invalid_specifiers)
8584             << 1 << 1;
8585         NewFD->setInvalidDecl(true);
8586       }
8587 
8588       if (isFriend) {
8589         Diag(D.getDeclSpec().getFriendSpecLoc(),
8590              diag::err_concept_decl_invalid_specifiers)
8591             << 1 << 2;
8592         NewFD->setInvalidDecl(true);
8593       }
8594 
8595       if (isConstexpr) {
8596         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8597              diag::err_concept_decl_invalid_specifiers)
8598             << 1 << 3;
8599         NewFD->setInvalidDecl(true);
8600       }
8601 
8602       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8603       // applied only to the definition of a function template or variable
8604       // template, declared in namespace scope.
8605       if (isFunctionTemplateSpecialization) {
8606         Diag(D.getDeclSpec().getConceptSpecLoc(),
8607              diag::err_concept_specified_specialization) << 1;
8608         NewFD->setInvalidDecl(true);
8609         return NewFD;
8610       }
8611     }
8612 
8613     // If __module_private__ was specified, mark the function accordingly.
8614     if (D.getDeclSpec().isModulePrivateSpecified()) {
8615       if (isFunctionTemplateSpecialization) {
8616         SourceLocation ModulePrivateLoc
8617           = D.getDeclSpec().getModulePrivateSpecLoc();
8618         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8619           << 0
8620           << FixItHint::CreateRemoval(ModulePrivateLoc);
8621       } else {
8622         NewFD->setModulePrivate();
8623         if (FunctionTemplate)
8624           FunctionTemplate->setModulePrivate();
8625       }
8626     }
8627 
8628     if (isFriend) {
8629       if (FunctionTemplate) {
8630         FunctionTemplate->setObjectOfFriendDecl();
8631         FunctionTemplate->setAccess(AS_public);
8632       }
8633       NewFD->setObjectOfFriendDecl();
8634       NewFD->setAccess(AS_public);
8635     }
8636 
8637     // If a function is defined as defaulted or deleted, mark it as such now.
8638     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8639     // definition kind to FDK_Definition.
8640     switch (D.getFunctionDefinitionKind()) {
8641       case FDK_Declaration:
8642       case FDK_Definition:
8643         break;
8644 
8645       case FDK_Defaulted:
8646         NewFD->setDefaulted();
8647         break;
8648 
8649       case FDK_Deleted:
8650         NewFD->setDeletedAsWritten();
8651         break;
8652     }
8653 
8654     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8655         D.isFunctionDefinition()) {
8656       // C++ [class.mfct]p2:
8657       //   A member function may be defined (8.4) in its class definition, in
8658       //   which case it is an inline member function (7.1.2)
8659       NewFD->setImplicitlyInline();
8660     }
8661 
8662     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8663         !CurContext->isRecord()) {
8664       // C++ [class.static]p1:
8665       //   A data or function member of a class may be declared static
8666       //   in a class definition, in which case it is a static member of
8667       //   the class.
8668 
8669       // Complain about the 'static' specifier if it's on an out-of-line
8670       // member function definition.
8671       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8672            diag::err_static_out_of_line)
8673         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8674     }
8675 
8676     // C++11 [except.spec]p15:
8677     //   A deallocation function with no exception-specification is treated
8678     //   as if it were specified with noexcept(true).
8679     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8680     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8681          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8682         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8683       NewFD->setType(Context.getFunctionType(
8684           FPT->getReturnType(), FPT->getParamTypes(),
8685           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8686   }
8687 
8688   // Filter out previous declarations that don't match the scope.
8689   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8690                        D.getCXXScopeSpec().isNotEmpty() ||
8691                        isMemberSpecialization ||
8692                        isFunctionTemplateSpecialization);
8693 
8694   // Handle GNU asm-label extension (encoded as an attribute).
8695   if (Expr *E = (Expr*) D.getAsmLabel()) {
8696     // The parser guarantees this is a string.
8697     StringLiteral *SE = cast<StringLiteral>(E);
8698     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8699                                                 SE->getString(), 0));
8700   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8701     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8702       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8703     if (I != ExtnameUndeclaredIdentifiers.end()) {
8704       if (isDeclExternC(NewFD)) {
8705         NewFD->addAttr(I->second);
8706         ExtnameUndeclaredIdentifiers.erase(I);
8707       } else
8708         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8709             << /*Variable*/0 << NewFD;
8710     }
8711   }
8712 
8713   // Copy the parameter declarations from the declarator D to the function
8714   // declaration NewFD, if they are available.  First scavenge them into Params.
8715   SmallVector<ParmVarDecl*, 16> Params;
8716   unsigned FTIIdx;
8717   if (D.isFunctionDeclarator(FTIIdx)) {
8718     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8719 
8720     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8721     // function that takes no arguments, not a function that takes a
8722     // single void argument.
8723     // We let through "const void" here because Sema::GetTypeForDeclarator
8724     // already checks for that case.
8725     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8726       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8727         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8728         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8729         Param->setDeclContext(NewFD);
8730         Params.push_back(Param);
8731 
8732         if (Param->isInvalidDecl())
8733           NewFD->setInvalidDecl();
8734       }
8735     }
8736 
8737     if (!getLangOpts().CPlusPlus) {
8738       // In C, find all the tag declarations from the prototype and move them
8739       // into the function DeclContext. Remove them from the surrounding tag
8740       // injection context of the function, which is typically but not always
8741       // the TU.
8742       DeclContext *PrototypeTagContext =
8743           getTagInjectionContext(NewFD->getLexicalDeclContext());
8744       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8745         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8746 
8747         // We don't want to reparent enumerators. Look at their parent enum
8748         // instead.
8749         if (!TD) {
8750           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8751             TD = cast<EnumDecl>(ECD->getDeclContext());
8752         }
8753         if (!TD)
8754           continue;
8755         DeclContext *TagDC = TD->getLexicalDeclContext();
8756         if (!TagDC->containsDecl(TD))
8757           continue;
8758         TagDC->removeDecl(TD);
8759         TD->setDeclContext(NewFD);
8760         NewFD->addDecl(TD);
8761 
8762         // Preserve the lexical DeclContext if it is not the surrounding tag
8763         // injection context of the FD. In this example, the semantic context of
8764         // E will be f and the lexical context will be S, while both the
8765         // semantic and lexical contexts of S will be f:
8766         //   void f(struct S { enum E { a } f; } s);
8767         if (TagDC != PrototypeTagContext)
8768           TD->setLexicalDeclContext(TagDC);
8769       }
8770     }
8771   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8772     // When we're declaring a function with a typedef, typeof, etc as in the
8773     // following example, we'll need to synthesize (unnamed)
8774     // parameters for use in the declaration.
8775     //
8776     // @code
8777     // typedef void fn(int);
8778     // fn f;
8779     // @endcode
8780 
8781     // Synthesize a parameter for each argument type.
8782     for (const auto &AI : FT->param_types()) {
8783       ParmVarDecl *Param =
8784           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8785       Param->setScopeInfo(0, Params.size());
8786       Params.push_back(Param);
8787     }
8788   } else {
8789     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8790            "Should not need args for typedef of non-prototype fn");
8791   }
8792 
8793   // Finally, we know we have the right number of parameters, install them.
8794   NewFD->setParams(Params);
8795 
8796   if (D.getDeclSpec().isNoreturnSpecified())
8797     NewFD->addAttr(
8798         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8799                                        Context, 0));
8800 
8801   // Functions returning a variably modified type violate C99 6.7.5.2p2
8802   // because all functions have linkage.
8803   if (!NewFD->isInvalidDecl() &&
8804       NewFD->getReturnType()->isVariablyModifiedType()) {
8805     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8806     NewFD->setInvalidDecl();
8807   }
8808 
8809   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8810   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8811       !NewFD->hasAttr<SectionAttr>()) {
8812     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8813                                                  PragmaClangTextSection.SectionName,
8814                                                  PragmaClangTextSection.PragmaLocation));
8815   }
8816 
8817   // Apply an implicit SectionAttr if #pragma code_seg is active.
8818   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8819       !NewFD->hasAttr<SectionAttr>()) {
8820     NewFD->addAttr(
8821         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8822                                     CodeSegStack.CurrentValue->getString(),
8823                                     CodeSegStack.CurrentPragmaLocation));
8824     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8825                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8826                          ASTContext::PSF_Read,
8827                      NewFD))
8828       NewFD->dropAttr<SectionAttr>();
8829   }
8830 
8831   // Handle attributes.
8832   ProcessDeclAttributes(S, NewFD, D);
8833 
8834   if (getLangOpts().OpenCL) {
8835     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8836     // type declaration will generate a compilation error.
8837     LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8838     if (AddressSpace != LangAS::Default) {
8839       Diag(NewFD->getLocation(),
8840            diag::err_opencl_return_value_with_address_space);
8841       NewFD->setInvalidDecl();
8842     }
8843   }
8844 
8845   if (!getLangOpts().CPlusPlus) {
8846     // Perform semantic checking on the function declaration.
8847     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8848       CheckMain(NewFD, D.getDeclSpec());
8849 
8850     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8851       CheckMSVCRTEntryPoint(NewFD);
8852 
8853     if (!NewFD->isInvalidDecl())
8854       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8855                                                   isMemberSpecialization));
8856     else if (!Previous.empty())
8857       // Recover gracefully from an invalid redeclaration.
8858       D.setRedeclaration(true);
8859     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8860             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8861            "previous declaration set still overloaded");
8862 
8863     // Diagnose no-prototype function declarations with calling conventions that
8864     // don't support variadic calls. Only do this in C and do it after merging
8865     // possibly prototyped redeclarations.
8866     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8867     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8868       CallingConv CC = FT->getExtInfo().getCC();
8869       if (!supportsVariadicCall(CC)) {
8870         // Windows system headers sometimes accidentally use stdcall without
8871         // (void) parameters, so we relax this to a warning.
8872         int DiagID =
8873             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8874         Diag(NewFD->getLocation(), DiagID)
8875             << FunctionType::getNameForCallConv(CC);
8876       }
8877     }
8878   } else {
8879     // C++11 [replacement.functions]p3:
8880     //  The program's definitions shall not be specified as inline.
8881     //
8882     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8883     //
8884     // Suppress the diagnostic if the function is __attribute__((used)), since
8885     // that forces an external definition to be emitted.
8886     if (D.getDeclSpec().isInlineSpecified() &&
8887         NewFD->isReplaceableGlobalAllocationFunction() &&
8888         !NewFD->hasAttr<UsedAttr>())
8889       Diag(D.getDeclSpec().getInlineSpecLoc(),
8890            diag::ext_operator_new_delete_declared_inline)
8891         << NewFD->getDeclName();
8892 
8893     // If the declarator is a template-id, translate the parser's template
8894     // argument list into our AST format.
8895     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8896       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8897       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8898       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8899       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8900                                          TemplateId->NumArgs);
8901       translateTemplateArguments(TemplateArgsPtr,
8902                                  TemplateArgs);
8903 
8904       HasExplicitTemplateArgs = true;
8905 
8906       if (NewFD->isInvalidDecl()) {
8907         HasExplicitTemplateArgs = false;
8908       } else if (FunctionTemplate) {
8909         // Function template with explicit template arguments.
8910         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8911           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8912 
8913         HasExplicitTemplateArgs = false;
8914       } else {
8915         assert((isFunctionTemplateSpecialization ||
8916                 D.getDeclSpec().isFriendSpecified()) &&
8917                "should have a 'template<>' for this decl");
8918         // "friend void foo<>(int);" is an implicit specialization decl.
8919         isFunctionTemplateSpecialization = true;
8920       }
8921     } else if (isFriend && isFunctionTemplateSpecialization) {
8922       // This combination is only possible in a recovery case;  the user
8923       // wrote something like:
8924       //   template <> friend void foo(int);
8925       // which we're recovering from as if the user had written:
8926       //   friend void foo<>(int);
8927       // Go ahead and fake up a template id.
8928       HasExplicitTemplateArgs = true;
8929       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8930       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8931     }
8932 
8933     // We do not add HD attributes to specializations here because
8934     // they may have different constexpr-ness compared to their
8935     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8936     // may end up with different effective targets. Instead, a
8937     // specialization inherits its target attributes from its template
8938     // in the CheckFunctionTemplateSpecialization() call below.
8939     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8940       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8941 
8942     // If it's a friend (and only if it's a friend), it's possible
8943     // that either the specialized function type or the specialized
8944     // template is dependent, and therefore matching will fail.  In
8945     // this case, don't check the specialization yet.
8946     bool InstantiationDependent = false;
8947     if (isFunctionTemplateSpecialization && isFriend &&
8948         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8949          TemplateSpecializationType::anyDependentTemplateArguments(
8950             TemplateArgs,
8951             InstantiationDependent))) {
8952       assert(HasExplicitTemplateArgs &&
8953              "friend function specialization without template args");
8954       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8955                                                        Previous))
8956         NewFD->setInvalidDecl();
8957     } else if (isFunctionTemplateSpecialization) {
8958       if (CurContext->isDependentContext() && CurContext->isRecord()
8959           && !isFriend) {
8960         isDependentClassScopeExplicitSpecialization = true;
8961         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8962           diag::ext_function_specialization_in_class :
8963           diag::err_function_specialization_in_class)
8964           << NewFD->getDeclName();
8965       } else if (CheckFunctionTemplateSpecialization(NewFD,
8966                                   (HasExplicitTemplateArgs ? &TemplateArgs
8967                                                            : nullptr),
8968                                                      Previous))
8969         NewFD->setInvalidDecl();
8970 
8971       // C++ [dcl.stc]p1:
8972       //   A storage-class-specifier shall not be specified in an explicit
8973       //   specialization (14.7.3)
8974       FunctionTemplateSpecializationInfo *Info =
8975           NewFD->getTemplateSpecializationInfo();
8976       if (Info && SC != SC_None) {
8977         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8978           Diag(NewFD->getLocation(),
8979                diag::err_explicit_specialization_inconsistent_storage_class)
8980             << SC
8981             << FixItHint::CreateRemoval(
8982                                       D.getDeclSpec().getStorageClassSpecLoc());
8983 
8984         else
8985           Diag(NewFD->getLocation(),
8986                diag::ext_explicit_specialization_storage_class)
8987             << FixItHint::CreateRemoval(
8988                                       D.getDeclSpec().getStorageClassSpecLoc());
8989       }
8990     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8991       if (CheckMemberSpecialization(NewFD, Previous))
8992           NewFD->setInvalidDecl();
8993     }
8994 
8995     // Perform semantic checking on the function declaration.
8996     if (!isDependentClassScopeExplicitSpecialization) {
8997       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8998         CheckMain(NewFD, D.getDeclSpec());
8999 
9000       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9001         CheckMSVCRTEntryPoint(NewFD);
9002 
9003       if (!NewFD->isInvalidDecl())
9004         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9005                                                     isMemberSpecialization));
9006       else if (!Previous.empty())
9007         // Recover gracefully from an invalid redeclaration.
9008         D.setRedeclaration(true);
9009     }
9010 
9011     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9012             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9013            "previous declaration set still overloaded");
9014 
9015     NamedDecl *PrincipalDecl = (FunctionTemplate
9016                                 ? cast<NamedDecl>(FunctionTemplate)
9017                                 : NewFD);
9018 
9019     if (isFriend && NewFD->getPreviousDecl()) {
9020       AccessSpecifier Access = AS_public;
9021       if (!NewFD->isInvalidDecl())
9022         Access = NewFD->getPreviousDecl()->getAccess();
9023 
9024       NewFD->setAccess(Access);
9025       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9026     }
9027 
9028     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9029         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9030       PrincipalDecl->setNonMemberOperator();
9031 
9032     // If we have a function template, check the template parameter
9033     // list. This will check and merge default template arguments.
9034     if (FunctionTemplate) {
9035       FunctionTemplateDecl *PrevTemplate =
9036                                      FunctionTemplate->getPreviousDecl();
9037       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9038                        PrevTemplate ? PrevTemplate->getTemplateParameters()
9039                                     : nullptr,
9040                             D.getDeclSpec().isFriendSpecified()
9041                               ? (D.isFunctionDefinition()
9042                                    ? TPC_FriendFunctionTemplateDefinition
9043                                    : TPC_FriendFunctionTemplate)
9044                               : (D.getCXXScopeSpec().isSet() &&
9045                                  DC && DC->isRecord() &&
9046                                  DC->isDependentContext())
9047                                   ? TPC_ClassTemplateMember
9048                                   : TPC_FunctionTemplate);
9049     }
9050 
9051     if (NewFD->isInvalidDecl()) {
9052       // Ignore all the rest of this.
9053     } else if (!D.isRedeclaration()) {
9054       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9055                                        AddToScope };
9056       // Fake up an access specifier if it's supposed to be a class member.
9057       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9058         NewFD->setAccess(AS_public);
9059 
9060       // Qualified decls generally require a previous declaration.
9061       if (D.getCXXScopeSpec().isSet()) {
9062         // ...with the major exception of templated-scope or
9063         // dependent-scope friend declarations.
9064 
9065         // TODO: we currently also suppress this check in dependent
9066         // contexts because (1) the parameter depth will be off when
9067         // matching friend templates and (2) we might actually be
9068         // selecting a friend based on a dependent factor.  But there
9069         // are situations where these conditions don't apply and we
9070         // can actually do this check immediately.
9071         if (isFriend &&
9072             (TemplateParamLists.size() ||
9073              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9074              CurContext->isDependentContext())) {
9075           // ignore these
9076         } else {
9077           // The user tried to provide an out-of-line definition for a
9078           // function that is a member of a class or namespace, but there
9079           // was no such member function declared (C++ [class.mfct]p2,
9080           // C++ [namespace.memdef]p2). For example:
9081           //
9082           // class X {
9083           //   void f() const;
9084           // };
9085           //
9086           // void X::f() { } // ill-formed
9087           //
9088           // Complain about this problem, and attempt to suggest close
9089           // matches (e.g., those that differ only in cv-qualifiers and
9090           // whether the parameter types are references).
9091 
9092           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9093                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9094             AddToScope = ExtraArgs.AddToScope;
9095             return Result;
9096           }
9097         }
9098 
9099         // Unqualified local friend declarations are required to resolve
9100         // to something.
9101       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9102         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9103                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9104           AddToScope = ExtraArgs.AddToScope;
9105           return Result;
9106         }
9107       }
9108     } else if (!D.isFunctionDefinition() &&
9109                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9110                !isFriend && !isFunctionTemplateSpecialization &&
9111                !isMemberSpecialization) {
9112       // An out-of-line member function declaration must also be a
9113       // definition (C++ [class.mfct]p2).
9114       // Note that this is not the case for explicit specializations of
9115       // function templates or member functions of class templates, per
9116       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9117       // extension for compatibility with old SWIG code which likes to
9118       // generate them.
9119       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9120         << D.getCXXScopeSpec().getRange();
9121     }
9122   }
9123 
9124   ProcessPragmaWeak(S, NewFD);
9125   checkAttributesAfterMerging(*this, *NewFD);
9126 
9127   AddKnownFunctionAttributes(NewFD);
9128 
9129   if (NewFD->hasAttr<OverloadableAttr>() &&
9130       !NewFD->getType()->getAs<FunctionProtoType>()) {
9131     Diag(NewFD->getLocation(),
9132          diag::err_attribute_overloadable_no_prototype)
9133       << NewFD;
9134 
9135     // Turn this into a variadic function with no parameters.
9136     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9137     FunctionProtoType::ExtProtoInfo EPI(
9138         Context.getDefaultCallingConvention(true, false));
9139     EPI.Variadic = true;
9140     EPI.ExtInfo = FT->getExtInfo();
9141 
9142     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9143     NewFD->setType(R);
9144   }
9145 
9146   // If there's a #pragma GCC visibility in scope, and this isn't a class
9147   // member, set the visibility of this function.
9148   if (!DC->isRecord() && NewFD->isExternallyVisible())
9149     AddPushedVisibilityAttribute(NewFD);
9150 
9151   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9152   // marking the function.
9153   AddCFAuditedAttribute(NewFD);
9154 
9155   // If this is a function definition, check if we have to apply optnone due to
9156   // a pragma.
9157   if(D.isFunctionDefinition())
9158     AddRangeBasedOptnone(NewFD);
9159 
9160   // If this is the first declaration of an extern C variable, update
9161   // the map of such variables.
9162   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9163       isIncompleteDeclExternC(*this, NewFD))
9164     RegisterLocallyScopedExternCDecl(NewFD, S);
9165 
9166   // Set this FunctionDecl's range up to the right paren.
9167   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9168 
9169   if (D.isRedeclaration() && !Previous.empty()) {
9170     checkDLLAttributeRedeclaration(
9171         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9172         isMemberSpecialization || isFunctionTemplateSpecialization,
9173         D.isFunctionDefinition());
9174   }
9175 
9176   if (getLangOpts().CUDA) {
9177     IdentifierInfo *II = NewFD->getIdentifier();
9178     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9179         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9180       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9181         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9182 
9183       Context.setcudaConfigureCallDecl(NewFD);
9184     }
9185 
9186     // Variadic functions, other than a *declaration* of printf, are not allowed
9187     // in device-side CUDA code, unless someone passed
9188     // -fcuda-allow-variadic-functions.
9189     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9190         (NewFD->hasAttr<CUDADeviceAttr>() ||
9191          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9192         !(II && II->isStr("printf") && NewFD->isExternC() &&
9193           !D.isFunctionDefinition())) {
9194       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9195     }
9196   }
9197 
9198   MarkUnusedFileScopedDecl(NewFD);
9199 
9200   if (getLangOpts().CPlusPlus) {
9201     if (FunctionTemplate) {
9202       if (NewFD->isInvalidDecl())
9203         FunctionTemplate->setInvalidDecl();
9204       return FunctionTemplate;
9205     }
9206 
9207     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9208       CompleteMemberSpecialization(NewFD, Previous);
9209   }
9210 
9211   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9212     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9213     if ((getLangOpts().OpenCLVersion >= 120)
9214         && (SC == SC_Static)) {
9215       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9216       D.setInvalidType();
9217     }
9218 
9219     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9220     if (!NewFD->getReturnType()->isVoidType()) {
9221       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9222       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9223           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9224                                 : FixItHint());
9225       D.setInvalidType();
9226     }
9227 
9228     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9229     for (auto Param : NewFD->parameters())
9230       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9231   }
9232   for (const ParmVarDecl *Param : NewFD->parameters()) {
9233     QualType PT = Param->getType();
9234 
9235     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9236     // types.
9237     if (getLangOpts().OpenCLVersion >= 200) {
9238       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9239         QualType ElemTy = PipeTy->getElementType();
9240           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9241             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9242             D.setInvalidType();
9243           }
9244       }
9245     }
9246   }
9247 
9248   // Here we have an function template explicit specialization at class scope.
9249   // The actually specialization will be postponed to template instatiation
9250   // time via the ClassScopeFunctionSpecializationDecl node.
9251   if (isDependentClassScopeExplicitSpecialization) {
9252     ClassScopeFunctionSpecializationDecl *NewSpec =
9253                          ClassScopeFunctionSpecializationDecl::Create(
9254                                 Context, CurContext, SourceLocation(),
9255                                 cast<CXXMethodDecl>(NewFD),
9256                                 HasExplicitTemplateArgs, TemplateArgs);
9257     CurContext->addDecl(NewSpec);
9258     AddToScope = false;
9259   }
9260 
9261   return NewFD;
9262 }
9263 
9264 /// \brief Checks if the new declaration declared in dependent context must be
9265 /// put in the same redeclaration chain as the specified declaration.
9266 ///
9267 /// \param D Declaration that is checked.
9268 /// \param PrevDecl Previous declaration found with proper lookup method for the
9269 ///                 same declaration name.
9270 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9271 ///          belongs to.
9272 ///
9273 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9274   // Any declarations should be put into redeclaration chains except for
9275   // friend declaration in a dependent context that names a function in
9276   // namespace scope.
9277   //
9278   // This allows to compile code like:
9279   //
9280   //       void func();
9281   //       template<typename T> class C1 { friend void func() { } };
9282   //       template<typename T> class C2 { friend void func() { } };
9283   //
9284   // This code snippet is a valid code unless both templates are instantiated.
9285   return !(D->getLexicalDeclContext()->isDependentContext() &&
9286            D->getDeclContext()->isFileContext() &&
9287            D->getFriendObjectKind() != Decl::FOK_None);
9288 }
9289 
9290 /// \brief Perform semantic checking of a new function declaration.
9291 ///
9292 /// Performs semantic analysis of the new function declaration
9293 /// NewFD. This routine performs all semantic checking that does not
9294 /// require the actual declarator involved in the declaration, and is
9295 /// used both for the declaration of functions as they are parsed
9296 /// (called via ActOnDeclarator) and for the declaration of functions
9297 /// that have been instantiated via C++ template instantiation (called
9298 /// via InstantiateDecl).
9299 ///
9300 /// \param IsMemberSpecialization whether this new function declaration is
9301 /// a member specialization (that replaces any definition provided by the
9302 /// previous declaration).
9303 ///
9304 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9305 ///
9306 /// \returns true if the function declaration is a redeclaration.
9307 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9308                                     LookupResult &Previous,
9309                                     bool IsMemberSpecialization) {
9310   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9311          "Variably modified return types are not handled here");
9312 
9313   // Determine whether the type of this function should be merged with
9314   // a previous visible declaration. This never happens for functions in C++,
9315   // and always happens in C if the previous declaration was visible.
9316   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9317                                !Previous.isShadowed();
9318 
9319   bool Redeclaration = false;
9320   NamedDecl *OldDecl = nullptr;
9321   bool MayNeedOverloadableChecks = false;
9322 
9323   // Merge or overload the declaration with an existing declaration of
9324   // the same name, if appropriate.
9325   if (!Previous.empty()) {
9326     // Determine whether NewFD is an overload of PrevDecl or
9327     // a declaration that requires merging. If it's an overload,
9328     // there's no more work to do here; we'll just add the new
9329     // function to the scope.
9330     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9331       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9332       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9333         Redeclaration = true;
9334         OldDecl = Candidate;
9335       }
9336     } else {
9337       MayNeedOverloadableChecks = true;
9338       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9339                             /*NewIsUsingDecl*/ false)) {
9340       case Ovl_Match:
9341         Redeclaration = true;
9342         break;
9343 
9344       case Ovl_NonFunction:
9345         Redeclaration = true;
9346         break;
9347 
9348       case Ovl_Overload:
9349         Redeclaration = false;
9350         break;
9351       }
9352     }
9353   }
9354 
9355   // Check for a previous extern "C" declaration with this name.
9356   if (!Redeclaration &&
9357       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9358     if (!Previous.empty()) {
9359       // This is an extern "C" declaration with the same name as a previous
9360       // declaration, and thus redeclares that entity...
9361       Redeclaration = true;
9362       OldDecl = Previous.getFoundDecl();
9363       MergeTypeWithPrevious = false;
9364 
9365       // ... except in the presence of __attribute__((overloadable)).
9366       if (OldDecl->hasAttr<OverloadableAttr>() ||
9367           NewFD->hasAttr<OverloadableAttr>()) {
9368         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9369           MayNeedOverloadableChecks = true;
9370           Redeclaration = false;
9371           OldDecl = nullptr;
9372         }
9373       }
9374     }
9375   }
9376 
9377   // C++11 [dcl.constexpr]p8:
9378   //   A constexpr specifier for a non-static member function that is not
9379   //   a constructor declares that member function to be const.
9380   //
9381   // This needs to be delayed until we know whether this is an out-of-line
9382   // definition of a static member function.
9383   //
9384   // This rule is not present in C++1y, so we produce a backwards
9385   // compatibility warning whenever it happens in C++11.
9386   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9387   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9388       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9389       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9390     CXXMethodDecl *OldMD = nullptr;
9391     if (OldDecl)
9392       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9393     if (!OldMD || !OldMD->isStatic()) {
9394       const FunctionProtoType *FPT =
9395         MD->getType()->castAs<FunctionProtoType>();
9396       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9397       EPI.TypeQuals |= Qualifiers::Const;
9398       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9399                                           FPT->getParamTypes(), EPI));
9400 
9401       // Warn that we did this, if we're not performing template instantiation.
9402       // In that case, we'll have warned already when the template was defined.
9403       if (!inTemplateInstantiation()) {
9404         SourceLocation AddConstLoc;
9405         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9406                 .IgnoreParens().getAs<FunctionTypeLoc>())
9407           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9408 
9409         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9410           << FixItHint::CreateInsertion(AddConstLoc, " const");
9411       }
9412     }
9413   }
9414 
9415   if (Redeclaration) {
9416     // NewFD and OldDecl represent declarations that need to be
9417     // merged.
9418     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9419       NewFD->setInvalidDecl();
9420       return Redeclaration;
9421     }
9422 
9423     Previous.clear();
9424     Previous.addDecl(OldDecl);
9425 
9426     if (FunctionTemplateDecl *OldTemplateDecl
9427                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9428       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9429       FunctionTemplateDecl *NewTemplateDecl
9430         = NewFD->getDescribedFunctionTemplate();
9431       assert(NewTemplateDecl && "Template/non-template mismatch");
9432       if (CXXMethodDecl *Method
9433             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9434         Method->setAccess(OldTemplateDecl->getAccess());
9435         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9436       }
9437 
9438       // If this is an explicit specialization of a member that is a function
9439       // template, mark it as a member specialization.
9440       if (IsMemberSpecialization &&
9441           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9442         NewTemplateDecl->setMemberSpecialization();
9443         assert(OldTemplateDecl->isMemberSpecialization());
9444         // Explicit specializations of a member template do not inherit deleted
9445         // status from the parent member template that they are specializing.
9446         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9447           FunctionDecl *const OldTemplatedDecl =
9448               OldTemplateDecl->getTemplatedDecl();
9449           // FIXME: This assert will not hold in the presence of modules.
9450           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9451           // FIXME: We need an update record for this AST mutation.
9452           OldTemplatedDecl->setDeletedAsWritten(false);
9453         }
9454       }
9455 
9456     } else {
9457       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9458         // This needs to happen first so that 'inline' propagates.
9459         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9460         if (isa<CXXMethodDecl>(NewFD))
9461           NewFD->setAccess(OldDecl->getAccess());
9462       }
9463     }
9464   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9465              !NewFD->getAttr<OverloadableAttr>()) {
9466     assert((Previous.empty() ||
9467             llvm::any_of(Previous,
9468                          [](const NamedDecl *ND) {
9469                            return ND->hasAttr<OverloadableAttr>();
9470                          })) &&
9471            "Non-redecls shouldn't happen without overloadable present");
9472 
9473     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9474       const auto *FD = dyn_cast<FunctionDecl>(ND);
9475       return FD && !FD->hasAttr<OverloadableAttr>();
9476     });
9477 
9478     if (OtherUnmarkedIter != Previous.end()) {
9479       Diag(NewFD->getLocation(),
9480            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9481       Diag((*OtherUnmarkedIter)->getLocation(),
9482            diag::note_attribute_overloadable_prev_overload)
9483           << false;
9484 
9485       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9486     }
9487   }
9488 
9489   // Semantic checking for this function declaration (in isolation).
9490 
9491   if (getLangOpts().CPlusPlus) {
9492     // C++-specific checks.
9493     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9494       CheckConstructor(Constructor);
9495     } else if (CXXDestructorDecl *Destructor =
9496                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9497       CXXRecordDecl *Record = Destructor->getParent();
9498       QualType ClassType = Context.getTypeDeclType(Record);
9499 
9500       // FIXME: Shouldn't we be able to perform this check even when the class
9501       // type is dependent? Both gcc and edg can handle that.
9502       if (!ClassType->isDependentType()) {
9503         DeclarationName Name
9504           = Context.DeclarationNames.getCXXDestructorName(
9505                                         Context.getCanonicalType(ClassType));
9506         if (NewFD->getDeclName() != Name) {
9507           Diag(NewFD->getLocation(), diag::err_destructor_name);
9508           NewFD->setInvalidDecl();
9509           return Redeclaration;
9510         }
9511       }
9512     } else if (CXXConversionDecl *Conversion
9513                = dyn_cast<CXXConversionDecl>(NewFD)) {
9514       ActOnConversionDeclarator(Conversion);
9515     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9516       if (auto *TD = Guide->getDescribedFunctionTemplate())
9517         CheckDeductionGuideTemplate(TD);
9518 
9519       // A deduction guide is not on the list of entities that can be
9520       // explicitly specialized.
9521       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9522         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9523             << /*explicit specialization*/ 1;
9524     }
9525 
9526     // Find any virtual functions that this function overrides.
9527     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9528       if (!Method->isFunctionTemplateSpecialization() &&
9529           !Method->getDescribedFunctionTemplate() &&
9530           Method->isCanonicalDecl()) {
9531         if (AddOverriddenMethods(Method->getParent(), Method)) {
9532           // If the function was marked as "static", we have a problem.
9533           if (NewFD->getStorageClass() == SC_Static) {
9534             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9535           }
9536         }
9537       }
9538 
9539       if (Method->isStatic())
9540         checkThisInStaticMemberFunctionType(Method);
9541     }
9542 
9543     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9544     if (NewFD->isOverloadedOperator() &&
9545         CheckOverloadedOperatorDeclaration(NewFD)) {
9546       NewFD->setInvalidDecl();
9547       return Redeclaration;
9548     }
9549 
9550     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9551     if (NewFD->getLiteralIdentifier() &&
9552         CheckLiteralOperatorDeclaration(NewFD)) {
9553       NewFD->setInvalidDecl();
9554       return Redeclaration;
9555     }
9556 
9557     // In C++, check default arguments now that we have merged decls. Unless
9558     // the lexical context is the class, because in this case this is done
9559     // during delayed parsing anyway.
9560     if (!CurContext->isRecord())
9561       CheckCXXDefaultArguments(NewFD);
9562 
9563     // If this function declares a builtin function, check the type of this
9564     // declaration against the expected type for the builtin.
9565     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9566       ASTContext::GetBuiltinTypeError Error;
9567       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9568       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9569       // If the type of the builtin differs only in its exception
9570       // specification, that's OK.
9571       // FIXME: If the types do differ in this way, it would be better to
9572       // retain the 'noexcept' form of the type.
9573       if (!T.isNull() &&
9574           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9575                                                             NewFD->getType()))
9576         // The type of this function differs from the type of the builtin,
9577         // so forget about the builtin entirely.
9578         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9579     }
9580 
9581     // If this function is declared as being extern "C", then check to see if
9582     // the function returns a UDT (class, struct, or union type) that is not C
9583     // compatible, and if it does, warn the user.
9584     // But, issue any diagnostic on the first declaration only.
9585     if (Previous.empty() && NewFD->isExternC()) {
9586       QualType R = NewFD->getReturnType();
9587       if (R->isIncompleteType() && !R->isVoidType())
9588         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9589             << NewFD << R;
9590       else if (!R.isPODType(Context) && !R->isVoidType() &&
9591                !R->isObjCObjectPointerType())
9592         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9593     }
9594 
9595     // C++1z [dcl.fct]p6:
9596     //   [...] whether the function has a non-throwing exception-specification
9597     //   [is] part of the function type
9598     //
9599     // This results in an ABI break between C++14 and C++17 for functions whose
9600     // declared type includes an exception-specification in a parameter or
9601     // return type. (Exception specifications on the function itself are OK in
9602     // most cases, and exception specifications are not permitted in most other
9603     // contexts where they could make it into a mangling.)
9604     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9605       auto HasNoexcept = [&](QualType T) -> bool {
9606         // Strip off declarator chunks that could be between us and a function
9607         // type. We don't need to look far, exception specifications are very
9608         // restricted prior to C++17.
9609         if (auto *RT = T->getAs<ReferenceType>())
9610           T = RT->getPointeeType();
9611         else if (T->isAnyPointerType())
9612           T = T->getPointeeType();
9613         else if (auto *MPT = T->getAs<MemberPointerType>())
9614           T = MPT->getPointeeType();
9615         if (auto *FPT = T->getAs<FunctionProtoType>())
9616           if (FPT->isNothrow(Context))
9617             return true;
9618         return false;
9619       };
9620 
9621       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9622       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9623       for (QualType T : FPT->param_types())
9624         AnyNoexcept |= HasNoexcept(T);
9625       if (AnyNoexcept)
9626         Diag(NewFD->getLocation(),
9627              diag::warn_cxx17_compat_exception_spec_in_signature)
9628             << NewFD;
9629     }
9630 
9631     if (!Redeclaration && LangOpts.CUDA)
9632       checkCUDATargetOverload(NewFD, Previous);
9633   }
9634   return Redeclaration;
9635 }
9636 
9637 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9638   // C++11 [basic.start.main]p3:
9639   //   A program that [...] declares main to be inline, static or
9640   //   constexpr is ill-formed.
9641   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9642   //   appear in a declaration of main.
9643   // static main is not an error under C99, but we should warn about it.
9644   // We accept _Noreturn main as an extension.
9645   if (FD->getStorageClass() == SC_Static)
9646     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9647          ? diag::err_static_main : diag::warn_static_main)
9648       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9649   if (FD->isInlineSpecified())
9650     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9651       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9652   if (DS.isNoreturnSpecified()) {
9653     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9654     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9655     Diag(NoreturnLoc, diag::ext_noreturn_main);
9656     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9657       << FixItHint::CreateRemoval(NoreturnRange);
9658   }
9659   if (FD->isConstexpr()) {
9660     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9661       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9662     FD->setConstexpr(false);
9663   }
9664 
9665   if (getLangOpts().OpenCL) {
9666     Diag(FD->getLocation(), diag::err_opencl_no_main)
9667         << FD->hasAttr<OpenCLKernelAttr>();
9668     FD->setInvalidDecl();
9669     return;
9670   }
9671 
9672   QualType T = FD->getType();
9673   assert(T->isFunctionType() && "function decl is not of function type");
9674   const FunctionType* FT = T->castAs<FunctionType>();
9675 
9676   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9677     // In C with GNU extensions we allow main() to have non-integer return
9678     // type, but we should warn about the extension, and we disable the
9679     // implicit-return-zero rule.
9680 
9681     // GCC in C mode accepts qualified 'int'.
9682     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9683       FD->setHasImplicitReturnZero(true);
9684     else {
9685       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9686       SourceRange RTRange = FD->getReturnTypeSourceRange();
9687       if (RTRange.isValid())
9688         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9689             << FixItHint::CreateReplacement(RTRange, "int");
9690     }
9691   } else {
9692     // In C and C++, main magically returns 0 if you fall off the end;
9693     // set the flag which tells us that.
9694     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9695 
9696     // All the standards say that main() should return 'int'.
9697     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9698       FD->setHasImplicitReturnZero(true);
9699     else {
9700       // Otherwise, this is just a flat-out error.
9701       SourceRange RTRange = FD->getReturnTypeSourceRange();
9702       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9703           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9704                                 : FixItHint());
9705       FD->setInvalidDecl(true);
9706     }
9707   }
9708 
9709   // Treat protoless main() as nullary.
9710   if (isa<FunctionNoProtoType>(FT)) return;
9711 
9712   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9713   unsigned nparams = FTP->getNumParams();
9714   assert(FD->getNumParams() == nparams);
9715 
9716   bool HasExtraParameters = (nparams > 3);
9717 
9718   if (FTP->isVariadic()) {
9719     Diag(FD->getLocation(), diag::ext_variadic_main);
9720     // FIXME: if we had information about the location of the ellipsis, we
9721     // could add a FixIt hint to remove it as a parameter.
9722   }
9723 
9724   // Darwin passes an undocumented fourth argument of type char**.  If
9725   // other platforms start sprouting these, the logic below will start
9726   // getting shifty.
9727   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9728     HasExtraParameters = false;
9729 
9730   if (HasExtraParameters) {
9731     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9732     FD->setInvalidDecl(true);
9733     nparams = 3;
9734   }
9735 
9736   // FIXME: a lot of the following diagnostics would be improved
9737   // if we had some location information about types.
9738 
9739   QualType CharPP =
9740     Context.getPointerType(Context.getPointerType(Context.CharTy));
9741   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9742 
9743   for (unsigned i = 0; i < nparams; ++i) {
9744     QualType AT = FTP->getParamType(i);
9745 
9746     bool mismatch = true;
9747 
9748     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9749       mismatch = false;
9750     else if (Expected[i] == CharPP) {
9751       // As an extension, the following forms are okay:
9752       //   char const **
9753       //   char const * const *
9754       //   char * const *
9755 
9756       QualifierCollector qs;
9757       const PointerType* PT;
9758       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9759           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9760           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9761                               Context.CharTy)) {
9762         qs.removeConst();
9763         mismatch = !qs.empty();
9764       }
9765     }
9766 
9767     if (mismatch) {
9768       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9769       // TODO: suggest replacing given type with expected type
9770       FD->setInvalidDecl(true);
9771     }
9772   }
9773 
9774   if (nparams == 1 && !FD->isInvalidDecl()) {
9775     Diag(FD->getLocation(), diag::warn_main_one_arg);
9776   }
9777 
9778   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9779     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9780     FD->setInvalidDecl();
9781   }
9782 }
9783 
9784 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9785   QualType T = FD->getType();
9786   assert(T->isFunctionType() && "function decl is not of function type");
9787   const FunctionType *FT = T->castAs<FunctionType>();
9788 
9789   // Set an implicit return of 'zero' if the function can return some integral,
9790   // enumeration, pointer or nullptr type.
9791   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9792       FT->getReturnType()->isAnyPointerType() ||
9793       FT->getReturnType()->isNullPtrType())
9794     // DllMain is exempt because a return value of zero means it failed.
9795     if (FD->getName() != "DllMain")
9796       FD->setHasImplicitReturnZero(true);
9797 
9798   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9799     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9800     FD->setInvalidDecl();
9801   }
9802 }
9803 
9804 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9805   // FIXME: Need strict checking.  In C89, we need to check for
9806   // any assignment, increment, decrement, function-calls, or
9807   // commas outside of a sizeof.  In C99, it's the same list,
9808   // except that the aforementioned are allowed in unevaluated
9809   // expressions.  Everything else falls under the
9810   // "may accept other forms of constant expressions" exception.
9811   // (We never end up here for C++, so the constant expression
9812   // rules there don't matter.)
9813   const Expr *Culprit;
9814   if (Init->isConstantInitializer(Context, false, &Culprit))
9815     return false;
9816   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9817     << Culprit->getSourceRange();
9818   return true;
9819 }
9820 
9821 namespace {
9822   // Visits an initialization expression to see if OrigDecl is evaluated in
9823   // its own initialization and throws a warning if it does.
9824   class SelfReferenceChecker
9825       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9826     Sema &S;
9827     Decl *OrigDecl;
9828     bool isRecordType;
9829     bool isPODType;
9830     bool isReferenceType;
9831 
9832     bool isInitList;
9833     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9834 
9835   public:
9836     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9837 
9838     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9839                                                     S(S), OrigDecl(OrigDecl) {
9840       isPODType = false;
9841       isRecordType = false;
9842       isReferenceType = false;
9843       isInitList = false;
9844       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9845         isPODType = VD->getType().isPODType(S.Context);
9846         isRecordType = VD->getType()->isRecordType();
9847         isReferenceType = VD->getType()->isReferenceType();
9848       }
9849     }
9850 
9851     // For most expressions, just call the visitor.  For initializer lists,
9852     // track the index of the field being initialized since fields are
9853     // initialized in order allowing use of previously initialized fields.
9854     void CheckExpr(Expr *E) {
9855       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9856       if (!InitList) {
9857         Visit(E);
9858         return;
9859       }
9860 
9861       // Track and increment the index here.
9862       isInitList = true;
9863       InitFieldIndex.push_back(0);
9864       for (auto Child : InitList->children()) {
9865         CheckExpr(cast<Expr>(Child));
9866         ++InitFieldIndex.back();
9867       }
9868       InitFieldIndex.pop_back();
9869     }
9870 
9871     // Returns true if MemberExpr is checked and no further checking is needed.
9872     // Returns false if additional checking is required.
9873     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9874       llvm::SmallVector<FieldDecl*, 4> Fields;
9875       Expr *Base = E;
9876       bool ReferenceField = false;
9877 
9878       // Get the field memebers used.
9879       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9880         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9881         if (!FD)
9882           return false;
9883         Fields.push_back(FD);
9884         if (FD->getType()->isReferenceType())
9885           ReferenceField = true;
9886         Base = ME->getBase()->IgnoreParenImpCasts();
9887       }
9888 
9889       // Keep checking only if the base Decl is the same.
9890       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9891       if (!DRE || DRE->getDecl() != OrigDecl)
9892         return false;
9893 
9894       // A reference field can be bound to an unininitialized field.
9895       if (CheckReference && !ReferenceField)
9896         return true;
9897 
9898       // Convert FieldDecls to their index number.
9899       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9900       for (const FieldDecl *I : llvm::reverse(Fields))
9901         UsedFieldIndex.push_back(I->getFieldIndex());
9902 
9903       // See if a warning is needed by checking the first difference in index
9904       // numbers.  If field being used has index less than the field being
9905       // initialized, then the use is safe.
9906       for (auto UsedIter = UsedFieldIndex.begin(),
9907                 UsedEnd = UsedFieldIndex.end(),
9908                 OrigIter = InitFieldIndex.begin(),
9909                 OrigEnd = InitFieldIndex.end();
9910            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9911         if (*UsedIter < *OrigIter)
9912           return true;
9913         if (*UsedIter > *OrigIter)
9914           break;
9915       }
9916 
9917       // TODO: Add a different warning which will print the field names.
9918       HandleDeclRefExpr(DRE);
9919       return true;
9920     }
9921 
9922     // For most expressions, the cast is directly above the DeclRefExpr.
9923     // For conditional operators, the cast can be outside the conditional
9924     // operator if both expressions are DeclRefExpr's.
9925     void HandleValue(Expr *E) {
9926       E = E->IgnoreParens();
9927       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9928         HandleDeclRefExpr(DRE);
9929         return;
9930       }
9931 
9932       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9933         Visit(CO->getCond());
9934         HandleValue(CO->getTrueExpr());
9935         HandleValue(CO->getFalseExpr());
9936         return;
9937       }
9938 
9939       if (BinaryConditionalOperator *BCO =
9940               dyn_cast<BinaryConditionalOperator>(E)) {
9941         Visit(BCO->getCond());
9942         HandleValue(BCO->getFalseExpr());
9943         return;
9944       }
9945 
9946       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9947         HandleValue(OVE->getSourceExpr());
9948         return;
9949       }
9950 
9951       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9952         if (BO->getOpcode() == BO_Comma) {
9953           Visit(BO->getLHS());
9954           HandleValue(BO->getRHS());
9955           return;
9956         }
9957       }
9958 
9959       if (isa<MemberExpr>(E)) {
9960         if (isInitList) {
9961           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9962                                       false /*CheckReference*/))
9963             return;
9964         }
9965 
9966         Expr *Base = E->IgnoreParenImpCasts();
9967         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9968           // Check for static member variables and don't warn on them.
9969           if (!isa<FieldDecl>(ME->getMemberDecl()))
9970             return;
9971           Base = ME->getBase()->IgnoreParenImpCasts();
9972         }
9973         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9974           HandleDeclRefExpr(DRE);
9975         return;
9976       }
9977 
9978       Visit(E);
9979     }
9980 
9981     // Reference types not handled in HandleValue are handled here since all
9982     // uses of references are bad, not just r-value uses.
9983     void VisitDeclRefExpr(DeclRefExpr *E) {
9984       if (isReferenceType)
9985         HandleDeclRefExpr(E);
9986     }
9987 
9988     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9989       if (E->getCastKind() == CK_LValueToRValue) {
9990         HandleValue(E->getSubExpr());
9991         return;
9992       }
9993 
9994       Inherited::VisitImplicitCastExpr(E);
9995     }
9996 
9997     void VisitMemberExpr(MemberExpr *E) {
9998       if (isInitList) {
9999         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10000           return;
10001       }
10002 
10003       // Don't warn on arrays since they can be treated as pointers.
10004       if (E->getType()->canDecayToPointerType()) return;
10005 
10006       // Warn when a non-static method call is followed by non-static member
10007       // field accesses, which is followed by a DeclRefExpr.
10008       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10009       bool Warn = (MD && !MD->isStatic());
10010       Expr *Base = E->getBase()->IgnoreParenImpCasts();
10011       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10012         if (!isa<FieldDecl>(ME->getMemberDecl()))
10013           Warn = false;
10014         Base = ME->getBase()->IgnoreParenImpCasts();
10015       }
10016 
10017       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10018         if (Warn)
10019           HandleDeclRefExpr(DRE);
10020         return;
10021       }
10022 
10023       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10024       // Visit that expression.
10025       Visit(Base);
10026     }
10027 
10028     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10029       Expr *Callee = E->getCallee();
10030 
10031       if (isa<UnresolvedLookupExpr>(Callee))
10032         return Inherited::VisitCXXOperatorCallExpr(E);
10033 
10034       Visit(Callee);
10035       for (auto Arg: E->arguments())
10036         HandleValue(Arg->IgnoreParenImpCasts());
10037     }
10038 
10039     void VisitUnaryOperator(UnaryOperator *E) {
10040       // For POD record types, addresses of its own members are well-defined.
10041       if (E->getOpcode() == UO_AddrOf && isRecordType &&
10042           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10043         if (!isPODType)
10044           HandleValue(E->getSubExpr());
10045         return;
10046       }
10047 
10048       if (E->isIncrementDecrementOp()) {
10049         HandleValue(E->getSubExpr());
10050         return;
10051       }
10052 
10053       Inherited::VisitUnaryOperator(E);
10054     }
10055 
10056     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10057 
10058     void VisitCXXConstructExpr(CXXConstructExpr *E) {
10059       if (E->getConstructor()->isCopyConstructor()) {
10060         Expr *ArgExpr = E->getArg(0);
10061         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10062           if (ILE->getNumInits() == 1)
10063             ArgExpr = ILE->getInit(0);
10064         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10065           if (ICE->getCastKind() == CK_NoOp)
10066             ArgExpr = ICE->getSubExpr();
10067         HandleValue(ArgExpr);
10068         return;
10069       }
10070       Inherited::VisitCXXConstructExpr(E);
10071     }
10072 
10073     void VisitCallExpr(CallExpr *E) {
10074       // Treat std::move as a use.
10075       if (E->isCallToStdMove()) {
10076         HandleValue(E->getArg(0));
10077         return;
10078       }
10079 
10080       Inherited::VisitCallExpr(E);
10081     }
10082 
10083     void VisitBinaryOperator(BinaryOperator *E) {
10084       if (E->isCompoundAssignmentOp()) {
10085         HandleValue(E->getLHS());
10086         Visit(E->getRHS());
10087         return;
10088       }
10089 
10090       Inherited::VisitBinaryOperator(E);
10091     }
10092 
10093     // A custom visitor for BinaryConditionalOperator is needed because the
10094     // regular visitor would check the condition and true expression separately
10095     // but both point to the same place giving duplicate diagnostics.
10096     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10097       Visit(E->getCond());
10098       Visit(E->getFalseExpr());
10099     }
10100 
10101     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10102       Decl* ReferenceDecl = DRE->getDecl();
10103       if (OrigDecl != ReferenceDecl) return;
10104       unsigned diag;
10105       if (isReferenceType) {
10106         diag = diag::warn_uninit_self_reference_in_reference_init;
10107       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10108         diag = diag::warn_static_self_reference_in_init;
10109       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10110                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10111                  DRE->getDecl()->getType()->isRecordType()) {
10112         diag = diag::warn_uninit_self_reference_in_init;
10113       } else {
10114         // Local variables will be handled by the CFG analysis.
10115         return;
10116       }
10117 
10118       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10119                             S.PDiag(diag)
10120                               << DRE->getNameInfo().getName()
10121                               << OrigDecl->getLocation()
10122                               << DRE->getSourceRange());
10123     }
10124   };
10125 
10126   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10127   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10128                                  bool DirectInit) {
10129     // Parameters arguments are occassionially constructed with itself,
10130     // for instance, in recursive functions.  Skip them.
10131     if (isa<ParmVarDecl>(OrigDecl))
10132       return;
10133 
10134     E = E->IgnoreParens();
10135 
10136     // Skip checking T a = a where T is not a record or reference type.
10137     // Doing so is a way to silence uninitialized warnings.
10138     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10139       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10140         if (ICE->getCastKind() == CK_LValueToRValue)
10141           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10142             if (DRE->getDecl() == OrigDecl)
10143               return;
10144 
10145     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10146   }
10147 } // end anonymous namespace
10148 
10149 namespace {
10150   // Simple wrapper to add the name of a variable or (if no variable is
10151   // available) a DeclarationName into a diagnostic.
10152   struct VarDeclOrName {
10153     VarDecl *VDecl;
10154     DeclarationName Name;
10155 
10156     friend const Sema::SemaDiagnosticBuilder &
10157     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10158       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10159     }
10160   };
10161 } // end anonymous namespace
10162 
10163 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10164                                             DeclarationName Name, QualType Type,
10165                                             TypeSourceInfo *TSI,
10166                                             SourceRange Range, bool DirectInit,
10167                                             Expr *Init) {
10168   bool IsInitCapture = !VDecl;
10169   assert((!VDecl || !VDecl->isInitCapture()) &&
10170          "init captures are expected to be deduced prior to initialization");
10171 
10172   VarDeclOrName VN{VDecl, Name};
10173 
10174   DeducedType *Deduced = Type->getContainedDeducedType();
10175   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10176 
10177   // C++11 [dcl.spec.auto]p3
10178   if (!Init) {
10179     assert(VDecl && "no init for init capture deduction?");
10180     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10181       << VDecl->getDeclName() << Type;
10182     return QualType();
10183   }
10184 
10185   ArrayRef<Expr*> DeduceInits = Init;
10186   if (DirectInit) {
10187     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10188       DeduceInits = PL->exprs();
10189   }
10190 
10191   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10192     assert(VDecl && "non-auto type for init capture deduction?");
10193     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10194     InitializationKind Kind = InitializationKind::CreateForInit(
10195         VDecl->getLocation(), DirectInit, Init);
10196     // FIXME: Initialization should not be taking a mutable list of inits.
10197     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10198     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10199                                                        InitsCopy);
10200   }
10201 
10202   if (DirectInit) {
10203     if (auto *IL = dyn_cast<InitListExpr>(Init))
10204       DeduceInits = IL->inits();
10205   }
10206 
10207   // Deduction only works if we have exactly one source expression.
10208   if (DeduceInits.empty()) {
10209     // It isn't possible to write this directly, but it is possible to
10210     // end up in this situation with "auto x(some_pack...);"
10211     Diag(Init->getLocStart(), IsInitCapture
10212                                   ? diag::err_init_capture_no_expression
10213                                   : diag::err_auto_var_init_no_expression)
10214         << VN << Type << Range;
10215     return QualType();
10216   }
10217 
10218   if (DeduceInits.size() > 1) {
10219     Diag(DeduceInits[1]->getLocStart(),
10220          IsInitCapture ? diag::err_init_capture_multiple_expressions
10221                        : diag::err_auto_var_init_multiple_expressions)
10222         << VN << Type << Range;
10223     return QualType();
10224   }
10225 
10226   Expr *DeduceInit = DeduceInits[0];
10227   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10228     Diag(Init->getLocStart(), IsInitCapture
10229                                   ? diag::err_init_capture_paren_braces
10230                                   : diag::err_auto_var_init_paren_braces)
10231         << isa<InitListExpr>(Init) << VN << Type << Range;
10232     return QualType();
10233   }
10234 
10235   // Expressions default to 'id' when we're in a debugger.
10236   bool DefaultedAnyToId = false;
10237   if (getLangOpts().DebuggerCastResultToId &&
10238       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10239     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10240     if (Result.isInvalid()) {
10241       return QualType();
10242     }
10243     Init = Result.get();
10244     DefaultedAnyToId = true;
10245   }
10246 
10247   // C++ [dcl.decomp]p1:
10248   //   If the assignment-expression [...] has array type A and no ref-qualifier
10249   //   is present, e has type cv A
10250   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10251       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10252       DeduceInit->getType()->isConstantArrayType())
10253     return Context.getQualifiedType(DeduceInit->getType(),
10254                                     Type.getQualifiers());
10255 
10256   QualType DeducedType;
10257   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10258     if (!IsInitCapture)
10259       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10260     else if (isa<InitListExpr>(Init))
10261       Diag(Range.getBegin(),
10262            diag::err_init_capture_deduction_failure_from_init_list)
10263           << VN
10264           << (DeduceInit->getType().isNull() ? TSI->getType()
10265                                              : DeduceInit->getType())
10266           << DeduceInit->getSourceRange();
10267     else
10268       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10269           << VN << TSI->getType()
10270           << (DeduceInit->getType().isNull() ? TSI->getType()
10271                                              : DeduceInit->getType())
10272           << DeduceInit->getSourceRange();
10273   }
10274 
10275   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10276   // 'id' instead of a specific object type prevents most of our usual
10277   // checks.
10278   // We only want to warn outside of template instantiations, though:
10279   // inside a template, the 'id' could have come from a parameter.
10280   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10281       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10282     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10283     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10284   }
10285 
10286   return DeducedType;
10287 }
10288 
10289 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10290                                          Expr *Init) {
10291   QualType DeducedType = deduceVarTypeFromInitializer(
10292       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10293       VDecl->getSourceRange(), DirectInit, Init);
10294   if (DeducedType.isNull()) {
10295     VDecl->setInvalidDecl();
10296     return true;
10297   }
10298 
10299   VDecl->setType(DeducedType);
10300   assert(VDecl->isLinkageValid());
10301 
10302   // In ARC, infer lifetime.
10303   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10304     VDecl->setInvalidDecl();
10305 
10306   // If this is a redeclaration, check that the type we just deduced matches
10307   // the previously declared type.
10308   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10309     // We never need to merge the type, because we cannot form an incomplete
10310     // array of auto, nor deduce such a type.
10311     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10312   }
10313 
10314   // Check the deduced type is valid for a variable declaration.
10315   CheckVariableDeclarationType(VDecl);
10316   return VDecl->isInvalidDecl();
10317 }
10318 
10319 /// AddInitializerToDecl - Adds the initializer Init to the
10320 /// declaration dcl. If DirectInit is true, this is C++ direct
10321 /// initialization rather than copy initialization.
10322 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10323   // If there is no declaration, there was an error parsing it.  Just ignore
10324   // the initializer.
10325   if (!RealDecl || RealDecl->isInvalidDecl()) {
10326     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10327     return;
10328   }
10329 
10330   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10331     // Pure-specifiers are handled in ActOnPureSpecifier.
10332     Diag(Method->getLocation(), diag::err_member_function_initialization)
10333       << Method->getDeclName() << Init->getSourceRange();
10334     Method->setInvalidDecl();
10335     return;
10336   }
10337 
10338   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10339   if (!VDecl) {
10340     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10341     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10342     RealDecl->setInvalidDecl();
10343     return;
10344   }
10345 
10346   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10347   if (VDecl->getType()->isUndeducedType()) {
10348     // Attempt typo correction early so that the type of the init expression can
10349     // be deduced based on the chosen correction if the original init contains a
10350     // TypoExpr.
10351     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10352     if (!Res.isUsable()) {
10353       RealDecl->setInvalidDecl();
10354       return;
10355     }
10356     Init = Res.get();
10357 
10358     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10359       return;
10360   }
10361 
10362   // dllimport cannot be used on variable definitions.
10363   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10364     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10365     VDecl->setInvalidDecl();
10366     return;
10367   }
10368 
10369   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10370     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10371     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10372     VDecl->setInvalidDecl();
10373     return;
10374   }
10375 
10376   if (!VDecl->getType()->isDependentType()) {
10377     // A definition must end up with a complete type, which means it must be
10378     // complete with the restriction that an array type might be completed by
10379     // the initializer; note that later code assumes this restriction.
10380     QualType BaseDeclType = VDecl->getType();
10381     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10382       BaseDeclType = Array->getElementType();
10383     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10384                             diag::err_typecheck_decl_incomplete_type)) {
10385       RealDecl->setInvalidDecl();
10386       return;
10387     }
10388 
10389     // The variable can not have an abstract class type.
10390     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10391                                diag::err_abstract_type_in_decl,
10392                                AbstractVariableType))
10393       VDecl->setInvalidDecl();
10394   }
10395 
10396   // If adding the initializer will turn this declaration into a definition,
10397   // and we already have a definition for this variable, diagnose or otherwise
10398   // handle the situation.
10399   VarDecl *Def;
10400   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10401       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10402       !VDecl->isThisDeclarationADemotedDefinition() &&
10403       checkVarDeclRedefinition(Def, VDecl))
10404     return;
10405 
10406   if (getLangOpts().CPlusPlus) {
10407     // C++ [class.static.data]p4
10408     //   If a static data member is of const integral or const
10409     //   enumeration type, its declaration in the class definition can
10410     //   specify a constant-initializer which shall be an integral
10411     //   constant expression (5.19). In that case, the member can appear
10412     //   in integral constant expressions. The member shall still be
10413     //   defined in a namespace scope if it is used in the program and the
10414     //   namespace scope definition shall not contain an initializer.
10415     //
10416     // We already performed a redefinition check above, but for static
10417     // data members we also need to check whether there was an in-class
10418     // declaration with an initializer.
10419     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10420       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10421           << VDecl->getDeclName();
10422       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10423            diag::note_previous_initializer)
10424           << 0;
10425       return;
10426     }
10427 
10428     if (VDecl->hasLocalStorage())
10429       getCurFunction()->setHasBranchProtectedScope();
10430 
10431     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10432       VDecl->setInvalidDecl();
10433       return;
10434     }
10435   }
10436 
10437   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10438   // a kernel function cannot be initialized."
10439   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10440     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10441     VDecl->setInvalidDecl();
10442     return;
10443   }
10444 
10445   // Get the decls type and save a reference for later, since
10446   // CheckInitializerTypes may change it.
10447   QualType DclT = VDecl->getType(), SavT = DclT;
10448 
10449   // Expressions default to 'id' when we're in a debugger
10450   // and we are assigning it to a variable of Objective-C pointer type.
10451   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10452       Init->getType() == Context.UnknownAnyTy) {
10453     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10454     if (Result.isInvalid()) {
10455       VDecl->setInvalidDecl();
10456       return;
10457     }
10458     Init = Result.get();
10459   }
10460 
10461   // Perform the initialization.
10462   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10463   if (!VDecl->isInvalidDecl()) {
10464     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10465     InitializationKind Kind = InitializationKind::CreateForInit(
10466         VDecl->getLocation(), DirectInit, Init);
10467 
10468     MultiExprArg Args = Init;
10469     if (CXXDirectInit)
10470       Args = MultiExprArg(CXXDirectInit->getExprs(),
10471                           CXXDirectInit->getNumExprs());
10472 
10473     // Try to correct any TypoExprs in the initialization arguments.
10474     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10475       ExprResult Res = CorrectDelayedTyposInExpr(
10476           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10477             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10478             return Init.Failed() ? ExprError() : E;
10479           });
10480       if (Res.isInvalid()) {
10481         VDecl->setInvalidDecl();
10482       } else if (Res.get() != Args[Idx]) {
10483         Args[Idx] = Res.get();
10484       }
10485     }
10486     if (VDecl->isInvalidDecl())
10487       return;
10488 
10489     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10490                                    /*TopLevelOfInitList=*/false,
10491                                    /*TreatUnavailableAsInvalid=*/false);
10492     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10493     if (Result.isInvalid()) {
10494       VDecl->setInvalidDecl();
10495       return;
10496     }
10497 
10498     Init = Result.getAs<Expr>();
10499   }
10500 
10501   // Check for self-references within variable initializers.
10502   // Variables declared within a function/method body (except for references)
10503   // are handled by a dataflow analysis.
10504   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10505       VDecl->getType()->isReferenceType()) {
10506     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10507   }
10508 
10509   // If the type changed, it means we had an incomplete type that was
10510   // completed by the initializer. For example:
10511   //   int ary[] = { 1, 3, 5 };
10512   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10513   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10514     VDecl->setType(DclT);
10515 
10516   if (!VDecl->isInvalidDecl()) {
10517     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10518 
10519     if (VDecl->hasAttr<BlocksAttr>())
10520       checkRetainCycles(VDecl, Init);
10521 
10522     // It is safe to assign a weak reference into a strong variable.
10523     // Although this code can still have problems:
10524     //   id x = self.weakProp;
10525     //   id y = self.weakProp;
10526     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10527     // paths through the function. This should be revisited if
10528     // -Wrepeated-use-of-weak is made flow-sensitive.
10529     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10530          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10531         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10532                          Init->getLocStart()))
10533       getCurFunction()->markSafeWeakUse(Init);
10534   }
10535 
10536   // The initialization is usually a full-expression.
10537   //
10538   // FIXME: If this is a braced initialization of an aggregate, it is not
10539   // an expression, and each individual field initializer is a separate
10540   // full-expression. For instance, in:
10541   //
10542   //   struct Temp { ~Temp(); };
10543   //   struct S { S(Temp); };
10544   //   struct T { S a, b; } t = { Temp(), Temp() }
10545   //
10546   // we should destroy the first Temp before constructing the second.
10547   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10548                                           false,
10549                                           VDecl->isConstexpr());
10550   if (Result.isInvalid()) {
10551     VDecl->setInvalidDecl();
10552     return;
10553   }
10554   Init = Result.get();
10555 
10556   // Attach the initializer to the decl.
10557   VDecl->setInit(Init);
10558 
10559   if (VDecl->isLocalVarDecl()) {
10560     // Don't check the initializer if the declaration is malformed.
10561     if (VDecl->isInvalidDecl()) {
10562       // do nothing
10563 
10564     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10565     // This is true even in OpenCL C++.
10566     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10567       CheckForConstantInitializer(Init, DclT);
10568 
10569     // Otherwise, C++ does not restrict the initializer.
10570     } else if (getLangOpts().CPlusPlus) {
10571       // do nothing
10572 
10573     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10574     // static storage duration shall be constant expressions or string literals.
10575     } else if (VDecl->getStorageClass() == SC_Static) {
10576       CheckForConstantInitializer(Init, DclT);
10577 
10578     // C89 is stricter than C99 for aggregate initializers.
10579     // C89 6.5.7p3: All the expressions [...] in an initializer list
10580     // for an object that has aggregate or union type shall be
10581     // constant expressions.
10582     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10583                isa<InitListExpr>(Init)) {
10584       const Expr *Culprit;
10585       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10586         Diag(Culprit->getExprLoc(),
10587              diag::ext_aggregate_init_not_constant)
10588           << Culprit->getSourceRange();
10589       }
10590     }
10591   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10592              VDecl->getLexicalDeclContext()->isRecord()) {
10593     // This is an in-class initialization for a static data member, e.g.,
10594     //
10595     // struct S {
10596     //   static const int value = 17;
10597     // };
10598 
10599     // C++ [class.mem]p4:
10600     //   A member-declarator can contain a constant-initializer only
10601     //   if it declares a static member (9.4) of const integral or
10602     //   const enumeration type, see 9.4.2.
10603     //
10604     // C++11 [class.static.data]p3:
10605     //   If a non-volatile non-inline const static data member is of integral
10606     //   or enumeration type, its declaration in the class definition can
10607     //   specify a brace-or-equal-initializer in which every initializer-clause
10608     //   that is an assignment-expression is a constant expression. A static
10609     //   data member of literal type can be declared in the class definition
10610     //   with the constexpr specifier; if so, its declaration shall specify a
10611     //   brace-or-equal-initializer in which every initializer-clause that is
10612     //   an assignment-expression is a constant expression.
10613 
10614     // Do nothing on dependent types.
10615     if (DclT->isDependentType()) {
10616 
10617     // Allow any 'static constexpr' members, whether or not they are of literal
10618     // type. We separately check that every constexpr variable is of literal
10619     // type.
10620     } else if (VDecl->isConstexpr()) {
10621 
10622     // Require constness.
10623     } else if (!DclT.isConstQualified()) {
10624       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10625         << Init->getSourceRange();
10626       VDecl->setInvalidDecl();
10627 
10628     // We allow integer constant expressions in all cases.
10629     } else if (DclT->isIntegralOrEnumerationType()) {
10630       // Check whether the expression is a constant expression.
10631       SourceLocation Loc;
10632       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10633         // In C++11, a non-constexpr const static data member with an
10634         // in-class initializer cannot be volatile.
10635         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10636       else if (Init->isValueDependent())
10637         ; // Nothing to check.
10638       else if (Init->isIntegerConstantExpr(Context, &Loc))
10639         ; // Ok, it's an ICE!
10640       else if (Init->isEvaluatable(Context)) {
10641         // If we can constant fold the initializer through heroics, accept it,
10642         // but report this as a use of an extension for -pedantic.
10643         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10644           << Init->getSourceRange();
10645       } else {
10646         // Otherwise, this is some crazy unknown case.  Report the issue at the
10647         // location provided by the isIntegerConstantExpr failed check.
10648         Diag(Loc, diag::err_in_class_initializer_non_constant)
10649           << Init->getSourceRange();
10650         VDecl->setInvalidDecl();
10651       }
10652 
10653     // We allow foldable floating-point constants as an extension.
10654     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10655       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10656       // it anyway and provide a fixit to add the 'constexpr'.
10657       if (getLangOpts().CPlusPlus11) {
10658         Diag(VDecl->getLocation(),
10659              diag::ext_in_class_initializer_float_type_cxx11)
10660             << DclT << Init->getSourceRange();
10661         Diag(VDecl->getLocStart(),
10662              diag::note_in_class_initializer_float_type_cxx11)
10663             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10664       } else {
10665         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10666           << DclT << Init->getSourceRange();
10667 
10668         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10669           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10670             << Init->getSourceRange();
10671           VDecl->setInvalidDecl();
10672         }
10673       }
10674 
10675     // Suggest adding 'constexpr' in C++11 for literal types.
10676     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10677       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10678         << DclT << Init->getSourceRange()
10679         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10680       VDecl->setConstexpr(true);
10681 
10682     } else {
10683       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10684         << DclT << Init->getSourceRange();
10685       VDecl->setInvalidDecl();
10686     }
10687   } else if (VDecl->isFileVarDecl()) {
10688     // In C, extern is typically used to avoid tentative definitions when
10689     // declaring variables in headers, but adding an intializer makes it a
10690     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10691     // In C++, extern is often used to give implictly static const variables
10692     // external linkage, so don't warn in that case. If selectany is present,
10693     // this might be header code intended for C and C++ inclusion, so apply the
10694     // C++ rules.
10695     if (VDecl->getStorageClass() == SC_Extern &&
10696         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10697          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10698         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10699         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10700       Diag(VDecl->getLocation(), diag::warn_extern_init);
10701 
10702     // C99 6.7.8p4. All file scoped initializers need to be constant.
10703     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10704       CheckForConstantInitializer(Init, DclT);
10705   }
10706 
10707   // We will represent direct-initialization similarly to copy-initialization:
10708   //    int x(1);  -as-> int x = 1;
10709   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10710   //
10711   // Clients that want to distinguish between the two forms, can check for
10712   // direct initializer using VarDecl::getInitStyle().
10713   // A major benefit is that clients that don't particularly care about which
10714   // exactly form was it (like the CodeGen) can handle both cases without
10715   // special case code.
10716 
10717   // C++ 8.5p11:
10718   // The form of initialization (using parentheses or '=') is generally
10719   // insignificant, but does matter when the entity being initialized has a
10720   // class type.
10721   if (CXXDirectInit) {
10722     assert(DirectInit && "Call-style initializer must be direct init.");
10723     VDecl->setInitStyle(VarDecl::CallInit);
10724   } else if (DirectInit) {
10725     // This must be list-initialization. No other way is direct-initialization.
10726     VDecl->setInitStyle(VarDecl::ListInit);
10727   }
10728 
10729   CheckCompleteVariableDeclaration(VDecl);
10730 }
10731 
10732 /// ActOnInitializerError - Given that there was an error parsing an
10733 /// initializer for the given declaration, try to return to some form
10734 /// of sanity.
10735 void Sema::ActOnInitializerError(Decl *D) {
10736   // Our main concern here is re-establishing invariants like "a
10737   // variable's type is either dependent or complete".
10738   if (!D || D->isInvalidDecl()) return;
10739 
10740   VarDecl *VD = dyn_cast<VarDecl>(D);
10741   if (!VD) return;
10742 
10743   // Bindings are not usable if we can't make sense of the initializer.
10744   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10745     for (auto *BD : DD->bindings())
10746       BD->setInvalidDecl();
10747 
10748   // Auto types are meaningless if we can't make sense of the initializer.
10749   if (ParsingInitForAutoVars.count(D)) {
10750     D->setInvalidDecl();
10751     return;
10752   }
10753 
10754   QualType Ty = VD->getType();
10755   if (Ty->isDependentType()) return;
10756 
10757   // Require a complete type.
10758   if (RequireCompleteType(VD->getLocation(),
10759                           Context.getBaseElementType(Ty),
10760                           diag::err_typecheck_decl_incomplete_type)) {
10761     VD->setInvalidDecl();
10762     return;
10763   }
10764 
10765   // Require a non-abstract type.
10766   if (RequireNonAbstractType(VD->getLocation(), Ty,
10767                              diag::err_abstract_type_in_decl,
10768                              AbstractVariableType)) {
10769     VD->setInvalidDecl();
10770     return;
10771   }
10772 
10773   // Don't bother complaining about constructors or destructors,
10774   // though.
10775 }
10776 
10777 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10778   // If there is no declaration, there was an error parsing it. Just ignore it.
10779   if (!RealDecl)
10780     return;
10781 
10782   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10783     QualType Type = Var->getType();
10784 
10785     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10786     if (isa<DecompositionDecl>(RealDecl)) {
10787       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10788       Var->setInvalidDecl();
10789       return;
10790     }
10791 
10792     if (Type->isUndeducedType() &&
10793         DeduceVariableDeclarationType(Var, false, nullptr))
10794       return;
10795 
10796     // C++11 [class.static.data]p3: A static data member can be declared with
10797     // the constexpr specifier; if so, its declaration shall specify
10798     // a brace-or-equal-initializer.
10799     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10800     // the definition of a variable [...] or the declaration of a static data
10801     // member.
10802     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10803         !Var->isThisDeclarationADemotedDefinition()) {
10804       if (Var->isStaticDataMember()) {
10805         // C++1z removes the relevant rule; the in-class declaration is always
10806         // a definition there.
10807         if (!getLangOpts().CPlusPlus1z) {
10808           Diag(Var->getLocation(),
10809                diag::err_constexpr_static_mem_var_requires_init)
10810             << Var->getDeclName();
10811           Var->setInvalidDecl();
10812           return;
10813         }
10814       } else {
10815         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10816         Var->setInvalidDecl();
10817         return;
10818       }
10819     }
10820 
10821     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10822     // definition having the concept specifier is called a variable concept. A
10823     // concept definition refers to [...] a variable concept and its initializer.
10824     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10825       if (VTD->isConcept()) {
10826         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10827         Var->setInvalidDecl();
10828         return;
10829       }
10830     }
10831 
10832     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10833     // be initialized.
10834     if (!Var->isInvalidDecl() &&
10835         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10836         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10837       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10838       Var->setInvalidDecl();
10839       return;
10840     }
10841 
10842     switch (Var->isThisDeclarationADefinition()) {
10843     case VarDecl::Definition:
10844       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10845         break;
10846 
10847       // We have an out-of-line definition of a static data member
10848       // that has an in-class initializer, so we type-check this like
10849       // a declaration.
10850       //
10851       // Fall through
10852 
10853     case VarDecl::DeclarationOnly:
10854       // It's only a declaration.
10855 
10856       // Block scope. C99 6.7p7: If an identifier for an object is
10857       // declared with no linkage (C99 6.2.2p6), the type for the
10858       // object shall be complete.
10859       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10860           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10861           RequireCompleteType(Var->getLocation(), Type,
10862                               diag::err_typecheck_decl_incomplete_type))
10863         Var->setInvalidDecl();
10864 
10865       // Make sure that the type is not abstract.
10866       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10867           RequireNonAbstractType(Var->getLocation(), Type,
10868                                  diag::err_abstract_type_in_decl,
10869                                  AbstractVariableType))
10870         Var->setInvalidDecl();
10871       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10872           Var->getStorageClass() == SC_PrivateExtern) {
10873         Diag(Var->getLocation(), diag::warn_private_extern);
10874         Diag(Var->getLocation(), diag::note_private_extern);
10875       }
10876 
10877       return;
10878 
10879     case VarDecl::TentativeDefinition:
10880       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10881       // object that has file scope without an initializer, and without a
10882       // storage-class specifier or with the storage-class specifier "static",
10883       // constitutes a tentative definition. Note: A tentative definition with
10884       // external linkage is valid (C99 6.2.2p5).
10885       if (!Var->isInvalidDecl()) {
10886         if (const IncompleteArrayType *ArrayT
10887                                     = Context.getAsIncompleteArrayType(Type)) {
10888           if (RequireCompleteType(Var->getLocation(),
10889                                   ArrayT->getElementType(),
10890                                   diag::err_illegal_decl_array_incomplete_type))
10891             Var->setInvalidDecl();
10892         } else if (Var->getStorageClass() == SC_Static) {
10893           // C99 6.9.2p3: If the declaration of an identifier for an object is
10894           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10895           // declared type shall not be an incomplete type.
10896           // NOTE: code such as the following
10897           //     static struct s;
10898           //     struct s { int a; };
10899           // is accepted by gcc. Hence here we issue a warning instead of
10900           // an error and we do not invalidate the static declaration.
10901           // NOTE: to avoid multiple warnings, only check the first declaration.
10902           if (Var->isFirstDecl())
10903             RequireCompleteType(Var->getLocation(), Type,
10904                                 diag::ext_typecheck_decl_incomplete_type);
10905         }
10906       }
10907 
10908       // Record the tentative definition; we're done.
10909       if (!Var->isInvalidDecl())
10910         TentativeDefinitions.push_back(Var);
10911       return;
10912     }
10913 
10914     // Provide a specific diagnostic for uninitialized variable
10915     // definitions with incomplete array type.
10916     if (Type->isIncompleteArrayType()) {
10917       Diag(Var->getLocation(),
10918            diag::err_typecheck_incomplete_array_needs_initializer);
10919       Var->setInvalidDecl();
10920       return;
10921     }
10922 
10923     // Provide a specific diagnostic for uninitialized variable
10924     // definitions with reference type.
10925     if (Type->isReferenceType()) {
10926       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10927         << Var->getDeclName()
10928         << SourceRange(Var->getLocation(), Var->getLocation());
10929       Var->setInvalidDecl();
10930       return;
10931     }
10932 
10933     // Do not attempt to type-check the default initializer for a
10934     // variable with dependent type.
10935     if (Type->isDependentType())
10936       return;
10937 
10938     if (Var->isInvalidDecl())
10939       return;
10940 
10941     if (!Var->hasAttr<AliasAttr>()) {
10942       if (RequireCompleteType(Var->getLocation(),
10943                               Context.getBaseElementType(Type),
10944                               diag::err_typecheck_decl_incomplete_type)) {
10945         Var->setInvalidDecl();
10946         return;
10947       }
10948     } else {
10949       return;
10950     }
10951 
10952     // The variable can not have an abstract class type.
10953     if (RequireNonAbstractType(Var->getLocation(), Type,
10954                                diag::err_abstract_type_in_decl,
10955                                AbstractVariableType)) {
10956       Var->setInvalidDecl();
10957       return;
10958     }
10959 
10960     // Check for jumps past the implicit initializer.  C++0x
10961     // clarifies that this applies to a "variable with automatic
10962     // storage duration", not a "local variable".
10963     // C++11 [stmt.dcl]p3
10964     //   A program that jumps from a point where a variable with automatic
10965     //   storage duration is not in scope to a point where it is in scope is
10966     //   ill-formed unless the variable has scalar type, class type with a
10967     //   trivial default constructor and a trivial destructor, a cv-qualified
10968     //   version of one of these types, or an array of one of the preceding
10969     //   types and is declared without an initializer.
10970     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10971       if (const RecordType *Record
10972             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10973         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10974         // Mark the function for further checking even if the looser rules of
10975         // C++11 do not require such checks, so that we can diagnose
10976         // incompatibilities with C++98.
10977         if (!CXXRecord->isPOD())
10978           getCurFunction()->setHasBranchProtectedScope();
10979       }
10980     }
10981 
10982     // C++03 [dcl.init]p9:
10983     //   If no initializer is specified for an object, and the
10984     //   object is of (possibly cv-qualified) non-POD class type (or
10985     //   array thereof), the object shall be default-initialized; if
10986     //   the object is of const-qualified type, the underlying class
10987     //   type shall have a user-declared default
10988     //   constructor. Otherwise, if no initializer is specified for
10989     //   a non- static object, the object and its subobjects, if
10990     //   any, have an indeterminate initial value); if the object
10991     //   or any of its subobjects are of const-qualified type, the
10992     //   program is ill-formed.
10993     // C++0x [dcl.init]p11:
10994     //   If no initializer is specified for an object, the object is
10995     //   default-initialized; [...].
10996     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10997     InitializationKind Kind
10998       = InitializationKind::CreateDefault(Var->getLocation());
10999 
11000     InitializationSequence InitSeq(*this, Entity, Kind, None);
11001     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11002     if (Init.isInvalid())
11003       Var->setInvalidDecl();
11004     else if (Init.get()) {
11005       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11006       // This is important for template substitution.
11007       Var->setInitStyle(VarDecl::CallInit);
11008     }
11009 
11010     CheckCompleteVariableDeclaration(Var);
11011   }
11012 }
11013 
11014 void Sema::ActOnCXXForRangeDecl(Decl *D) {
11015   // If there is no declaration, there was an error parsing it. Ignore it.
11016   if (!D)
11017     return;
11018 
11019   VarDecl *VD = dyn_cast<VarDecl>(D);
11020   if (!VD) {
11021     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11022     D->setInvalidDecl();
11023     return;
11024   }
11025 
11026   VD->setCXXForRangeDecl(true);
11027 
11028   // for-range-declaration cannot be given a storage class specifier.
11029   int Error = -1;
11030   switch (VD->getStorageClass()) {
11031   case SC_None:
11032     break;
11033   case SC_Extern:
11034     Error = 0;
11035     break;
11036   case SC_Static:
11037     Error = 1;
11038     break;
11039   case SC_PrivateExtern:
11040     Error = 2;
11041     break;
11042   case SC_Auto:
11043     Error = 3;
11044     break;
11045   case SC_Register:
11046     Error = 4;
11047     break;
11048   }
11049   if (Error != -1) {
11050     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11051       << VD->getDeclName() << Error;
11052     D->setInvalidDecl();
11053   }
11054 }
11055 
11056 StmtResult
11057 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11058                                  IdentifierInfo *Ident,
11059                                  ParsedAttributes &Attrs,
11060                                  SourceLocation AttrEnd) {
11061   // C++1y [stmt.iter]p1:
11062   //   A range-based for statement of the form
11063   //      for ( for-range-identifier : for-range-initializer ) statement
11064   //   is equivalent to
11065   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11066   DeclSpec DS(Attrs.getPool().getFactory());
11067 
11068   const char *PrevSpec;
11069   unsigned DiagID;
11070   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11071                      getPrintingPolicy());
11072 
11073   Declarator D(DS, Declarator::ForContext);
11074   D.SetIdentifier(Ident, IdentLoc);
11075   D.takeAttributes(Attrs, AttrEnd);
11076 
11077   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11078   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11079                 EmptyAttrs, IdentLoc);
11080   Decl *Var = ActOnDeclarator(S, D);
11081   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11082   FinalizeDeclaration(Var);
11083   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11084                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11085 }
11086 
11087 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11088   if (var->isInvalidDecl()) return;
11089 
11090   if (getLangOpts().OpenCL) {
11091     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11092     // initialiser
11093     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11094         !var->hasInit()) {
11095       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11096           << 1 /*Init*/;
11097       var->setInvalidDecl();
11098       return;
11099     }
11100   }
11101 
11102   // In Objective-C, don't allow jumps past the implicit initialization of a
11103   // local retaining variable.
11104   if (getLangOpts().ObjC1 &&
11105       var->hasLocalStorage()) {
11106     switch (var->getType().getObjCLifetime()) {
11107     case Qualifiers::OCL_None:
11108     case Qualifiers::OCL_ExplicitNone:
11109     case Qualifiers::OCL_Autoreleasing:
11110       break;
11111 
11112     case Qualifiers::OCL_Weak:
11113     case Qualifiers::OCL_Strong:
11114       getCurFunction()->setHasBranchProtectedScope();
11115       break;
11116     }
11117   }
11118 
11119   // Warn about externally-visible variables being defined without a
11120   // prior declaration.  We only want to do this for global
11121   // declarations, but we also specifically need to avoid doing it for
11122   // class members because the linkage of an anonymous class can
11123   // change if it's later given a typedef name.
11124   if (var->isThisDeclarationADefinition() &&
11125       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11126       var->isExternallyVisible() && var->hasLinkage() &&
11127       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11128                                   var->getLocation())) {
11129     // Find a previous declaration that's not a definition.
11130     VarDecl *prev = var->getPreviousDecl();
11131     while (prev && prev->isThisDeclarationADefinition())
11132       prev = prev->getPreviousDecl();
11133 
11134     if (!prev)
11135       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11136   }
11137 
11138   // Cache the result of checking for constant initialization.
11139   Optional<bool> CacheHasConstInit;
11140   const Expr *CacheCulprit;
11141   auto checkConstInit = [&]() mutable {
11142     if (!CacheHasConstInit)
11143       CacheHasConstInit = var->getInit()->isConstantInitializer(
11144             Context, var->getType()->isReferenceType(), &CacheCulprit);
11145     return *CacheHasConstInit;
11146   };
11147 
11148   if (var->getTLSKind() == VarDecl::TLS_Static) {
11149     if (var->getType().isDestructedType()) {
11150       // GNU C++98 edits for __thread, [basic.start.term]p3:
11151       //   The type of an object with thread storage duration shall not
11152       //   have a non-trivial destructor.
11153       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11154       if (getLangOpts().CPlusPlus11)
11155         Diag(var->getLocation(), diag::note_use_thread_local);
11156     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11157       if (!checkConstInit()) {
11158         // GNU C++98 edits for __thread, [basic.start.init]p4:
11159         //   An object of thread storage duration shall not require dynamic
11160         //   initialization.
11161         // FIXME: Need strict checking here.
11162         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11163           << CacheCulprit->getSourceRange();
11164         if (getLangOpts().CPlusPlus11)
11165           Diag(var->getLocation(), diag::note_use_thread_local);
11166       }
11167     }
11168   }
11169 
11170   // Apply section attributes and pragmas to global variables.
11171   bool GlobalStorage = var->hasGlobalStorage();
11172   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11173       !inTemplateInstantiation()) {
11174     PragmaStack<StringLiteral *> *Stack = nullptr;
11175     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11176     if (var->getType().isConstQualified())
11177       Stack = &ConstSegStack;
11178     else if (!var->getInit()) {
11179       Stack = &BSSSegStack;
11180       SectionFlags |= ASTContext::PSF_Write;
11181     } else {
11182       Stack = &DataSegStack;
11183       SectionFlags |= ASTContext::PSF_Write;
11184     }
11185     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11186       var->addAttr(SectionAttr::CreateImplicit(
11187           Context, SectionAttr::Declspec_allocate,
11188           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11189     }
11190     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11191       if (UnifySection(SA->getName(), SectionFlags, var))
11192         var->dropAttr<SectionAttr>();
11193 
11194     // Apply the init_seg attribute if this has an initializer.  If the
11195     // initializer turns out to not be dynamic, we'll end up ignoring this
11196     // attribute.
11197     if (CurInitSeg && var->getInit())
11198       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11199                                                CurInitSegLoc));
11200   }
11201 
11202   // All the following checks are C++ only.
11203   if (!getLangOpts().CPlusPlus) {
11204       // If this variable must be emitted, add it as an initializer for the
11205       // current module.
11206      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11207        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11208      return;
11209   }
11210 
11211   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11212     CheckCompleteDecompositionDeclaration(DD);
11213 
11214   QualType type = var->getType();
11215   if (type->isDependentType()) return;
11216 
11217   // __block variables might require us to capture a copy-initializer.
11218   if (var->hasAttr<BlocksAttr>()) {
11219     // It's currently invalid to ever have a __block variable with an
11220     // array type; should we diagnose that here?
11221 
11222     // Regardless, we don't want to ignore array nesting when
11223     // constructing this copy.
11224     if (type->isStructureOrClassType()) {
11225       EnterExpressionEvaluationContext scope(
11226           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11227       SourceLocation poi = var->getLocation();
11228       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11229       ExprResult result
11230         = PerformMoveOrCopyInitialization(
11231             InitializedEntity::InitializeBlock(poi, type, false),
11232             var, var->getType(), varRef, /*AllowNRVO=*/true);
11233       if (!result.isInvalid()) {
11234         result = MaybeCreateExprWithCleanups(result);
11235         Expr *init = result.getAs<Expr>();
11236         Context.setBlockVarCopyInits(var, init);
11237       }
11238     }
11239   }
11240 
11241   Expr *Init = var->getInit();
11242   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11243   QualType baseType = Context.getBaseElementType(type);
11244 
11245   if (Init && !Init->isValueDependent()) {
11246     if (var->isConstexpr()) {
11247       SmallVector<PartialDiagnosticAt, 8> Notes;
11248       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11249         SourceLocation DiagLoc = var->getLocation();
11250         // If the note doesn't add any useful information other than a source
11251         // location, fold it into the primary diagnostic.
11252         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11253               diag::note_invalid_subexpr_in_const_expr) {
11254           DiagLoc = Notes[0].first;
11255           Notes.clear();
11256         }
11257         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11258           << var << Init->getSourceRange();
11259         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11260           Diag(Notes[I].first, Notes[I].second);
11261       }
11262     } else if (var->isUsableInConstantExpressions(Context)) {
11263       // Check whether the initializer of a const variable of integral or
11264       // enumeration type is an ICE now, since we can't tell whether it was
11265       // initialized by a constant expression if we check later.
11266       var->checkInitIsICE();
11267     }
11268 
11269     // Don't emit further diagnostics about constexpr globals since they
11270     // were just diagnosed.
11271     if (!var->isConstexpr() && GlobalStorage &&
11272             var->hasAttr<RequireConstantInitAttr>()) {
11273       // FIXME: Need strict checking in C++03 here.
11274       bool DiagErr = getLangOpts().CPlusPlus11
11275           ? !var->checkInitIsICE() : !checkConstInit();
11276       if (DiagErr) {
11277         auto attr = var->getAttr<RequireConstantInitAttr>();
11278         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11279           << Init->getSourceRange();
11280         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11281           << attr->getRange();
11282         if (getLangOpts().CPlusPlus11) {
11283           APValue Value;
11284           SmallVector<PartialDiagnosticAt, 8> Notes;
11285           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11286           for (auto &it : Notes)
11287             Diag(it.first, it.second);
11288         } else {
11289           Diag(CacheCulprit->getExprLoc(),
11290                diag::note_invalid_subexpr_in_const_expr)
11291               << CacheCulprit->getSourceRange();
11292         }
11293       }
11294     }
11295     else if (!var->isConstexpr() && IsGlobal &&
11296              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11297                                     var->getLocation())) {
11298       // Warn about globals which don't have a constant initializer.  Don't
11299       // warn about globals with a non-trivial destructor because we already
11300       // warned about them.
11301       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11302       if (!(RD && !RD->hasTrivialDestructor())) {
11303         if (!checkConstInit())
11304           Diag(var->getLocation(), diag::warn_global_constructor)
11305             << Init->getSourceRange();
11306       }
11307     }
11308   }
11309 
11310   // Require the destructor.
11311   if (const RecordType *recordType = baseType->getAs<RecordType>())
11312     FinalizeVarWithDestructor(var, recordType);
11313 
11314   // If this variable must be emitted, add it as an initializer for the current
11315   // module.
11316   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11317     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11318 }
11319 
11320 /// \brief Determines if a variable's alignment is dependent.
11321 static bool hasDependentAlignment(VarDecl *VD) {
11322   if (VD->getType()->isDependentType())
11323     return true;
11324   for (auto *I : VD->specific_attrs<AlignedAttr>())
11325     if (I->isAlignmentDependent())
11326       return true;
11327   return false;
11328 }
11329 
11330 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11331 /// any semantic actions necessary after any initializer has been attached.
11332 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11333   // Note that we are no longer parsing the initializer for this declaration.
11334   ParsingInitForAutoVars.erase(ThisDecl);
11335 
11336   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11337   if (!VD)
11338     return;
11339 
11340   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11341   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11342       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11343     if (PragmaClangBSSSection.Valid)
11344       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11345                                                             PragmaClangBSSSection.SectionName,
11346                                                             PragmaClangBSSSection.PragmaLocation));
11347     if (PragmaClangDataSection.Valid)
11348       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11349                                                              PragmaClangDataSection.SectionName,
11350                                                              PragmaClangDataSection.PragmaLocation));
11351     if (PragmaClangRodataSection.Valid)
11352       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11353                                                                PragmaClangRodataSection.SectionName,
11354                                                                PragmaClangRodataSection.PragmaLocation));
11355   }
11356 
11357   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11358     for (auto *BD : DD->bindings()) {
11359       FinalizeDeclaration(BD);
11360     }
11361   }
11362 
11363   checkAttributesAfterMerging(*this, *VD);
11364 
11365   // Perform TLS alignment check here after attributes attached to the variable
11366   // which may affect the alignment have been processed. Only perform the check
11367   // if the target has a maximum TLS alignment (zero means no constraints).
11368   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11369     // Protect the check so that it's not performed on dependent types and
11370     // dependent alignments (we can't determine the alignment in that case).
11371     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11372         !VD->isInvalidDecl()) {
11373       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11374       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11375         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11376           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11377           << (unsigned)MaxAlignChars.getQuantity();
11378       }
11379     }
11380   }
11381 
11382   if (VD->isStaticLocal()) {
11383     if (FunctionDecl *FD =
11384             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11385       // Static locals inherit dll attributes from their function.
11386       if (Attr *A = getDLLAttr(FD)) {
11387         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11388         NewAttr->setInherited(true);
11389         VD->addAttr(NewAttr);
11390       }
11391       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11392       // function, only __shared__ variables may be declared with
11393       // static storage class.
11394       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11395           CUDADiagIfDeviceCode(VD->getLocation(),
11396                                diag::err_device_static_local_var)
11397               << CurrentCUDATarget())
11398         VD->setInvalidDecl();
11399     }
11400   }
11401 
11402   // Perform check for initializers of device-side global variables.
11403   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11404   // 7.5). We must also apply the same checks to all __shared__
11405   // variables whether they are local or not. CUDA also allows
11406   // constant initializers for __constant__ and __device__ variables.
11407   if (getLangOpts().CUDA) {
11408     const Expr *Init = VD->getInit();
11409     if (Init && VD->hasGlobalStorage()) {
11410       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11411           VD->hasAttr<CUDASharedAttr>()) {
11412         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11413         bool AllowedInit = false;
11414         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11415           AllowedInit =
11416               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11417         // We'll allow constant initializers even if it's a non-empty
11418         // constructor according to CUDA rules. This deviates from NVCC,
11419         // but allows us to handle things like constexpr constructors.
11420         if (!AllowedInit &&
11421             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11422           AllowedInit = VD->getInit()->isConstantInitializer(
11423               Context, VD->getType()->isReferenceType());
11424 
11425         // Also make sure that destructor, if there is one, is empty.
11426         if (AllowedInit)
11427           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11428             AllowedInit =
11429                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11430 
11431         if (!AllowedInit) {
11432           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11433                                       ? diag::err_shared_var_init
11434                                       : diag::err_dynamic_var_init)
11435               << Init->getSourceRange();
11436           VD->setInvalidDecl();
11437         }
11438       } else {
11439         // This is a host-side global variable.  Check that the initializer is
11440         // callable from the host side.
11441         const FunctionDecl *InitFn = nullptr;
11442         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11443           InitFn = CE->getConstructor();
11444         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11445           InitFn = CE->getDirectCallee();
11446         }
11447         if (InitFn) {
11448           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11449           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11450             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11451                 << InitFnTarget << InitFn;
11452             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11453             VD->setInvalidDecl();
11454           }
11455         }
11456       }
11457     }
11458   }
11459 
11460   // Grab the dllimport or dllexport attribute off of the VarDecl.
11461   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11462 
11463   // Imported static data members cannot be defined out-of-line.
11464   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11465     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11466         VD->isThisDeclarationADefinition()) {
11467       // We allow definitions of dllimport class template static data members
11468       // with a warning.
11469       CXXRecordDecl *Context =
11470         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11471       bool IsClassTemplateMember =
11472           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11473           Context->getDescribedClassTemplate();
11474 
11475       Diag(VD->getLocation(),
11476            IsClassTemplateMember
11477                ? diag::warn_attribute_dllimport_static_field_definition
11478                : diag::err_attribute_dllimport_static_field_definition);
11479       Diag(IA->getLocation(), diag::note_attribute);
11480       if (!IsClassTemplateMember)
11481         VD->setInvalidDecl();
11482     }
11483   }
11484 
11485   // dllimport/dllexport variables cannot be thread local, their TLS index
11486   // isn't exported with the variable.
11487   if (DLLAttr && VD->getTLSKind()) {
11488     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11489     if (F && getDLLAttr(F)) {
11490       assert(VD->isStaticLocal());
11491       // But if this is a static local in a dlimport/dllexport function, the
11492       // function will never be inlined, which means the var would never be
11493       // imported, so having it marked import/export is safe.
11494     } else {
11495       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11496                                                                     << DLLAttr;
11497       VD->setInvalidDecl();
11498     }
11499   }
11500 
11501   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11502     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11503       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11504       VD->dropAttr<UsedAttr>();
11505     }
11506   }
11507 
11508   const DeclContext *DC = VD->getDeclContext();
11509   // If there's a #pragma GCC visibility in scope, and this isn't a class
11510   // member, set the visibility of this variable.
11511   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11512     AddPushedVisibilityAttribute(VD);
11513 
11514   // FIXME: Warn on unused var template partial specializations.
11515   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11516     MarkUnusedFileScopedDecl(VD);
11517 
11518   // Now we have parsed the initializer and can update the table of magic
11519   // tag values.
11520   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11521       !VD->getType()->isIntegralOrEnumerationType())
11522     return;
11523 
11524   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11525     const Expr *MagicValueExpr = VD->getInit();
11526     if (!MagicValueExpr) {
11527       continue;
11528     }
11529     llvm::APSInt MagicValueInt;
11530     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11531       Diag(I->getRange().getBegin(),
11532            diag::err_type_tag_for_datatype_not_ice)
11533         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11534       continue;
11535     }
11536     if (MagicValueInt.getActiveBits() > 64) {
11537       Diag(I->getRange().getBegin(),
11538            diag::err_type_tag_for_datatype_too_large)
11539         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11540       continue;
11541     }
11542     uint64_t MagicValue = MagicValueInt.getZExtValue();
11543     RegisterTypeTagForDatatype(I->getArgumentKind(),
11544                                MagicValue,
11545                                I->getMatchingCType(),
11546                                I->getLayoutCompatible(),
11547                                I->getMustBeNull());
11548   }
11549 }
11550 
11551 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11552   auto *VD = dyn_cast<VarDecl>(DD);
11553   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11554 }
11555 
11556 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11557                                                    ArrayRef<Decl *> Group) {
11558   SmallVector<Decl*, 8> Decls;
11559 
11560   if (DS.isTypeSpecOwned())
11561     Decls.push_back(DS.getRepAsDecl());
11562 
11563   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11564   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11565   bool DiagnosedMultipleDecomps = false;
11566   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11567   bool DiagnosedNonDeducedAuto = false;
11568 
11569   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11570     if (Decl *D = Group[i]) {
11571       // For declarators, there are some additional syntactic-ish checks we need
11572       // to perform.
11573       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11574         if (!FirstDeclaratorInGroup)
11575           FirstDeclaratorInGroup = DD;
11576         if (!FirstDecompDeclaratorInGroup)
11577           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11578         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11579             !hasDeducedAuto(DD))
11580           FirstNonDeducedAutoInGroup = DD;
11581 
11582         if (FirstDeclaratorInGroup != DD) {
11583           // A decomposition declaration cannot be combined with any other
11584           // declaration in the same group.
11585           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11586             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11587                  diag::err_decomp_decl_not_alone)
11588                 << FirstDeclaratorInGroup->getSourceRange()
11589                 << DD->getSourceRange();
11590             DiagnosedMultipleDecomps = true;
11591           }
11592 
11593           // A declarator that uses 'auto' in any way other than to declare a
11594           // variable with a deduced type cannot be combined with any other
11595           // declarator in the same group.
11596           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11597             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11598                  diag::err_auto_non_deduced_not_alone)
11599                 << FirstNonDeducedAutoInGroup->getType()
11600                        ->hasAutoForTrailingReturnType()
11601                 << FirstDeclaratorInGroup->getSourceRange()
11602                 << DD->getSourceRange();
11603             DiagnosedNonDeducedAuto = true;
11604           }
11605         }
11606       }
11607 
11608       Decls.push_back(D);
11609     }
11610   }
11611 
11612   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11613     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11614       handleTagNumbering(Tag, S);
11615       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11616           getLangOpts().CPlusPlus)
11617         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11618     }
11619   }
11620 
11621   return BuildDeclaratorGroup(Decls);
11622 }
11623 
11624 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11625 /// group, performing any necessary semantic checking.
11626 Sema::DeclGroupPtrTy
11627 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11628   // C++14 [dcl.spec.auto]p7: (DR1347)
11629   //   If the type that replaces the placeholder type is not the same in each
11630   //   deduction, the program is ill-formed.
11631   if (Group.size() > 1) {
11632     QualType Deduced;
11633     VarDecl *DeducedDecl = nullptr;
11634     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11635       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11636       if (!D || D->isInvalidDecl())
11637         break;
11638       DeducedType *DT = D->getType()->getContainedDeducedType();
11639       if (!DT || DT->getDeducedType().isNull())
11640         continue;
11641       if (Deduced.isNull()) {
11642         Deduced = DT->getDeducedType();
11643         DeducedDecl = D;
11644       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11645         auto *AT = dyn_cast<AutoType>(DT);
11646         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11647              diag::err_auto_different_deductions)
11648           << (AT ? (unsigned)AT->getKeyword() : 3)
11649           << Deduced << DeducedDecl->getDeclName()
11650           << DT->getDeducedType() << D->getDeclName()
11651           << DeducedDecl->getInit()->getSourceRange()
11652           << D->getInit()->getSourceRange();
11653         D->setInvalidDecl();
11654         break;
11655       }
11656     }
11657   }
11658 
11659   ActOnDocumentableDecls(Group);
11660 
11661   return DeclGroupPtrTy::make(
11662       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11663 }
11664 
11665 void Sema::ActOnDocumentableDecl(Decl *D) {
11666   ActOnDocumentableDecls(D);
11667 }
11668 
11669 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11670   // Don't parse the comment if Doxygen diagnostics are ignored.
11671   if (Group.empty() || !Group[0])
11672     return;
11673 
11674   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11675                       Group[0]->getLocation()) &&
11676       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11677                       Group[0]->getLocation()))
11678     return;
11679 
11680   if (Group.size() >= 2) {
11681     // This is a decl group.  Normally it will contain only declarations
11682     // produced from declarator list.  But in case we have any definitions or
11683     // additional declaration references:
11684     //   'typedef struct S {} S;'
11685     //   'typedef struct S *S;'
11686     //   'struct S *pS;'
11687     // FinalizeDeclaratorGroup adds these as separate declarations.
11688     Decl *MaybeTagDecl = Group[0];
11689     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11690       Group = Group.slice(1);
11691     }
11692   }
11693 
11694   // See if there are any new comments that are not attached to a decl.
11695   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11696   if (!Comments.empty() &&
11697       !Comments.back()->isAttached()) {
11698     // There is at least one comment that not attached to a decl.
11699     // Maybe it should be attached to one of these decls?
11700     //
11701     // Note that this way we pick up not only comments that precede the
11702     // declaration, but also comments that *follow* the declaration -- thanks to
11703     // the lookahead in the lexer: we've consumed the semicolon and looked
11704     // ahead through comments.
11705     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11706       Context.getCommentForDecl(Group[i], &PP);
11707   }
11708 }
11709 
11710 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11711 /// to introduce parameters into function prototype scope.
11712 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11713   const DeclSpec &DS = D.getDeclSpec();
11714 
11715   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11716 
11717   // C++03 [dcl.stc]p2 also permits 'auto'.
11718   StorageClass SC = SC_None;
11719   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11720     SC = SC_Register;
11721   } else if (getLangOpts().CPlusPlus &&
11722              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11723     SC = SC_Auto;
11724   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11725     Diag(DS.getStorageClassSpecLoc(),
11726          diag::err_invalid_storage_class_in_func_decl);
11727     D.getMutableDeclSpec().ClearStorageClassSpecs();
11728   }
11729 
11730   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11731     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11732       << DeclSpec::getSpecifierName(TSCS);
11733   if (DS.isInlineSpecified())
11734     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11735         << getLangOpts().CPlusPlus1z;
11736   if (DS.isConstexprSpecified())
11737     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11738       << 0;
11739   if (DS.isConceptSpecified())
11740     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11741 
11742   DiagnoseFunctionSpecifiers(DS);
11743 
11744   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11745   QualType parmDeclType = TInfo->getType();
11746 
11747   if (getLangOpts().CPlusPlus) {
11748     // Check that there are no default arguments inside the type of this
11749     // parameter.
11750     CheckExtraCXXDefaultArguments(D);
11751 
11752     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11753     if (D.getCXXScopeSpec().isSet()) {
11754       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11755         << D.getCXXScopeSpec().getRange();
11756       D.getCXXScopeSpec().clear();
11757     }
11758   }
11759 
11760   // Ensure we have a valid name
11761   IdentifierInfo *II = nullptr;
11762   if (D.hasName()) {
11763     II = D.getIdentifier();
11764     if (!II) {
11765       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11766         << GetNameForDeclarator(D).getName();
11767       D.setInvalidType(true);
11768     }
11769   }
11770 
11771   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11772   if (II) {
11773     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11774                    ForVisibleRedeclaration);
11775     LookupName(R, S);
11776     if (R.isSingleResult()) {
11777       NamedDecl *PrevDecl = R.getFoundDecl();
11778       if (PrevDecl->isTemplateParameter()) {
11779         // Maybe we will complain about the shadowed template parameter.
11780         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11781         // Just pretend that we didn't see the previous declaration.
11782         PrevDecl = nullptr;
11783       } else if (S->isDeclScope(PrevDecl)) {
11784         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11785         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11786 
11787         // Recover by removing the name
11788         II = nullptr;
11789         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11790         D.setInvalidType(true);
11791       }
11792     }
11793   }
11794 
11795   // Temporarily put parameter variables in the translation unit, not
11796   // the enclosing context.  This prevents them from accidentally
11797   // looking like class members in C++.
11798   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11799                                     D.getLocStart(),
11800                                     D.getIdentifierLoc(), II,
11801                                     parmDeclType, TInfo,
11802                                     SC);
11803 
11804   if (D.isInvalidType())
11805     New->setInvalidDecl();
11806 
11807   assert(S->isFunctionPrototypeScope());
11808   assert(S->getFunctionPrototypeDepth() >= 1);
11809   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11810                     S->getNextFunctionPrototypeIndex());
11811 
11812   // Add the parameter declaration into this scope.
11813   S->AddDecl(New);
11814   if (II)
11815     IdResolver.AddDecl(New);
11816 
11817   ProcessDeclAttributes(S, New, D);
11818 
11819   if (D.getDeclSpec().isModulePrivateSpecified())
11820     Diag(New->getLocation(), diag::err_module_private_local)
11821       << 1 << New->getDeclName()
11822       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11823       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11824 
11825   if (New->hasAttr<BlocksAttr>()) {
11826     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11827   }
11828   return New;
11829 }
11830 
11831 /// \brief Synthesizes a variable for a parameter arising from a
11832 /// typedef.
11833 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11834                                               SourceLocation Loc,
11835                                               QualType T) {
11836   /* FIXME: setting StartLoc == Loc.
11837      Would it be worth to modify callers so as to provide proper source
11838      location for the unnamed parameters, embedding the parameter's type? */
11839   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11840                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11841                                            SC_None, nullptr);
11842   Param->setImplicit();
11843   return Param;
11844 }
11845 
11846 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11847   // Don't diagnose unused-parameter errors in template instantiations; we
11848   // will already have done so in the template itself.
11849   if (inTemplateInstantiation())
11850     return;
11851 
11852   for (const ParmVarDecl *Parameter : Parameters) {
11853     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11854         !Parameter->hasAttr<UnusedAttr>()) {
11855       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11856         << Parameter->getDeclName();
11857     }
11858   }
11859 }
11860 
11861 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11862     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11863   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11864     return;
11865 
11866   // Warn if the return value is pass-by-value and larger than the specified
11867   // threshold.
11868   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11869     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11870     if (Size > LangOpts.NumLargeByValueCopy)
11871       Diag(D->getLocation(), diag::warn_return_value_size)
11872           << D->getDeclName() << Size;
11873   }
11874 
11875   // Warn if any parameter is pass-by-value and larger than the specified
11876   // threshold.
11877   for (const ParmVarDecl *Parameter : Parameters) {
11878     QualType T = Parameter->getType();
11879     if (T->isDependentType() || !T.isPODType(Context))
11880       continue;
11881     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11882     if (Size > LangOpts.NumLargeByValueCopy)
11883       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11884           << Parameter->getDeclName() << Size;
11885   }
11886 }
11887 
11888 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11889                                   SourceLocation NameLoc, IdentifierInfo *Name,
11890                                   QualType T, TypeSourceInfo *TSInfo,
11891                                   StorageClass SC) {
11892   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11893   if (getLangOpts().ObjCAutoRefCount &&
11894       T.getObjCLifetime() == Qualifiers::OCL_None &&
11895       T->isObjCLifetimeType()) {
11896 
11897     Qualifiers::ObjCLifetime lifetime;
11898 
11899     // Special cases for arrays:
11900     //   - if it's const, use __unsafe_unretained
11901     //   - otherwise, it's an error
11902     if (T->isArrayType()) {
11903       if (!T.isConstQualified()) {
11904         DelayedDiagnostics.add(
11905             sema::DelayedDiagnostic::makeForbiddenType(
11906             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11907       }
11908       lifetime = Qualifiers::OCL_ExplicitNone;
11909     } else {
11910       lifetime = T->getObjCARCImplicitLifetime();
11911     }
11912     T = Context.getLifetimeQualifiedType(T, lifetime);
11913   }
11914 
11915   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11916                                          Context.getAdjustedParameterType(T),
11917                                          TSInfo, SC, nullptr);
11918 
11919   // Parameters can not be abstract class types.
11920   // For record types, this is done by the AbstractClassUsageDiagnoser once
11921   // the class has been completely parsed.
11922   if (!CurContext->isRecord() &&
11923       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11924                              AbstractParamType))
11925     New->setInvalidDecl();
11926 
11927   // Parameter declarators cannot be interface types. All ObjC objects are
11928   // passed by reference.
11929   if (T->isObjCObjectType()) {
11930     SourceLocation TypeEndLoc =
11931         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11932     Diag(NameLoc,
11933          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11934       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11935     T = Context.getObjCObjectPointerType(T);
11936     New->setType(T);
11937   }
11938 
11939   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11940   // duration shall not be qualified by an address-space qualifier."
11941   // Since all parameters have automatic store duration, they can not have
11942   // an address space.
11943   if (T.getAddressSpace() != LangAS::Default &&
11944       // OpenCL allows function arguments declared to be an array of a type
11945       // to be qualified with an address space.
11946       !(getLangOpts().OpenCL &&
11947         (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
11948     Diag(NameLoc, diag::err_arg_with_address_space);
11949     New->setInvalidDecl();
11950   }
11951 
11952   return New;
11953 }
11954 
11955 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11956                                            SourceLocation LocAfterDecls) {
11957   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11958 
11959   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11960   // for a K&R function.
11961   if (!FTI.hasPrototype) {
11962     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11963       --i;
11964       if (FTI.Params[i].Param == nullptr) {
11965         SmallString<256> Code;
11966         llvm::raw_svector_ostream(Code)
11967             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11968         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11969             << FTI.Params[i].Ident
11970             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11971 
11972         // Implicitly declare the argument as type 'int' for lack of a better
11973         // type.
11974         AttributeFactory attrs;
11975         DeclSpec DS(attrs);
11976         const char* PrevSpec; // unused
11977         unsigned DiagID; // unused
11978         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11979                            DiagID, Context.getPrintingPolicy());
11980         // Use the identifier location for the type source range.
11981         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11982         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11983         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11984         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11985         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11986       }
11987     }
11988   }
11989 }
11990 
11991 Decl *
11992 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11993                               MultiTemplateParamsArg TemplateParameterLists,
11994                               SkipBodyInfo *SkipBody) {
11995   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11996   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11997   Scope *ParentScope = FnBodyScope->getParent();
11998 
11999   D.setFunctionDefinitionKind(FDK_Definition);
12000   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12001   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12002 }
12003 
12004 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12005   Consumer.HandleInlineFunctionDefinition(D);
12006 }
12007 
12008 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12009                              const FunctionDecl*& PossibleZeroParamPrototype) {
12010   // Don't warn about invalid declarations.
12011   if (FD->isInvalidDecl())
12012     return false;
12013 
12014   // Or declarations that aren't global.
12015   if (!FD->isGlobal())
12016     return false;
12017 
12018   // Don't warn about C++ member functions.
12019   if (isa<CXXMethodDecl>(FD))
12020     return false;
12021 
12022   // Don't warn about 'main'.
12023   if (FD->isMain())
12024     return false;
12025 
12026   // Don't warn about inline functions.
12027   if (FD->isInlined())
12028     return false;
12029 
12030   // Don't warn about function templates.
12031   if (FD->getDescribedFunctionTemplate())
12032     return false;
12033 
12034   // Don't warn about function template specializations.
12035   if (FD->isFunctionTemplateSpecialization())
12036     return false;
12037 
12038   // Don't warn for OpenCL kernels.
12039   if (FD->hasAttr<OpenCLKernelAttr>())
12040     return false;
12041 
12042   // Don't warn on explicitly deleted functions.
12043   if (FD->isDeleted())
12044     return false;
12045 
12046   bool MissingPrototype = true;
12047   for (const FunctionDecl *Prev = FD->getPreviousDecl();
12048        Prev; Prev = Prev->getPreviousDecl()) {
12049     // Ignore any declarations that occur in function or method
12050     // scope, because they aren't visible from the header.
12051     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12052       continue;
12053 
12054     MissingPrototype = !Prev->getType()->isFunctionProtoType();
12055     if (FD->getNumParams() == 0)
12056       PossibleZeroParamPrototype = Prev;
12057     break;
12058   }
12059 
12060   return MissingPrototype;
12061 }
12062 
12063 void
12064 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12065                                    const FunctionDecl *EffectiveDefinition,
12066                                    SkipBodyInfo *SkipBody) {
12067   const FunctionDecl *Definition = EffectiveDefinition;
12068   if (!Definition)
12069     if (!FD->isDefined(Definition))
12070       return;
12071 
12072   if (canRedefineFunction(Definition, getLangOpts()))
12073     return;
12074 
12075   // Don't emit an error when this is redefinition of a typo-corrected
12076   // definition.
12077   if (TypoCorrectedFunctionDefinitions.count(Definition))
12078     return;
12079 
12080   // If we don't have a visible definition of the function, and it's inline or
12081   // a template, skip the new definition.
12082   if (SkipBody && !hasVisibleDefinition(Definition) &&
12083       (Definition->getFormalLinkage() == InternalLinkage ||
12084        Definition->isInlined() ||
12085        Definition->getDescribedFunctionTemplate() ||
12086        Definition->getNumTemplateParameterLists())) {
12087     SkipBody->ShouldSkip = true;
12088     if (auto *TD = Definition->getDescribedFunctionTemplate())
12089       makeMergedDefinitionVisible(TD);
12090     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12091     return;
12092   }
12093 
12094   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12095       Definition->getStorageClass() == SC_Extern)
12096     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12097         << FD->getDeclName() << getLangOpts().CPlusPlus;
12098   else
12099     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12100 
12101   Diag(Definition->getLocation(), diag::note_previous_definition);
12102   FD->setInvalidDecl();
12103 }
12104 
12105 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12106                                    Sema &S) {
12107   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12108 
12109   LambdaScopeInfo *LSI = S.PushLambdaScope();
12110   LSI->CallOperator = CallOperator;
12111   LSI->Lambda = LambdaClass;
12112   LSI->ReturnType = CallOperator->getReturnType();
12113   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12114 
12115   if (LCD == LCD_None)
12116     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12117   else if (LCD == LCD_ByCopy)
12118     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12119   else if (LCD == LCD_ByRef)
12120     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12121   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12122 
12123   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12124   LSI->Mutable = !CallOperator->isConst();
12125 
12126   // Add the captures to the LSI so they can be noted as already
12127   // captured within tryCaptureVar.
12128   auto I = LambdaClass->field_begin();
12129   for (const auto &C : LambdaClass->captures()) {
12130     if (C.capturesVariable()) {
12131       VarDecl *VD = C.getCapturedVar();
12132       if (VD->isInitCapture())
12133         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12134       QualType CaptureType = VD->getType();
12135       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12136       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12137           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12138           /*EllipsisLoc*/C.isPackExpansion()
12139                          ? C.getEllipsisLoc() : SourceLocation(),
12140           CaptureType, /*Expr*/ nullptr);
12141 
12142     } else if (C.capturesThis()) {
12143       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12144                               /*Expr*/ nullptr,
12145                               C.getCaptureKind() == LCK_StarThis);
12146     } else {
12147       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12148     }
12149     ++I;
12150   }
12151 }
12152 
12153 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12154                                     SkipBodyInfo *SkipBody) {
12155   if (!D)
12156     return D;
12157   FunctionDecl *FD = nullptr;
12158 
12159   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12160     FD = FunTmpl->getTemplatedDecl();
12161   else
12162     FD = cast<FunctionDecl>(D);
12163 
12164   // Check for defining attributes before the check for redefinition.
12165   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12166     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12167     FD->dropAttr<AliasAttr>();
12168     FD->setInvalidDecl();
12169   }
12170   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12171     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12172     FD->dropAttr<IFuncAttr>();
12173     FD->setInvalidDecl();
12174   }
12175 
12176   // See if this is a redefinition. If 'will have body' is already set, then
12177   // these checks were already performed when it was set.
12178   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12179     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12180 
12181     // If we're skipping the body, we're done. Don't enter the scope.
12182     if (SkipBody && SkipBody->ShouldSkip)
12183       return D;
12184   }
12185 
12186   // Mark this function as "will have a body eventually".  This lets users to
12187   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12188   // this function.
12189   FD->setWillHaveBody();
12190 
12191   // If we are instantiating a generic lambda call operator, push
12192   // a LambdaScopeInfo onto the function stack.  But use the information
12193   // that's already been calculated (ActOnLambdaExpr) to prime the current
12194   // LambdaScopeInfo.
12195   // When the template operator is being specialized, the LambdaScopeInfo,
12196   // has to be properly restored so that tryCaptureVariable doesn't try
12197   // and capture any new variables. In addition when calculating potential
12198   // captures during transformation of nested lambdas, it is necessary to
12199   // have the LSI properly restored.
12200   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12201     assert(inTemplateInstantiation() &&
12202            "There should be an active template instantiation on the stack "
12203            "when instantiating a generic lambda!");
12204     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12205   } else {
12206     // Enter a new function scope
12207     PushFunctionScope();
12208   }
12209 
12210   // Builtin functions cannot be defined.
12211   if (unsigned BuiltinID = FD->getBuiltinID()) {
12212     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12213         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12214       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12215       FD->setInvalidDecl();
12216     }
12217   }
12218 
12219   // The return type of a function definition must be complete
12220   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12221   QualType ResultType = FD->getReturnType();
12222   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12223       !FD->isInvalidDecl() &&
12224       RequireCompleteType(FD->getLocation(), ResultType,
12225                           diag::err_func_def_incomplete_result))
12226     FD->setInvalidDecl();
12227 
12228   if (FnBodyScope)
12229     PushDeclContext(FnBodyScope, FD);
12230 
12231   // Check the validity of our function parameters
12232   CheckParmsForFunctionDef(FD->parameters(),
12233                            /*CheckParameterNames=*/true);
12234 
12235   // Add non-parameter declarations already in the function to the current
12236   // scope.
12237   if (FnBodyScope) {
12238     for (Decl *NPD : FD->decls()) {
12239       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12240       if (!NonParmDecl)
12241         continue;
12242       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12243              "parameters should not be in newly created FD yet");
12244 
12245       // If the decl has a name, make it accessible in the current scope.
12246       if (NonParmDecl->getDeclName())
12247         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12248 
12249       // Similarly, dive into enums and fish their constants out, making them
12250       // accessible in this scope.
12251       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12252         for (auto *EI : ED->enumerators())
12253           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12254       }
12255     }
12256   }
12257 
12258   // Introduce our parameters into the function scope
12259   for (auto Param : FD->parameters()) {
12260     Param->setOwningFunction(FD);
12261 
12262     // If this has an identifier, add it to the scope stack.
12263     if (Param->getIdentifier() && FnBodyScope) {
12264       CheckShadow(FnBodyScope, Param);
12265 
12266       PushOnScopeChains(Param, FnBodyScope);
12267     }
12268   }
12269 
12270   // Ensure that the function's exception specification is instantiated.
12271   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12272     ResolveExceptionSpec(D->getLocation(), FPT);
12273 
12274   // dllimport cannot be applied to non-inline function definitions.
12275   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12276       !FD->isTemplateInstantiation()) {
12277     assert(!FD->hasAttr<DLLExportAttr>());
12278     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12279     FD->setInvalidDecl();
12280     return D;
12281   }
12282   // We want to attach documentation to original Decl (which might be
12283   // a function template).
12284   ActOnDocumentableDecl(D);
12285   if (getCurLexicalContext()->isObjCContainer() &&
12286       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12287       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12288     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12289 
12290   return D;
12291 }
12292 
12293 /// \brief Given the set of return statements within a function body,
12294 /// compute the variables that are subject to the named return value
12295 /// optimization.
12296 ///
12297 /// Each of the variables that is subject to the named return value
12298 /// optimization will be marked as NRVO variables in the AST, and any
12299 /// return statement that has a marked NRVO variable as its NRVO candidate can
12300 /// use the named return value optimization.
12301 ///
12302 /// This function applies a very simplistic algorithm for NRVO: if every return
12303 /// statement in the scope of a variable has the same NRVO candidate, that
12304 /// candidate is an NRVO variable.
12305 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12306   ReturnStmt **Returns = Scope->Returns.data();
12307 
12308   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12309     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12310       if (!NRVOCandidate->isNRVOVariable())
12311         Returns[I]->setNRVOCandidate(nullptr);
12312     }
12313   }
12314 }
12315 
12316 bool Sema::canDelayFunctionBody(const Declarator &D) {
12317   // We can't delay parsing the body of a constexpr function template (yet).
12318   if (D.getDeclSpec().isConstexprSpecified())
12319     return false;
12320 
12321   // We can't delay parsing the body of a function template with a deduced
12322   // return type (yet).
12323   if (D.getDeclSpec().hasAutoTypeSpec()) {
12324     // If the placeholder introduces a non-deduced trailing return type,
12325     // we can still delay parsing it.
12326     if (D.getNumTypeObjects()) {
12327       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12328       if (Outer.Kind == DeclaratorChunk::Function &&
12329           Outer.Fun.hasTrailingReturnType()) {
12330         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12331         return Ty.isNull() || !Ty->isUndeducedType();
12332       }
12333     }
12334     return false;
12335   }
12336 
12337   return true;
12338 }
12339 
12340 bool Sema::canSkipFunctionBody(Decl *D) {
12341   // We cannot skip the body of a function (or function template) which is
12342   // constexpr, since we may need to evaluate its body in order to parse the
12343   // rest of the file.
12344   // We cannot skip the body of a function with an undeduced return type,
12345   // because any callers of that function need to know the type.
12346   if (const FunctionDecl *FD = D->getAsFunction())
12347     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12348       return false;
12349   return Consumer.shouldSkipFunctionBody(D);
12350 }
12351 
12352 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12353   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12354     FD->setHasSkippedBody();
12355   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12356     MD->setHasSkippedBody();
12357   return Decl;
12358 }
12359 
12360 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12361   return ActOnFinishFunctionBody(D, BodyArg, false);
12362 }
12363 
12364 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12365                                     bool IsInstantiation) {
12366   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12367 
12368   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12369   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12370 
12371   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12372     CheckCompletedCoroutineBody(FD, Body);
12373 
12374   if (FD) {
12375     FD->setBody(Body);
12376     FD->setWillHaveBody(false);
12377 
12378     if (getLangOpts().CPlusPlus14) {
12379       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12380           FD->getReturnType()->isUndeducedType()) {
12381         // If the function has a deduced result type but contains no 'return'
12382         // statements, the result type as written must be exactly 'auto', and
12383         // the deduced result type is 'void'.
12384         if (!FD->getReturnType()->getAs<AutoType>()) {
12385           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12386               << FD->getReturnType();
12387           FD->setInvalidDecl();
12388         } else {
12389           // Substitute 'void' for the 'auto' in the type.
12390           TypeLoc ResultType = getReturnTypeLoc(FD);
12391           Context.adjustDeducedFunctionResultType(
12392               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12393         }
12394       }
12395     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12396       // In C++11, we don't use 'auto' deduction rules for lambda call
12397       // operators because we don't support return type deduction.
12398       auto *LSI = getCurLambda();
12399       if (LSI->HasImplicitReturnType) {
12400         deduceClosureReturnType(*LSI);
12401 
12402         // C++11 [expr.prim.lambda]p4:
12403         //   [...] if there are no return statements in the compound-statement
12404         //   [the deduced type is] the type void
12405         QualType RetType =
12406             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12407 
12408         // Update the return type to the deduced type.
12409         const FunctionProtoType *Proto =
12410             FD->getType()->getAs<FunctionProtoType>();
12411         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12412                                             Proto->getExtProtoInfo()));
12413       }
12414     }
12415 
12416     // If the function implicitly returns zero (like 'main') or is naked,
12417     // don't complain about missing return statements.
12418     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12419       WP.disableCheckFallThrough();
12420 
12421     // MSVC permits the use of pure specifier (=0) on function definition,
12422     // defined at class scope, warn about this non-standard construct.
12423     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12424       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12425 
12426     if (!FD->isInvalidDecl()) {
12427       // Don't diagnose unused parameters of defaulted or deleted functions.
12428       if (!FD->isDeleted() && !FD->isDefaulted())
12429         DiagnoseUnusedParameters(FD->parameters());
12430       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12431                                              FD->getReturnType(), FD);
12432 
12433       // If this is a structor, we need a vtable.
12434       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12435         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12436       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12437         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12438 
12439       // Try to apply the named return value optimization. We have to check
12440       // if we can do this here because lambdas keep return statements around
12441       // to deduce an implicit return type.
12442       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12443           !FD->isDependentContext())
12444         computeNRVO(Body, getCurFunction());
12445     }
12446 
12447     // GNU warning -Wmissing-prototypes:
12448     //   Warn if a global function is defined without a previous
12449     //   prototype declaration. This warning is issued even if the
12450     //   definition itself provides a prototype. The aim is to detect
12451     //   global functions that fail to be declared in header files.
12452     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12453     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12454       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12455 
12456       if (PossibleZeroParamPrototype) {
12457         // We found a declaration that is not a prototype,
12458         // but that could be a zero-parameter prototype
12459         if (TypeSourceInfo *TI =
12460                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12461           TypeLoc TL = TI->getTypeLoc();
12462           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12463             Diag(PossibleZeroParamPrototype->getLocation(),
12464                  diag::note_declaration_not_a_prototype)
12465                 << PossibleZeroParamPrototype
12466                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12467         }
12468       }
12469 
12470       // GNU warning -Wstrict-prototypes
12471       //   Warn if K&R function is defined without a previous declaration.
12472       //   This warning is issued only if the definition itself does not provide
12473       //   a prototype. Only K&R definitions do not provide a prototype.
12474       //   An empty list in a function declarator that is part of a definition
12475       //   of that function specifies that the function has no parameters
12476       //   (C99 6.7.5.3p14)
12477       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12478           !LangOpts.CPlusPlus) {
12479         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12480         TypeLoc TL = TI->getTypeLoc();
12481         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12482         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12483       }
12484     }
12485 
12486     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12487       const CXXMethodDecl *KeyFunction;
12488       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12489           MD->isVirtual() &&
12490           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12491           MD == KeyFunction->getCanonicalDecl()) {
12492         // Update the key-function state if necessary for this ABI.
12493         if (FD->isInlined() &&
12494             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12495           Context.setNonKeyFunction(MD);
12496 
12497           // If the newly-chosen key function is already defined, then we
12498           // need to mark the vtable as used retroactively.
12499           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12500           const FunctionDecl *Definition;
12501           if (KeyFunction && KeyFunction->isDefined(Definition))
12502             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12503         } else {
12504           // We just defined they key function; mark the vtable as used.
12505           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12506         }
12507       }
12508     }
12509 
12510     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12511            "Function parsing confused");
12512   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12513     assert(MD == getCurMethodDecl() && "Method parsing confused");
12514     MD->setBody(Body);
12515     if (!MD->isInvalidDecl()) {
12516       DiagnoseUnusedParameters(MD->parameters());
12517       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12518                                              MD->getReturnType(), MD);
12519 
12520       if (Body)
12521         computeNRVO(Body, getCurFunction());
12522     }
12523     if (getCurFunction()->ObjCShouldCallSuper) {
12524       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12525         << MD->getSelector().getAsString();
12526       getCurFunction()->ObjCShouldCallSuper = false;
12527     }
12528     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12529       const ObjCMethodDecl *InitMethod = nullptr;
12530       bool isDesignated =
12531           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12532       assert(isDesignated && InitMethod);
12533       (void)isDesignated;
12534 
12535       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12536         auto IFace = MD->getClassInterface();
12537         if (!IFace)
12538           return false;
12539         auto SuperD = IFace->getSuperClass();
12540         if (!SuperD)
12541           return false;
12542         return SuperD->getIdentifier() ==
12543             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12544       };
12545       // Don't issue this warning for unavailable inits or direct subclasses
12546       // of NSObject.
12547       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12548         Diag(MD->getLocation(),
12549              diag::warn_objc_designated_init_missing_super_call);
12550         Diag(InitMethod->getLocation(),
12551              diag::note_objc_designated_init_marked_here);
12552       }
12553       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12554     }
12555     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12556       // Don't issue this warning for unavaialable inits.
12557       if (!MD->isUnavailable())
12558         Diag(MD->getLocation(),
12559              diag::warn_objc_secondary_init_missing_init_call);
12560       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12561     }
12562   } else {
12563     return nullptr;
12564   }
12565 
12566   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12567     DiagnoseUnguardedAvailabilityViolations(dcl);
12568 
12569   assert(!getCurFunction()->ObjCShouldCallSuper &&
12570          "This should only be set for ObjC methods, which should have been "
12571          "handled in the block above.");
12572 
12573   // Verify and clean out per-function state.
12574   if (Body && (!FD || !FD->isDefaulted())) {
12575     // C++ constructors that have function-try-blocks can't have return
12576     // statements in the handlers of that block. (C++ [except.handle]p14)
12577     // Verify this.
12578     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12579       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12580 
12581     // Verify that gotos and switch cases don't jump into scopes illegally.
12582     if (getCurFunction()->NeedsScopeChecking() &&
12583         !PP.isCodeCompletionEnabled())
12584       DiagnoseInvalidJumps(Body);
12585 
12586     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12587       if (!Destructor->getParent()->isDependentType())
12588         CheckDestructor(Destructor);
12589 
12590       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12591                                              Destructor->getParent());
12592     }
12593 
12594     // If any errors have occurred, clear out any temporaries that may have
12595     // been leftover. This ensures that these temporaries won't be picked up for
12596     // deletion in some later function.
12597     if (getDiagnostics().hasErrorOccurred() ||
12598         getDiagnostics().getSuppressAllDiagnostics()) {
12599       DiscardCleanupsInEvaluationContext();
12600     }
12601     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12602         !isa<FunctionTemplateDecl>(dcl)) {
12603       // Since the body is valid, issue any analysis-based warnings that are
12604       // enabled.
12605       ActivePolicy = &WP;
12606     }
12607 
12608     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12609         (!CheckConstexprFunctionDecl(FD) ||
12610          !CheckConstexprFunctionBody(FD, Body)))
12611       FD->setInvalidDecl();
12612 
12613     if (FD && FD->hasAttr<NakedAttr>()) {
12614       for (const Stmt *S : Body->children()) {
12615         // Allow local register variables without initializer as they don't
12616         // require prologue.
12617         bool RegisterVariables = false;
12618         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12619           for (const auto *Decl : DS->decls()) {
12620             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12621               RegisterVariables =
12622                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12623               if (!RegisterVariables)
12624                 break;
12625             }
12626           }
12627         }
12628         if (RegisterVariables)
12629           continue;
12630         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12631           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12632           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12633           FD->setInvalidDecl();
12634           break;
12635         }
12636       }
12637     }
12638 
12639     assert(ExprCleanupObjects.size() ==
12640                ExprEvalContexts.back().NumCleanupObjects &&
12641            "Leftover temporaries in function");
12642     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12643     assert(MaybeODRUseExprs.empty() &&
12644            "Leftover expressions for odr-use checking");
12645   }
12646 
12647   if (!IsInstantiation)
12648     PopDeclContext();
12649 
12650   PopFunctionScopeInfo(ActivePolicy, dcl);
12651   // If any errors have occurred, clear out any temporaries that may have
12652   // been leftover. This ensures that these temporaries won't be picked up for
12653   // deletion in some later function.
12654   if (getDiagnostics().hasErrorOccurred()) {
12655     DiscardCleanupsInEvaluationContext();
12656   }
12657 
12658   return dcl;
12659 }
12660 
12661 /// When we finish delayed parsing of an attribute, we must attach it to the
12662 /// relevant Decl.
12663 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12664                                        ParsedAttributes &Attrs) {
12665   // Always attach attributes to the underlying decl.
12666   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12667     D = TD->getTemplatedDecl();
12668   ProcessDeclAttributeList(S, D, Attrs.getList());
12669 
12670   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12671     if (Method->isStatic())
12672       checkThisInStaticMemberFunctionAttributes(Method);
12673 }
12674 
12675 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12676 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12677 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12678                                           IdentifierInfo &II, Scope *S) {
12679   Scope *BlockScope = S;
12680   while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12681     BlockScope = BlockScope->getParent();
12682 
12683   // Before we produce a declaration for an implicitly defined
12684   // function, see whether there was a locally-scoped declaration of
12685   // this name as a function or variable. If so, use that
12686   // (non-visible) declaration, and complain about it.
12687   NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12688   if (ExternCPrev) {
12689     // We still need to inject the function into the enclosing block scope so
12690     // that later (non-call) uses can see it.
12691     PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12692 
12693     // C89 footnote 38:
12694     //   If in fact it is not defined as having type "function returning int",
12695     //   the behavior is undefined.
12696     if (!isa<FunctionDecl>(ExternCPrev) ||
12697         !Context.typesAreCompatible(
12698             cast<FunctionDecl>(ExternCPrev)->getType(),
12699             Context.getFunctionNoProtoType(Context.IntTy))) {
12700       Diag(Loc, diag::ext_use_out_of_scope_declaration)
12701           << ExternCPrev << !getLangOpts().C99;
12702       Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12703       return ExternCPrev;
12704     }
12705   }
12706 
12707   // Extension in C99.  Legal in C90, but warn about it.
12708   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12709   unsigned diag_id;
12710   if (II.getName().startswith("__builtin_"))
12711     diag_id = diag::warn_builtin_unknown;
12712   else if (getLangOpts().C99 || getLangOpts().OpenCL)
12713     diag_id = diag::ext_implicit_function_decl;
12714   else
12715     diag_id = diag::warn_implicit_function_decl;
12716   Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
12717 
12718   // If we found a prior declaration of this function, don't bother building
12719   // another one. We've already pushed that one into scope, so there's nothing
12720   // more to do.
12721   if (ExternCPrev)
12722     return ExternCPrev;
12723 
12724   // Because typo correction is expensive, only do it if the implicit
12725   // function declaration is going to be treated as an error.
12726   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12727     TypoCorrection Corrected;
12728     if (S &&
12729         (Corrected = CorrectTypo(
12730              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12731              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12732       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12733                    /*ErrorRecovery*/false);
12734   }
12735 
12736   // Set a Declarator for the implicit definition: int foo();
12737   const char *Dummy;
12738   AttributeFactory attrFactory;
12739   DeclSpec DS(attrFactory);
12740   unsigned DiagID;
12741   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12742                                   Context.getPrintingPolicy());
12743   (void)Error; // Silence warning.
12744   assert(!Error && "Error setting up implicit decl!");
12745   SourceLocation NoLoc;
12746   Declarator D(DS, Declarator::BlockContext);
12747   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12748                                              /*IsAmbiguous=*/false,
12749                                              /*LParenLoc=*/NoLoc,
12750                                              /*Params=*/nullptr,
12751                                              /*NumParams=*/0,
12752                                              /*EllipsisLoc=*/NoLoc,
12753                                              /*RParenLoc=*/NoLoc,
12754                                              /*TypeQuals=*/0,
12755                                              /*RefQualifierIsLvalueRef=*/true,
12756                                              /*RefQualifierLoc=*/NoLoc,
12757                                              /*ConstQualifierLoc=*/NoLoc,
12758                                              /*VolatileQualifierLoc=*/NoLoc,
12759                                              /*RestrictQualifierLoc=*/NoLoc,
12760                                              /*MutableLoc=*/NoLoc,
12761                                              EST_None,
12762                                              /*ESpecRange=*/SourceRange(),
12763                                              /*Exceptions=*/nullptr,
12764                                              /*ExceptionRanges=*/nullptr,
12765                                              /*NumExceptions=*/0,
12766                                              /*NoexceptExpr=*/nullptr,
12767                                              /*ExceptionSpecTokens=*/nullptr,
12768                                              /*DeclsInPrototype=*/None,
12769                                              Loc, Loc, D),
12770                 DS.getAttributes(),
12771                 SourceLocation());
12772   D.SetIdentifier(&II, Loc);
12773 
12774   // Insert this function into the enclosing block scope.
12775   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
12776   FD->setImplicit();
12777 
12778   AddKnownFunctionAttributes(FD);
12779 
12780   return FD;
12781 }
12782 
12783 /// \brief Adds any function attributes that we know a priori based on
12784 /// the declaration of this function.
12785 ///
12786 /// These attributes can apply both to implicitly-declared builtins
12787 /// (like __builtin___printf_chk) or to library-declared functions
12788 /// like NSLog or printf.
12789 ///
12790 /// We need to check for duplicate attributes both here and where user-written
12791 /// attributes are applied to declarations.
12792 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12793   if (FD->isInvalidDecl())
12794     return;
12795 
12796   // If this is a built-in function, map its builtin attributes to
12797   // actual attributes.
12798   if (unsigned BuiltinID = FD->getBuiltinID()) {
12799     // Handle printf-formatting attributes.
12800     unsigned FormatIdx;
12801     bool HasVAListArg;
12802     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12803       if (!FD->hasAttr<FormatAttr>()) {
12804         const char *fmt = "printf";
12805         unsigned int NumParams = FD->getNumParams();
12806         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12807             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12808           fmt = "NSString";
12809         FD->addAttr(FormatAttr::CreateImplicit(Context,
12810                                                &Context.Idents.get(fmt),
12811                                                FormatIdx+1,
12812                                                HasVAListArg ? 0 : FormatIdx+2,
12813                                                FD->getLocation()));
12814       }
12815     }
12816     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12817                                              HasVAListArg)) {
12818      if (!FD->hasAttr<FormatAttr>())
12819        FD->addAttr(FormatAttr::CreateImplicit(Context,
12820                                               &Context.Idents.get("scanf"),
12821                                               FormatIdx+1,
12822                                               HasVAListArg ? 0 : FormatIdx+2,
12823                                               FD->getLocation()));
12824     }
12825 
12826     // Mark const if we don't care about errno and that is the only
12827     // thing preventing the function from being const. This allows
12828     // IRgen to use LLVM intrinsics for such functions.
12829     if (!getLangOpts().MathErrno &&
12830         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12831       if (!FD->hasAttr<ConstAttr>())
12832         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12833     }
12834 
12835     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12836         !FD->hasAttr<ReturnsTwiceAttr>())
12837       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12838                                          FD->getLocation()));
12839     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12840       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12841     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12842       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12843     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12844       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12845     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12846         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12847       // Add the appropriate attribute, depending on the CUDA compilation mode
12848       // and which target the builtin belongs to. For example, during host
12849       // compilation, aux builtins are __device__, while the rest are __host__.
12850       if (getLangOpts().CUDAIsDevice !=
12851           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12852         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12853       else
12854         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12855     }
12856   }
12857 
12858   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12859   // throw, add an implicit nothrow attribute to any extern "C" function we come
12860   // across.
12861   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12862       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12863     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12864     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12865       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12866   }
12867 
12868   IdentifierInfo *Name = FD->getIdentifier();
12869   if (!Name)
12870     return;
12871   if ((!getLangOpts().CPlusPlus &&
12872        FD->getDeclContext()->isTranslationUnit()) ||
12873       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12874        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12875        LinkageSpecDecl::lang_c)) {
12876     // Okay: this could be a libc/libm/Objective-C function we know
12877     // about.
12878   } else
12879     return;
12880 
12881   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12882     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12883     // target-specific builtins, perhaps?
12884     if (!FD->hasAttr<FormatAttr>())
12885       FD->addAttr(FormatAttr::CreateImplicit(Context,
12886                                              &Context.Idents.get("printf"), 2,
12887                                              Name->isStr("vasprintf") ? 0 : 3,
12888                                              FD->getLocation()));
12889   }
12890 
12891   if (Name->isStr("__CFStringMakeConstantString")) {
12892     // We already have a __builtin___CFStringMakeConstantString,
12893     // but builds that use -fno-constant-cfstrings don't go through that.
12894     if (!FD->hasAttr<FormatArgAttr>())
12895       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12896                                                 FD->getLocation()));
12897   }
12898 }
12899 
12900 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12901                                     TypeSourceInfo *TInfo) {
12902   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12903   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12904 
12905   if (!TInfo) {
12906     assert(D.isInvalidType() && "no declarator info for valid type");
12907     TInfo = Context.getTrivialTypeSourceInfo(T);
12908   }
12909 
12910   // Scope manipulation handled by caller.
12911   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12912                                            D.getLocStart(),
12913                                            D.getIdentifierLoc(),
12914                                            D.getIdentifier(),
12915                                            TInfo);
12916 
12917   // Bail out immediately if we have an invalid declaration.
12918   if (D.isInvalidType()) {
12919     NewTD->setInvalidDecl();
12920     return NewTD;
12921   }
12922 
12923   if (D.getDeclSpec().isModulePrivateSpecified()) {
12924     if (CurContext->isFunctionOrMethod())
12925       Diag(NewTD->getLocation(), diag::err_module_private_local)
12926         << 2 << NewTD->getDeclName()
12927         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12928         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12929     else
12930       NewTD->setModulePrivate();
12931   }
12932 
12933   // C++ [dcl.typedef]p8:
12934   //   If the typedef declaration defines an unnamed class (or
12935   //   enum), the first typedef-name declared by the declaration
12936   //   to be that class type (or enum type) is used to denote the
12937   //   class type (or enum type) for linkage purposes only.
12938   // We need to check whether the type was declared in the declaration.
12939   switch (D.getDeclSpec().getTypeSpecType()) {
12940   case TST_enum:
12941   case TST_struct:
12942   case TST_interface:
12943   case TST_union:
12944   case TST_class: {
12945     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12946     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12947     break;
12948   }
12949 
12950   default:
12951     break;
12952   }
12953 
12954   return NewTD;
12955 }
12956 
12957 /// \brief Check that this is a valid underlying type for an enum declaration.
12958 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12959   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12960   QualType T = TI->getType();
12961 
12962   if (T->isDependentType())
12963     return false;
12964 
12965   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12966     if (BT->isInteger())
12967       return false;
12968 
12969   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12970   return true;
12971 }
12972 
12973 /// Check whether this is a valid redeclaration of a previous enumeration.
12974 /// \return true if the redeclaration was invalid.
12975 bool Sema::CheckEnumRedeclaration(
12976     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12977     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12978   bool IsFixed = !EnumUnderlyingTy.isNull();
12979 
12980   if (IsScoped != Prev->isScoped()) {
12981     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12982       << Prev->isScoped();
12983     Diag(Prev->getLocation(), diag::note_previous_declaration);
12984     return true;
12985   }
12986 
12987   if (IsFixed && Prev->isFixed()) {
12988     if (!EnumUnderlyingTy->isDependentType() &&
12989         !Prev->getIntegerType()->isDependentType() &&
12990         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12991                                         Prev->getIntegerType())) {
12992       // TODO: Highlight the underlying type of the redeclaration.
12993       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12994         << EnumUnderlyingTy << Prev->getIntegerType();
12995       Diag(Prev->getLocation(), diag::note_previous_declaration)
12996           << Prev->getIntegerTypeRange();
12997       return true;
12998     }
12999   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
13000     ;
13001   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
13002     ;
13003   } else if (IsFixed != Prev->isFixed()) {
13004     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13005       << Prev->isFixed();
13006     Diag(Prev->getLocation(), diag::note_previous_declaration);
13007     return true;
13008   }
13009 
13010   return false;
13011 }
13012 
13013 /// \brief Get diagnostic %select index for tag kind for
13014 /// redeclaration diagnostic message.
13015 /// WARNING: Indexes apply to particular diagnostics only!
13016 ///
13017 /// \returns diagnostic %select index.
13018 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13019   switch (Tag) {
13020   case TTK_Struct: return 0;
13021   case TTK_Interface: return 1;
13022   case TTK_Class:  return 2;
13023   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13024   }
13025 }
13026 
13027 /// \brief Determine if tag kind is a class-key compatible with
13028 /// class for redeclaration (class, struct, or __interface).
13029 ///
13030 /// \returns true iff the tag kind is compatible.
13031 static bool isClassCompatTagKind(TagTypeKind Tag)
13032 {
13033   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13034 }
13035 
13036 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13037                                              TagTypeKind TTK) {
13038   if (isa<TypedefDecl>(PrevDecl))
13039     return NTK_Typedef;
13040   else if (isa<TypeAliasDecl>(PrevDecl))
13041     return NTK_TypeAlias;
13042   else if (isa<ClassTemplateDecl>(PrevDecl))
13043     return NTK_Template;
13044   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13045     return NTK_TypeAliasTemplate;
13046   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13047     return NTK_TemplateTemplateArgument;
13048   switch (TTK) {
13049   case TTK_Struct:
13050   case TTK_Interface:
13051   case TTK_Class:
13052     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13053   case TTK_Union:
13054     return NTK_NonUnion;
13055   case TTK_Enum:
13056     return NTK_NonEnum;
13057   }
13058   llvm_unreachable("invalid TTK");
13059 }
13060 
13061 /// \brief Determine whether a tag with a given kind is acceptable
13062 /// as a redeclaration of the given tag declaration.
13063 ///
13064 /// \returns true if the new tag kind is acceptable, false otherwise.
13065 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13066                                         TagTypeKind NewTag, bool isDefinition,
13067                                         SourceLocation NewTagLoc,
13068                                         const IdentifierInfo *Name) {
13069   // C++ [dcl.type.elab]p3:
13070   //   The class-key or enum keyword present in the
13071   //   elaborated-type-specifier shall agree in kind with the
13072   //   declaration to which the name in the elaborated-type-specifier
13073   //   refers. This rule also applies to the form of
13074   //   elaborated-type-specifier that declares a class-name or
13075   //   friend class since it can be construed as referring to the
13076   //   definition of the class. Thus, in any
13077   //   elaborated-type-specifier, the enum keyword shall be used to
13078   //   refer to an enumeration (7.2), the union class-key shall be
13079   //   used to refer to a union (clause 9), and either the class or
13080   //   struct class-key shall be used to refer to a class (clause 9)
13081   //   declared using the class or struct class-key.
13082   TagTypeKind OldTag = Previous->getTagKind();
13083   if (!isDefinition || !isClassCompatTagKind(NewTag))
13084     if (OldTag == NewTag)
13085       return true;
13086 
13087   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13088     // Warn about the struct/class tag mismatch.
13089     bool isTemplate = false;
13090     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13091       isTemplate = Record->getDescribedClassTemplate();
13092 
13093     if (inTemplateInstantiation()) {
13094       // In a template instantiation, do not offer fix-its for tag mismatches
13095       // since they usually mess up the template instead of fixing the problem.
13096       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13097         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13098         << getRedeclDiagFromTagKind(OldTag);
13099       return true;
13100     }
13101 
13102     if (isDefinition) {
13103       // On definitions, check previous tags and issue a fix-it for each
13104       // one that doesn't match the current tag.
13105       if (Previous->getDefinition()) {
13106         // Don't suggest fix-its for redefinitions.
13107         return true;
13108       }
13109 
13110       bool previousMismatch = false;
13111       for (auto I : Previous->redecls()) {
13112         if (I->getTagKind() != NewTag) {
13113           if (!previousMismatch) {
13114             previousMismatch = true;
13115             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13116               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13117               << getRedeclDiagFromTagKind(I->getTagKind());
13118           }
13119           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13120             << getRedeclDiagFromTagKind(NewTag)
13121             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13122                  TypeWithKeyword::getTagTypeKindName(NewTag));
13123         }
13124       }
13125       return true;
13126     }
13127 
13128     // Check for a previous definition.  If current tag and definition
13129     // are same type, do nothing.  If no definition, but disagree with
13130     // with previous tag type, give a warning, but no fix-it.
13131     const TagDecl *Redecl = Previous->getDefinition() ?
13132                             Previous->getDefinition() : Previous;
13133     if (Redecl->getTagKind() == NewTag) {
13134       return true;
13135     }
13136 
13137     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13138       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13139       << getRedeclDiagFromTagKind(OldTag);
13140     Diag(Redecl->getLocation(), diag::note_previous_use);
13141 
13142     // If there is a previous definition, suggest a fix-it.
13143     if (Previous->getDefinition()) {
13144         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13145           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13146           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13147                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13148     }
13149 
13150     return true;
13151   }
13152   return false;
13153 }
13154 
13155 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13156 /// from an outer enclosing namespace or file scope inside a friend declaration.
13157 /// This should provide the commented out code in the following snippet:
13158 ///   namespace N {
13159 ///     struct X;
13160 ///     namespace M {
13161 ///       struct Y { friend struct /*N::*/ X; };
13162 ///     }
13163 ///   }
13164 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13165                                          SourceLocation NameLoc) {
13166   // While the decl is in a namespace, do repeated lookup of that name and see
13167   // if we get the same namespace back.  If we do not, continue until
13168   // translation unit scope, at which point we have a fully qualified NNS.
13169   SmallVector<IdentifierInfo *, 4> Namespaces;
13170   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13171   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13172     // This tag should be declared in a namespace, which can only be enclosed by
13173     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13174     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13175     if (!Namespace || Namespace->isAnonymousNamespace())
13176       return FixItHint();
13177     IdentifierInfo *II = Namespace->getIdentifier();
13178     Namespaces.push_back(II);
13179     NamedDecl *Lookup = SemaRef.LookupSingleName(
13180         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13181     if (Lookup == Namespace)
13182       break;
13183   }
13184 
13185   // Once we have all the namespaces, reverse them to go outermost first, and
13186   // build an NNS.
13187   SmallString<64> Insertion;
13188   llvm::raw_svector_ostream OS(Insertion);
13189   if (DC->isTranslationUnit())
13190     OS << "::";
13191   std::reverse(Namespaces.begin(), Namespaces.end());
13192   for (auto *II : Namespaces)
13193     OS << II->getName() << "::";
13194   return FixItHint::CreateInsertion(NameLoc, Insertion);
13195 }
13196 
13197 /// \brief Determine whether a tag originally declared in context \p OldDC can
13198 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13199 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13200 /// using-declaration).
13201 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13202                                          DeclContext *NewDC) {
13203   OldDC = OldDC->getRedeclContext();
13204   NewDC = NewDC->getRedeclContext();
13205 
13206   if (OldDC->Equals(NewDC))
13207     return true;
13208 
13209   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13210   // encloses the other).
13211   if (S.getLangOpts().MSVCCompat &&
13212       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13213     return true;
13214 
13215   return false;
13216 }
13217 
13218 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13219 /// former case, Name will be non-null.  In the later case, Name will be null.
13220 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13221 /// reference/declaration/definition of a tag.
13222 ///
13223 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13224 /// trailing-type-specifier) other than one in an alias-declaration.
13225 ///
13226 /// \param SkipBody If non-null, will be set to indicate if the caller should
13227 /// skip the definition of this tag and treat it as if it were a declaration.
13228 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13229                      SourceLocation KWLoc, CXXScopeSpec &SS,
13230                      IdentifierInfo *Name, SourceLocation NameLoc,
13231                      AttributeList *Attr, AccessSpecifier AS,
13232                      SourceLocation ModulePrivateLoc,
13233                      MultiTemplateParamsArg TemplateParameterLists,
13234                      bool &OwnedDecl, bool &IsDependent,
13235                      SourceLocation ScopedEnumKWLoc,
13236                      bool ScopedEnumUsesClassTag,
13237                      TypeResult UnderlyingType,
13238                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13239                      SkipBodyInfo *SkipBody) {
13240   // If this is not a definition, it must have a name.
13241   IdentifierInfo *OrigName = Name;
13242   assert((Name != nullptr || TUK == TUK_Definition) &&
13243          "Nameless record must be a definition!");
13244   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13245 
13246   OwnedDecl = false;
13247   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13248   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13249 
13250   // FIXME: Check member specializations more carefully.
13251   bool isMemberSpecialization = false;
13252   bool Invalid = false;
13253 
13254   // We only need to do this matching if we have template parameters
13255   // or a scope specifier, which also conveniently avoids this work
13256   // for non-C++ cases.
13257   if (TemplateParameterLists.size() > 0 ||
13258       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13259     if (TemplateParameterList *TemplateParams =
13260             MatchTemplateParametersToScopeSpecifier(
13261                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13262                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13263       if (Kind == TTK_Enum) {
13264         Diag(KWLoc, diag::err_enum_template);
13265         return nullptr;
13266       }
13267 
13268       if (TemplateParams->size() > 0) {
13269         // This is a declaration or definition of a class template (which may
13270         // be a member of another template).
13271 
13272         if (Invalid)
13273           return nullptr;
13274 
13275         OwnedDecl = false;
13276         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13277                                                SS, Name, NameLoc, Attr,
13278                                                TemplateParams, AS,
13279                                                ModulePrivateLoc,
13280                                                /*FriendLoc*/SourceLocation(),
13281                                                TemplateParameterLists.size()-1,
13282                                                TemplateParameterLists.data(),
13283                                                SkipBody);
13284         return Result.get();
13285       } else {
13286         // The "template<>" header is extraneous.
13287         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13288           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13289         isMemberSpecialization = true;
13290       }
13291     }
13292   }
13293 
13294   // Figure out the underlying type if this a enum declaration. We need to do
13295   // this early, because it's needed to detect if this is an incompatible
13296   // redeclaration.
13297   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13298   bool EnumUnderlyingIsImplicit = false;
13299 
13300   if (Kind == TTK_Enum) {
13301     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13302       // No underlying type explicitly specified, or we failed to parse the
13303       // type, default to int.
13304       EnumUnderlying = Context.IntTy.getTypePtr();
13305     else if (UnderlyingType.get()) {
13306       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13307       // integral type; any cv-qualification is ignored.
13308       TypeSourceInfo *TI = nullptr;
13309       GetTypeFromParser(UnderlyingType.get(), &TI);
13310       EnumUnderlying = TI;
13311 
13312       if (CheckEnumUnderlyingType(TI))
13313         // Recover by falling back to int.
13314         EnumUnderlying = Context.IntTy.getTypePtr();
13315 
13316       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13317                                           UPPC_FixedUnderlyingType))
13318         EnumUnderlying = Context.IntTy.getTypePtr();
13319 
13320     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13321       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13322         // Microsoft enums are always of int type.
13323         EnumUnderlying = Context.IntTy.getTypePtr();
13324         EnumUnderlyingIsImplicit = true;
13325       }
13326     }
13327   }
13328 
13329   DeclContext *SearchDC = CurContext;
13330   DeclContext *DC = CurContext;
13331   bool isStdBadAlloc = false;
13332   bool isStdAlignValT = false;
13333 
13334   RedeclarationKind Redecl = forRedeclarationInCurContext();
13335   if (TUK == TUK_Friend || TUK == TUK_Reference)
13336     Redecl = NotForRedeclaration;
13337 
13338   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13339   /// implemented asks for structural equivalence checking, the returned decl
13340   /// here is passed back to the parser, allowing the tag body to be parsed.
13341   auto createTagFromNewDecl = [&]() -> TagDecl * {
13342     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13343     // If there is an identifier, use the location of the identifier as the
13344     // location of the decl, otherwise use the location of the struct/union
13345     // keyword.
13346     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13347     TagDecl *New = nullptr;
13348 
13349     if (Kind == TTK_Enum) {
13350       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13351                              ScopedEnum, ScopedEnumUsesClassTag,
13352                              !EnumUnderlying.isNull());
13353       // If this is an undefined enum, bail.
13354       if (TUK != TUK_Definition && !Invalid)
13355         return nullptr;
13356       if (EnumUnderlying) {
13357         EnumDecl *ED = cast<EnumDecl>(New);
13358         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13359           ED->setIntegerTypeSourceInfo(TI);
13360         else
13361           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13362         ED->setPromotionType(ED->getIntegerType());
13363       }
13364     } else { // struct/union
13365       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13366                                nullptr);
13367     }
13368 
13369     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13370       // Add alignment attributes if necessary; these attributes are checked
13371       // when the ASTContext lays out the structure.
13372       //
13373       // It is important for implementing the correct semantics that this
13374       // happen here (in ActOnTag). The #pragma pack stack is
13375       // maintained as a result of parser callbacks which can occur at
13376       // many points during the parsing of a struct declaration (because
13377       // the #pragma tokens are effectively skipped over during the
13378       // parsing of the struct).
13379       if (TUK == TUK_Definition) {
13380         AddAlignmentAttributesForRecord(RD);
13381         AddMsStructLayoutForRecord(RD);
13382       }
13383     }
13384     New->setLexicalDeclContext(CurContext);
13385     return New;
13386   };
13387 
13388   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13389   if (Name && SS.isNotEmpty()) {
13390     // We have a nested-name tag ('struct foo::bar').
13391 
13392     // Check for invalid 'foo::'.
13393     if (SS.isInvalid()) {
13394       Name = nullptr;
13395       goto CreateNewDecl;
13396     }
13397 
13398     // If this is a friend or a reference to a class in a dependent
13399     // context, don't try to make a decl for it.
13400     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13401       DC = computeDeclContext(SS, false);
13402       if (!DC) {
13403         IsDependent = true;
13404         return nullptr;
13405       }
13406     } else {
13407       DC = computeDeclContext(SS, true);
13408       if (!DC) {
13409         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13410           << SS.getRange();
13411         return nullptr;
13412       }
13413     }
13414 
13415     if (RequireCompleteDeclContext(SS, DC))
13416       return nullptr;
13417 
13418     SearchDC = DC;
13419     // Look-up name inside 'foo::'.
13420     LookupQualifiedName(Previous, DC);
13421 
13422     if (Previous.isAmbiguous())
13423       return nullptr;
13424 
13425     if (Previous.empty()) {
13426       // Name lookup did not find anything. However, if the
13427       // nested-name-specifier refers to the current instantiation,
13428       // and that current instantiation has any dependent base
13429       // classes, we might find something at instantiation time: treat
13430       // this as a dependent elaborated-type-specifier.
13431       // But this only makes any sense for reference-like lookups.
13432       if (Previous.wasNotFoundInCurrentInstantiation() &&
13433           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13434         IsDependent = true;
13435         return nullptr;
13436       }
13437 
13438       // A tag 'foo::bar' must already exist.
13439       Diag(NameLoc, diag::err_not_tag_in_scope)
13440         << Kind << Name << DC << SS.getRange();
13441       Name = nullptr;
13442       Invalid = true;
13443       goto CreateNewDecl;
13444     }
13445   } else if (Name) {
13446     // C++14 [class.mem]p14:
13447     //   If T is the name of a class, then each of the following shall have a
13448     //   name different from T:
13449     //    -- every member of class T that is itself a type
13450     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13451         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13452       return nullptr;
13453 
13454     // If this is a named struct, check to see if there was a previous forward
13455     // declaration or definition.
13456     // FIXME: We're looking into outer scopes here, even when we
13457     // shouldn't be. Doing so can result in ambiguities that we
13458     // shouldn't be diagnosing.
13459     LookupName(Previous, S);
13460 
13461     // When declaring or defining a tag, ignore ambiguities introduced
13462     // by types using'ed into this scope.
13463     if (Previous.isAmbiguous() &&
13464         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13465       LookupResult::Filter F = Previous.makeFilter();
13466       while (F.hasNext()) {
13467         NamedDecl *ND = F.next();
13468         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13469                 SearchDC->getRedeclContext()))
13470           F.erase();
13471       }
13472       F.done();
13473     }
13474 
13475     // C++11 [namespace.memdef]p3:
13476     //   If the name in a friend declaration is neither qualified nor
13477     //   a template-id and the declaration is a function or an
13478     //   elaborated-type-specifier, the lookup to determine whether
13479     //   the entity has been previously declared shall not consider
13480     //   any scopes outside the innermost enclosing namespace.
13481     //
13482     // MSVC doesn't implement the above rule for types, so a friend tag
13483     // declaration may be a redeclaration of a type declared in an enclosing
13484     // scope.  They do implement this rule for friend functions.
13485     //
13486     // Does it matter that this should be by scope instead of by
13487     // semantic context?
13488     if (!Previous.empty() && TUK == TUK_Friend) {
13489       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13490       LookupResult::Filter F = Previous.makeFilter();
13491       bool FriendSawTagOutsideEnclosingNamespace = false;
13492       while (F.hasNext()) {
13493         NamedDecl *ND = F.next();
13494         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13495         if (DC->isFileContext() &&
13496             !EnclosingNS->Encloses(ND->getDeclContext())) {
13497           if (getLangOpts().MSVCCompat)
13498             FriendSawTagOutsideEnclosingNamespace = true;
13499           else
13500             F.erase();
13501         }
13502       }
13503       F.done();
13504 
13505       // Diagnose this MSVC extension in the easy case where lookup would have
13506       // unambiguously found something outside the enclosing namespace.
13507       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13508         NamedDecl *ND = Previous.getFoundDecl();
13509         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13510             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13511       }
13512     }
13513 
13514     // Note:  there used to be some attempt at recovery here.
13515     if (Previous.isAmbiguous())
13516       return nullptr;
13517 
13518     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13519       // FIXME: This makes sure that we ignore the contexts associated
13520       // with C structs, unions, and enums when looking for a matching
13521       // tag declaration or definition. See the similar lookup tweak
13522       // in Sema::LookupName; is there a better way to deal with this?
13523       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13524         SearchDC = SearchDC->getParent();
13525     }
13526   }
13527 
13528   if (Previous.isSingleResult() &&
13529       Previous.getFoundDecl()->isTemplateParameter()) {
13530     // Maybe we will complain about the shadowed template parameter.
13531     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13532     // Just pretend that we didn't see the previous declaration.
13533     Previous.clear();
13534   }
13535 
13536   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13537       DC->Equals(getStdNamespace())) {
13538     if (Name->isStr("bad_alloc")) {
13539       // This is a declaration of or a reference to "std::bad_alloc".
13540       isStdBadAlloc = true;
13541 
13542       // If std::bad_alloc has been implicitly declared (but made invisible to
13543       // name lookup), fill in this implicit declaration as the previous
13544       // declaration, so that the declarations get chained appropriately.
13545       if (Previous.empty() && StdBadAlloc)
13546         Previous.addDecl(getStdBadAlloc());
13547     } else if (Name->isStr("align_val_t")) {
13548       isStdAlignValT = true;
13549       if (Previous.empty() && StdAlignValT)
13550         Previous.addDecl(getStdAlignValT());
13551     }
13552   }
13553 
13554   // If we didn't find a previous declaration, and this is a reference
13555   // (or friend reference), move to the correct scope.  In C++, we
13556   // also need to do a redeclaration lookup there, just in case
13557   // there's a shadow friend decl.
13558   if (Name && Previous.empty() &&
13559       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13560     if (Invalid) goto CreateNewDecl;
13561     assert(SS.isEmpty());
13562 
13563     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13564       // C++ [basic.scope.pdecl]p5:
13565       //   -- for an elaborated-type-specifier of the form
13566       //
13567       //          class-key identifier
13568       //
13569       //      if the elaborated-type-specifier is used in the
13570       //      decl-specifier-seq or parameter-declaration-clause of a
13571       //      function defined in namespace scope, the identifier is
13572       //      declared as a class-name in the namespace that contains
13573       //      the declaration; otherwise, except as a friend
13574       //      declaration, the identifier is declared in the smallest
13575       //      non-class, non-function-prototype scope that contains the
13576       //      declaration.
13577       //
13578       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13579       // C structs and unions.
13580       //
13581       // It is an error in C++ to declare (rather than define) an enum
13582       // type, including via an elaborated type specifier.  We'll
13583       // diagnose that later; for now, declare the enum in the same
13584       // scope as we would have picked for any other tag type.
13585       //
13586       // GNU C also supports this behavior as part of its incomplete
13587       // enum types extension, while GNU C++ does not.
13588       //
13589       // Find the context where we'll be declaring the tag.
13590       // FIXME: We would like to maintain the current DeclContext as the
13591       // lexical context,
13592       SearchDC = getTagInjectionContext(SearchDC);
13593 
13594       // Find the scope where we'll be declaring the tag.
13595       S = getTagInjectionScope(S, getLangOpts());
13596     } else {
13597       assert(TUK == TUK_Friend);
13598       // C++ [namespace.memdef]p3:
13599       //   If a friend declaration in a non-local class first declares a
13600       //   class or function, the friend class or function is a member of
13601       //   the innermost enclosing namespace.
13602       SearchDC = SearchDC->getEnclosingNamespaceContext();
13603     }
13604 
13605     // In C++, we need to do a redeclaration lookup to properly
13606     // diagnose some problems.
13607     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13608     // hidden declaration so that we don't get ambiguity errors when using a
13609     // type declared by an elaborated-type-specifier.  In C that is not correct
13610     // and we should instead merge compatible types found by lookup.
13611     if (getLangOpts().CPlusPlus) {
13612       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13613       LookupQualifiedName(Previous, SearchDC);
13614     } else {
13615       Previous.setRedeclarationKind(forRedeclarationInCurContext());
13616       LookupName(Previous, S);
13617     }
13618   }
13619 
13620   // If we have a known previous declaration to use, then use it.
13621   if (Previous.empty() && SkipBody && SkipBody->Previous)
13622     Previous.addDecl(SkipBody->Previous);
13623 
13624   if (!Previous.empty()) {
13625     NamedDecl *PrevDecl = Previous.getFoundDecl();
13626     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13627 
13628     // It's okay to have a tag decl in the same scope as a typedef
13629     // which hides a tag decl in the same scope.  Finding this
13630     // insanity with a redeclaration lookup can only actually happen
13631     // in C++.
13632     //
13633     // This is also okay for elaborated-type-specifiers, which is
13634     // technically forbidden by the current standard but which is
13635     // okay according to the likely resolution of an open issue;
13636     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13637     if (getLangOpts().CPlusPlus) {
13638       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13639         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13640           TagDecl *Tag = TT->getDecl();
13641           if (Tag->getDeclName() == Name &&
13642               Tag->getDeclContext()->getRedeclContext()
13643                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13644             PrevDecl = Tag;
13645             Previous.clear();
13646             Previous.addDecl(Tag);
13647             Previous.resolveKind();
13648           }
13649         }
13650       }
13651     }
13652 
13653     // If this is a redeclaration of a using shadow declaration, it must
13654     // declare a tag in the same context. In MSVC mode, we allow a
13655     // redefinition if either context is within the other.
13656     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13657       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13658       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13659           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13660           !(OldTag && isAcceptableTagRedeclContext(
13661                           *this, OldTag->getDeclContext(), SearchDC))) {
13662         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13663         Diag(Shadow->getTargetDecl()->getLocation(),
13664              diag::note_using_decl_target);
13665         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13666             << 0;
13667         // Recover by ignoring the old declaration.
13668         Previous.clear();
13669         goto CreateNewDecl;
13670       }
13671     }
13672 
13673     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13674       // If this is a use of a previous tag, or if the tag is already declared
13675       // in the same scope (so that the definition/declaration completes or
13676       // rementions the tag), reuse the decl.
13677       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13678           isDeclInScope(DirectPrevDecl, SearchDC, S,
13679                         SS.isNotEmpty() || isMemberSpecialization)) {
13680         // Make sure that this wasn't declared as an enum and now used as a
13681         // struct or something similar.
13682         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13683                                           TUK == TUK_Definition, KWLoc,
13684                                           Name)) {
13685           bool SafeToContinue
13686             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13687                Kind != TTK_Enum);
13688           if (SafeToContinue)
13689             Diag(KWLoc, diag::err_use_with_wrong_tag)
13690               << Name
13691               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13692                                               PrevTagDecl->getKindName());
13693           else
13694             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13695           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13696 
13697           if (SafeToContinue)
13698             Kind = PrevTagDecl->getTagKind();
13699           else {
13700             // Recover by making this an anonymous redefinition.
13701             Name = nullptr;
13702             Previous.clear();
13703             Invalid = true;
13704           }
13705         }
13706 
13707         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13708           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13709 
13710           // If this is an elaborated-type-specifier for a scoped enumeration,
13711           // the 'class' keyword is not necessary and not permitted.
13712           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13713             if (ScopedEnum)
13714               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13715                 << PrevEnum->isScoped()
13716                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13717             return PrevTagDecl;
13718           }
13719 
13720           QualType EnumUnderlyingTy;
13721           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13722             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13723           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13724             EnumUnderlyingTy = QualType(T, 0);
13725 
13726           // All conflicts with previous declarations are recovered by
13727           // returning the previous declaration, unless this is a definition,
13728           // in which case we want the caller to bail out.
13729           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13730                                      ScopedEnum, EnumUnderlyingTy,
13731                                      EnumUnderlyingIsImplicit, PrevEnum))
13732             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13733         }
13734 
13735         // C++11 [class.mem]p1:
13736         //   A member shall not be declared twice in the member-specification,
13737         //   except that a nested class or member class template can be declared
13738         //   and then later defined.
13739         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13740             S->isDeclScope(PrevDecl)) {
13741           Diag(NameLoc, diag::ext_member_redeclared);
13742           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13743         }
13744 
13745         if (!Invalid) {
13746           // If this is a use, just return the declaration we found, unless
13747           // we have attributes.
13748           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13749             if (Attr) {
13750               // FIXME: Diagnose these attributes. For now, we create a new
13751               // declaration to hold them.
13752             } else if (TUK == TUK_Reference &&
13753                        (PrevTagDecl->getFriendObjectKind() ==
13754                             Decl::FOK_Undeclared ||
13755                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13756                        SS.isEmpty()) {
13757               // This declaration is a reference to an existing entity, but
13758               // has different visibility from that entity: it either makes
13759               // a friend visible or it makes a type visible in a new module.
13760               // In either case, create a new declaration. We only do this if
13761               // the declaration would have meant the same thing if no prior
13762               // declaration were found, that is, if it was found in the same
13763               // scope where we would have injected a declaration.
13764               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13765                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13766                 return PrevTagDecl;
13767               // This is in the injected scope, create a new declaration in
13768               // that scope.
13769               S = getTagInjectionScope(S, getLangOpts());
13770             } else {
13771               return PrevTagDecl;
13772             }
13773           }
13774 
13775           // Diagnose attempts to redefine a tag.
13776           if (TUK == TUK_Definition) {
13777             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13778               // If we're defining a specialization and the previous definition
13779               // is from an implicit instantiation, don't emit an error
13780               // here; we'll catch this in the general case below.
13781               bool IsExplicitSpecializationAfterInstantiation = false;
13782               if (isMemberSpecialization) {
13783                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13784                   IsExplicitSpecializationAfterInstantiation =
13785                     RD->getTemplateSpecializationKind() !=
13786                     TSK_ExplicitSpecialization;
13787                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13788                   IsExplicitSpecializationAfterInstantiation =
13789                     ED->getTemplateSpecializationKind() !=
13790                     TSK_ExplicitSpecialization;
13791               }
13792 
13793               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13794               // not keep more that one definition around (merge them). However,
13795               // ensure the decl passes the structural compatibility check in
13796               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13797               NamedDecl *Hidden = nullptr;
13798               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13799                 // There is a definition of this tag, but it is not visible. We
13800                 // explicitly make use of C++'s one definition rule here, and
13801                 // assume that this definition is identical to the hidden one
13802                 // we already have. Make the existing definition visible and
13803                 // use it in place of this one.
13804                 if (!getLangOpts().CPlusPlus) {
13805                   // Postpone making the old definition visible until after we
13806                   // complete parsing the new one and do the structural
13807                   // comparison.
13808                   SkipBody->CheckSameAsPrevious = true;
13809                   SkipBody->New = createTagFromNewDecl();
13810                   SkipBody->Previous = Hidden;
13811                 } else {
13812                   SkipBody->ShouldSkip = true;
13813                   makeMergedDefinitionVisible(Hidden);
13814                 }
13815                 return Def;
13816               } else if (!IsExplicitSpecializationAfterInstantiation) {
13817                 // A redeclaration in function prototype scope in C isn't
13818                 // visible elsewhere, so merely issue a warning.
13819                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13820                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13821                 else
13822                   Diag(NameLoc, diag::err_redefinition) << Name;
13823                 notePreviousDefinition(Def,
13824                                        NameLoc.isValid() ? NameLoc : KWLoc);
13825                 // If this is a redefinition, recover by making this
13826                 // struct be anonymous, which will make any later
13827                 // references get the previous definition.
13828                 Name = nullptr;
13829                 Previous.clear();
13830                 Invalid = true;
13831               }
13832             } else {
13833               // If the type is currently being defined, complain
13834               // about a nested redefinition.
13835               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13836               if (TD->isBeingDefined()) {
13837                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13838                 Diag(PrevTagDecl->getLocation(),
13839                      diag::note_previous_definition);
13840                 Name = nullptr;
13841                 Previous.clear();
13842                 Invalid = true;
13843               }
13844             }
13845 
13846             // Okay, this is definition of a previously declared or referenced
13847             // tag. We're going to create a new Decl for it.
13848           }
13849 
13850           // Okay, we're going to make a redeclaration.  If this is some kind
13851           // of reference, make sure we build the redeclaration in the same DC
13852           // as the original, and ignore the current access specifier.
13853           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13854             SearchDC = PrevTagDecl->getDeclContext();
13855             AS = AS_none;
13856           }
13857         }
13858         // If we get here we have (another) forward declaration or we
13859         // have a definition.  Just create a new decl.
13860 
13861       } else {
13862         // If we get here, this is a definition of a new tag type in a nested
13863         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13864         // new decl/type.  We set PrevDecl to NULL so that the entities
13865         // have distinct types.
13866         Previous.clear();
13867       }
13868       // If we get here, we're going to create a new Decl. If PrevDecl
13869       // is non-NULL, it's a definition of the tag declared by
13870       // PrevDecl. If it's NULL, we have a new definition.
13871 
13872     // Otherwise, PrevDecl is not a tag, but was found with tag
13873     // lookup.  This is only actually possible in C++, where a few
13874     // things like templates still live in the tag namespace.
13875     } else {
13876       // Use a better diagnostic if an elaborated-type-specifier
13877       // found the wrong kind of type on the first
13878       // (non-redeclaration) lookup.
13879       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13880           !Previous.isForRedeclaration()) {
13881         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13882         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13883                                                        << Kind;
13884         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13885         Invalid = true;
13886 
13887       // Otherwise, only diagnose if the declaration is in scope.
13888       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13889                                 SS.isNotEmpty() || isMemberSpecialization)) {
13890         // do nothing
13891 
13892       // Diagnose implicit declarations introduced by elaborated types.
13893       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13894         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13895         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13896         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13897         Invalid = true;
13898 
13899       // Otherwise it's a declaration.  Call out a particularly common
13900       // case here.
13901       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13902         unsigned Kind = 0;
13903         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13904         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13905           << Name << Kind << TND->getUnderlyingType();
13906         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13907         Invalid = true;
13908 
13909       // Otherwise, diagnose.
13910       } else {
13911         // The tag name clashes with something else in the target scope,
13912         // issue an error and recover by making this tag be anonymous.
13913         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13914         notePreviousDefinition(PrevDecl, NameLoc);
13915         Name = nullptr;
13916         Invalid = true;
13917       }
13918 
13919       // The existing declaration isn't relevant to us; we're in a
13920       // new scope, so clear out the previous declaration.
13921       Previous.clear();
13922     }
13923   }
13924 
13925 CreateNewDecl:
13926 
13927   TagDecl *PrevDecl = nullptr;
13928   if (Previous.isSingleResult())
13929     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13930 
13931   // If there is an identifier, use the location of the identifier as the
13932   // location of the decl, otherwise use the location of the struct/union
13933   // keyword.
13934   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13935 
13936   // Otherwise, create a new declaration. If there is a previous
13937   // declaration of the same entity, the two will be linked via
13938   // PrevDecl.
13939   TagDecl *New;
13940 
13941   bool IsForwardReference = false;
13942   if (Kind == TTK_Enum) {
13943     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13944     // enum X { A, B, C } D;    D should chain to X.
13945     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13946                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13947                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13948 
13949     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13950       StdAlignValT = cast<EnumDecl>(New);
13951 
13952     // If this is an undefined enum, warn.
13953     if (TUK != TUK_Definition && !Invalid) {
13954       TagDecl *Def;
13955       if (!EnumUnderlyingIsImplicit &&
13956           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13957           cast<EnumDecl>(New)->isFixed()) {
13958         // C++0x: 7.2p2: opaque-enum-declaration.
13959         // Conflicts are diagnosed above. Do nothing.
13960       }
13961       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13962         Diag(Loc, diag::ext_forward_ref_enum_def)
13963           << New;
13964         Diag(Def->getLocation(), diag::note_previous_definition);
13965       } else {
13966         unsigned DiagID = diag::ext_forward_ref_enum;
13967         if (getLangOpts().MSVCCompat)
13968           DiagID = diag::ext_ms_forward_ref_enum;
13969         else if (getLangOpts().CPlusPlus)
13970           DiagID = diag::err_forward_ref_enum;
13971         Diag(Loc, DiagID);
13972 
13973         // If this is a forward-declared reference to an enumeration, make a
13974         // note of it; we won't actually be introducing the declaration into
13975         // the declaration context.
13976         if (TUK == TUK_Reference)
13977           IsForwardReference = true;
13978       }
13979     }
13980 
13981     if (EnumUnderlying) {
13982       EnumDecl *ED = cast<EnumDecl>(New);
13983       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13984         ED->setIntegerTypeSourceInfo(TI);
13985       else
13986         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13987       ED->setPromotionType(ED->getIntegerType());
13988     }
13989   } else {
13990     // struct/union/class
13991 
13992     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13993     // struct X { int A; } D;    D should chain to X.
13994     if (getLangOpts().CPlusPlus) {
13995       // FIXME: Look for a way to use RecordDecl for simple structs.
13996       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13997                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13998 
13999       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14000         StdBadAlloc = cast<CXXRecordDecl>(New);
14001     } else
14002       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14003                                cast_or_null<RecordDecl>(PrevDecl));
14004   }
14005 
14006   // C++11 [dcl.type]p3:
14007   //   A type-specifier-seq shall not define a class or enumeration [...].
14008   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14009       TUK == TUK_Definition) {
14010     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14011       << Context.getTagDeclType(New);
14012     Invalid = true;
14013   }
14014 
14015   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14016       DC->getDeclKind() == Decl::Enum) {
14017     Diag(New->getLocation(), diag::err_type_defined_in_enum)
14018       << Context.getTagDeclType(New);
14019     Invalid = true;
14020   }
14021 
14022   // Maybe add qualifier info.
14023   if (SS.isNotEmpty()) {
14024     if (SS.isSet()) {
14025       // If this is either a declaration or a definition, check the
14026       // nested-name-specifier against the current context. We don't do this
14027       // for explicit specializations, because they have similar checking
14028       // (with more specific diagnostics) in the call to
14029       // CheckMemberSpecialization, below.
14030       if (!isMemberSpecialization &&
14031           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
14032           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
14033         Invalid = true;
14034 
14035       New->setQualifierInfo(SS.getWithLocInContext(Context));
14036       if (TemplateParameterLists.size() > 0) {
14037         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14038       }
14039     }
14040     else
14041       Invalid = true;
14042   }
14043 
14044   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14045     // Add alignment attributes if necessary; these attributes are checked when
14046     // the ASTContext lays out the structure.
14047     //
14048     // It is important for implementing the correct semantics that this
14049     // happen here (in ActOnTag). The #pragma pack stack is
14050     // maintained as a result of parser callbacks which can occur at
14051     // many points during the parsing of a struct declaration (because
14052     // the #pragma tokens are effectively skipped over during the
14053     // parsing of the struct).
14054     if (TUK == TUK_Definition) {
14055       AddAlignmentAttributesForRecord(RD);
14056       AddMsStructLayoutForRecord(RD);
14057     }
14058   }
14059 
14060   if (ModulePrivateLoc.isValid()) {
14061     if (isMemberSpecialization)
14062       Diag(New->getLocation(), diag::err_module_private_specialization)
14063         << 2
14064         << FixItHint::CreateRemoval(ModulePrivateLoc);
14065     // __module_private__ does not apply to local classes. However, we only
14066     // diagnose this as an error when the declaration specifiers are
14067     // freestanding. Here, we just ignore the __module_private__.
14068     else if (!SearchDC->isFunctionOrMethod())
14069       New->setModulePrivate();
14070   }
14071 
14072   // If this is a specialization of a member class (of a class template),
14073   // check the specialization.
14074   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14075     Invalid = true;
14076 
14077   // If we're declaring or defining a tag in function prototype scope in C,
14078   // note that this type can only be used within the function and add it to
14079   // the list of decls to inject into the function definition scope.
14080   if ((Name || Kind == TTK_Enum) &&
14081       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14082     if (getLangOpts().CPlusPlus) {
14083       // C++ [dcl.fct]p6:
14084       //   Types shall not be defined in return or parameter types.
14085       if (TUK == TUK_Definition && !IsTypeSpecifier) {
14086         Diag(Loc, diag::err_type_defined_in_param_type)
14087             << Name;
14088         Invalid = true;
14089       }
14090     } else if (!PrevDecl) {
14091       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14092     }
14093   }
14094 
14095   if (Invalid)
14096     New->setInvalidDecl();
14097 
14098   // Set the lexical context. If the tag has a C++ scope specifier, the
14099   // lexical context will be different from the semantic context.
14100   New->setLexicalDeclContext(CurContext);
14101 
14102   // Mark this as a friend decl if applicable.
14103   // In Microsoft mode, a friend declaration also acts as a forward
14104   // declaration so we always pass true to setObjectOfFriendDecl to make
14105   // the tag name visible.
14106   if (TUK == TUK_Friend)
14107     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14108 
14109   // Set the access specifier.
14110   if (!Invalid && SearchDC->isRecord())
14111     SetMemberAccessSpecifier(New, PrevDecl, AS);
14112 
14113   if (PrevDecl)
14114     CheckRedeclarationModuleOwnership(New, PrevDecl);
14115 
14116   if (TUK == TUK_Definition)
14117     New->startDefinition();
14118 
14119   if (Attr)
14120     ProcessDeclAttributeList(S, New, Attr);
14121   AddPragmaAttributes(S, New);
14122 
14123   // If this has an identifier, add it to the scope stack.
14124   if (TUK == TUK_Friend) {
14125     // We might be replacing an existing declaration in the lookup tables;
14126     // if so, borrow its access specifier.
14127     if (PrevDecl)
14128       New->setAccess(PrevDecl->getAccess());
14129 
14130     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14131     DC->makeDeclVisibleInContext(New);
14132     if (Name) // can be null along some error paths
14133       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14134         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14135   } else if (Name) {
14136     S = getNonFieldDeclScope(S);
14137     PushOnScopeChains(New, S, !IsForwardReference);
14138     if (IsForwardReference)
14139       SearchDC->makeDeclVisibleInContext(New);
14140   } else {
14141     CurContext->addDecl(New);
14142   }
14143 
14144   // If this is the C FILE type, notify the AST context.
14145   if (IdentifierInfo *II = New->getIdentifier())
14146     if (!New->isInvalidDecl() &&
14147         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14148         II->isStr("FILE"))
14149       Context.setFILEDecl(New);
14150 
14151   if (PrevDecl)
14152     mergeDeclAttributes(New, PrevDecl);
14153 
14154   // If there's a #pragma GCC visibility in scope, set the visibility of this
14155   // record.
14156   AddPushedVisibilityAttribute(New);
14157 
14158   if (isMemberSpecialization && !New->isInvalidDecl())
14159     CompleteMemberSpecialization(New, Previous);
14160 
14161   OwnedDecl = true;
14162   // In C++, don't return an invalid declaration. We can't recover well from
14163   // the cases where we make the type anonymous.
14164   if (Invalid && getLangOpts().CPlusPlus) {
14165     if (New->isBeingDefined())
14166       if (auto RD = dyn_cast<RecordDecl>(New))
14167         RD->completeDefinition();
14168     return nullptr;
14169   } else {
14170     return New;
14171   }
14172 }
14173 
14174 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14175   AdjustDeclIfTemplate(TagD);
14176   TagDecl *Tag = cast<TagDecl>(TagD);
14177 
14178   // Enter the tag context.
14179   PushDeclContext(S, Tag);
14180 
14181   ActOnDocumentableDecl(TagD);
14182 
14183   // If there's a #pragma GCC visibility in scope, set the visibility of this
14184   // record.
14185   AddPushedVisibilityAttribute(Tag);
14186 }
14187 
14188 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14189                                     SkipBodyInfo &SkipBody) {
14190   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14191     return false;
14192 
14193   // Make the previous decl visible.
14194   makeMergedDefinitionVisible(SkipBody.Previous);
14195   return true;
14196 }
14197 
14198 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14199   assert(isa<ObjCContainerDecl>(IDecl) &&
14200          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14201   DeclContext *OCD = cast<DeclContext>(IDecl);
14202   assert(getContainingDC(OCD) == CurContext &&
14203       "The next DeclContext should be lexically contained in the current one.");
14204   CurContext = OCD;
14205   return IDecl;
14206 }
14207 
14208 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14209                                            SourceLocation FinalLoc,
14210                                            bool IsFinalSpelledSealed,
14211                                            SourceLocation LBraceLoc) {
14212   AdjustDeclIfTemplate(TagD);
14213   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14214 
14215   FieldCollector->StartClass();
14216 
14217   if (!Record->getIdentifier())
14218     return;
14219 
14220   if (FinalLoc.isValid())
14221     Record->addAttr(new (Context)
14222                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14223 
14224   // C++ [class]p2:
14225   //   [...] The class-name is also inserted into the scope of the
14226   //   class itself; this is known as the injected-class-name. For
14227   //   purposes of access checking, the injected-class-name is treated
14228   //   as if it were a public member name.
14229   CXXRecordDecl *InjectedClassName
14230     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14231                             Record->getLocStart(), Record->getLocation(),
14232                             Record->getIdentifier(),
14233                             /*PrevDecl=*/nullptr,
14234                             /*DelayTypeCreation=*/true);
14235   Context.getTypeDeclType(InjectedClassName, Record);
14236   InjectedClassName->setImplicit();
14237   InjectedClassName->setAccess(AS_public);
14238   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14239       InjectedClassName->setDescribedClassTemplate(Template);
14240   PushOnScopeChains(InjectedClassName, S);
14241   assert(InjectedClassName->isInjectedClassName() &&
14242          "Broken injected-class-name");
14243 }
14244 
14245 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14246                                     SourceRange BraceRange) {
14247   AdjustDeclIfTemplate(TagD);
14248   TagDecl *Tag = cast<TagDecl>(TagD);
14249   Tag->setBraceRange(BraceRange);
14250 
14251   // Make sure we "complete" the definition even it is invalid.
14252   if (Tag->isBeingDefined()) {
14253     assert(Tag->isInvalidDecl() && "We should already have completed it");
14254     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14255       RD->completeDefinition();
14256   }
14257 
14258   if (isa<CXXRecordDecl>(Tag)) {
14259     FieldCollector->FinishClass();
14260   }
14261 
14262   // Exit this scope of this tag's definition.
14263   PopDeclContext();
14264 
14265   if (getCurLexicalContext()->isObjCContainer() &&
14266       Tag->getDeclContext()->isFileContext())
14267     Tag->setTopLevelDeclInObjCContainer();
14268 
14269   // Notify the consumer that we've defined a tag.
14270   if (!Tag->isInvalidDecl())
14271     Consumer.HandleTagDeclDefinition(Tag);
14272 }
14273 
14274 void Sema::ActOnObjCContainerFinishDefinition() {
14275   // Exit this scope of this interface definition.
14276   PopDeclContext();
14277 }
14278 
14279 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14280   assert(DC == CurContext && "Mismatch of container contexts");
14281   OriginalLexicalContext = DC;
14282   ActOnObjCContainerFinishDefinition();
14283 }
14284 
14285 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14286   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14287   OriginalLexicalContext = nullptr;
14288 }
14289 
14290 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14291   AdjustDeclIfTemplate(TagD);
14292   TagDecl *Tag = cast<TagDecl>(TagD);
14293   Tag->setInvalidDecl();
14294 
14295   // Make sure we "complete" the definition even it is invalid.
14296   if (Tag->isBeingDefined()) {
14297     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14298       RD->completeDefinition();
14299   }
14300 
14301   // We're undoing ActOnTagStartDefinition here, not
14302   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14303   // the FieldCollector.
14304 
14305   PopDeclContext();
14306 }
14307 
14308 // Note that FieldName may be null for anonymous bitfields.
14309 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14310                                 IdentifierInfo *FieldName,
14311                                 QualType FieldTy, bool IsMsStruct,
14312                                 Expr *BitWidth, bool *ZeroWidth) {
14313   // Default to true; that shouldn't confuse checks for emptiness
14314   if (ZeroWidth)
14315     *ZeroWidth = true;
14316 
14317   // C99 6.7.2.1p4 - verify the field type.
14318   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14319   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14320     // Handle incomplete types with specific error.
14321     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14322       return ExprError();
14323     if (FieldName)
14324       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14325         << FieldName << FieldTy << BitWidth->getSourceRange();
14326     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14327       << FieldTy << BitWidth->getSourceRange();
14328   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14329                                              UPPC_BitFieldWidth))
14330     return ExprError();
14331 
14332   // If the bit-width is type- or value-dependent, don't try to check
14333   // it now.
14334   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14335     return BitWidth;
14336 
14337   llvm::APSInt Value;
14338   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14339   if (ICE.isInvalid())
14340     return ICE;
14341   BitWidth = ICE.get();
14342 
14343   if (Value != 0 && ZeroWidth)
14344     *ZeroWidth = false;
14345 
14346   // Zero-width bitfield is ok for anonymous field.
14347   if (Value == 0 && FieldName)
14348     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14349 
14350   if (Value.isSigned() && Value.isNegative()) {
14351     if (FieldName)
14352       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14353                << FieldName << Value.toString(10);
14354     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14355       << Value.toString(10);
14356   }
14357 
14358   if (!FieldTy->isDependentType()) {
14359     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14360     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14361     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14362 
14363     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14364     // ABI.
14365     bool CStdConstraintViolation =
14366         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14367     bool MSBitfieldViolation =
14368         Value.ugt(TypeStorageSize) &&
14369         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14370     if (CStdConstraintViolation || MSBitfieldViolation) {
14371       unsigned DiagWidth =
14372           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14373       if (FieldName)
14374         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14375                << FieldName << (unsigned)Value.getZExtValue()
14376                << !CStdConstraintViolation << DiagWidth;
14377 
14378       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14379              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14380              << DiagWidth;
14381     }
14382 
14383     // Warn on types where the user might conceivably expect to get all
14384     // specified bits as value bits: that's all integral types other than
14385     // 'bool'.
14386     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14387       if (FieldName)
14388         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14389             << FieldName << (unsigned)Value.getZExtValue()
14390             << (unsigned)TypeWidth;
14391       else
14392         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14393             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14394     }
14395   }
14396 
14397   return BitWidth;
14398 }
14399 
14400 /// ActOnField - Each field of a C struct/union is passed into this in order
14401 /// to create a FieldDecl object for it.
14402 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14403                        Declarator &D, Expr *BitfieldWidth) {
14404   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14405                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14406                                /*InitStyle=*/ICIS_NoInit, AS_public);
14407   return Res;
14408 }
14409 
14410 /// HandleField - Analyze a field of a C struct or a C++ data member.
14411 ///
14412 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14413                              SourceLocation DeclStart,
14414                              Declarator &D, Expr *BitWidth,
14415                              InClassInitStyle InitStyle,
14416                              AccessSpecifier AS) {
14417   if (D.isDecompositionDeclarator()) {
14418     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14419     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14420       << Decomp.getSourceRange();
14421     return nullptr;
14422   }
14423 
14424   IdentifierInfo *II = D.getIdentifier();
14425   SourceLocation Loc = DeclStart;
14426   if (II) Loc = D.getIdentifierLoc();
14427 
14428   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14429   QualType T = TInfo->getType();
14430   if (getLangOpts().CPlusPlus) {
14431     CheckExtraCXXDefaultArguments(D);
14432 
14433     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14434                                         UPPC_DataMemberType)) {
14435       D.setInvalidType();
14436       T = Context.IntTy;
14437       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14438     }
14439   }
14440 
14441   // TR 18037 does not allow fields to be declared with address spaces.
14442   if (T.getQualifiers().hasAddressSpace() ||
14443       T->isDependentAddressSpaceType() ||
14444       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14445     Diag(Loc, diag::err_field_with_address_space);
14446     D.setInvalidType();
14447   }
14448 
14449   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14450   // used as structure or union field: image, sampler, event or block types.
14451   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14452                           T->isSamplerT() || T->isBlockPointerType())) {
14453     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14454     D.setInvalidType();
14455   }
14456 
14457   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14458 
14459   if (D.getDeclSpec().isInlineSpecified())
14460     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14461         << getLangOpts().CPlusPlus1z;
14462   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14463     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14464          diag::err_invalid_thread)
14465       << DeclSpec::getSpecifierName(TSCS);
14466 
14467   // Check to see if this name was declared as a member previously
14468   NamedDecl *PrevDecl = nullptr;
14469   LookupResult Previous(*this, II, Loc, LookupMemberName,
14470                         ForVisibleRedeclaration);
14471   LookupName(Previous, S);
14472   switch (Previous.getResultKind()) {
14473     case LookupResult::Found:
14474     case LookupResult::FoundUnresolvedValue:
14475       PrevDecl = Previous.getAsSingle<NamedDecl>();
14476       break;
14477 
14478     case LookupResult::FoundOverloaded:
14479       PrevDecl = Previous.getRepresentativeDecl();
14480       break;
14481 
14482     case LookupResult::NotFound:
14483     case LookupResult::NotFoundInCurrentInstantiation:
14484     case LookupResult::Ambiguous:
14485       break;
14486   }
14487   Previous.suppressDiagnostics();
14488 
14489   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14490     // Maybe we will complain about the shadowed template parameter.
14491     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14492     // Just pretend that we didn't see the previous declaration.
14493     PrevDecl = nullptr;
14494   }
14495 
14496   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14497     PrevDecl = nullptr;
14498 
14499   bool Mutable
14500     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14501   SourceLocation TSSL = D.getLocStart();
14502   FieldDecl *NewFD
14503     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14504                      TSSL, AS, PrevDecl, &D);
14505 
14506   if (NewFD->isInvalidDecl())
14507     Record->setInvalidDecl();
14508 
14509   if (D.getDeclSpec().isModulePrivateSpecified())
14510     NewFD->setModulePrivate();
14511 
14512   if (NewFD->isInvalidDecl() && PrevDecl) {
14513     // Don't introduce NewFD into scope; there's already something
14514     // with the same name in the same scope.
14515   } else if (II) {
14516     PushOnScopeChains(NewFD, S);
14517   } else
14518     Record->addDecl(NewFD);
14519 
14520   return NewFD;
14521 }
14522 
14523 /// \brief Build a new FieldDecl and check its well-formedness.
14524 ///
14525 /// This routine builds a new FieldDecl given the fields name, type,
14526 /// record, etc. \p PrevDecl should refer to any previous declaration
14527 /// with the same name and in the same scope as the field to be
14528 /// created.
14529 ///
14530 /// \returns a new FieldDecl.
14531 ///
14532 /// \todo The Declarator argument is a hack. It will be removed once
14533 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14534                                 TypeSourceInfo *TInfo,
14535                                 RecordDecl *Record, SourceLocation Loc,
14536                                 bool Mutable, Expr *BitWidth,
14537                                 InClassInitStyle InitStyle,
14538                                 SourceLocation TSSL,
14539                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14540                                 Declarator *D) {
14541   IdentifierInfo *II = Name.getAsIdentifierInfo();
14542   bool InvalidDecl = false;
14543   if (D) InvalidDecl = D->isInvalidType();
14544 
14545   // If we receive a broken type, recover by assuming 'int' and
14546   // marking this declaration as invalid.
14547   if (T.isNull()) {
14548     InvalidDecl = true;
14549     T = Context.IntTy;
14550   }
14551 
14552   QualType EltTy = Context.getBaseElementType(T);
14553   if (!EltTy->isDependentType()) {
14554     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14555       // Fields of incomplete type force their record to be invalid.
14556       Record->setInvalidDecl();
14557       InvalidDecl = true;
14558     } else {
14559       NamedDecl *Def;
14560       EltTy->isIncompleteType(&Def);
14561       if (Def && Def->isInvalidDecl()) {
14562         Record->setInvalidDecl();
14563         InvalidDecl = true;
14564       }
14565     }
14566   }
14567 
14568   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14569   if (BitWidth && getLangOpts().OpenCL) {
14570     Diag(Loc, diag::err_opencl_bitfields);
14571     InvalidDecl = true;
14572   }
14573 
14574   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14575   // than a variably modified type.
14576   if (!InvalidDecl && T->isVariablyModifiedType()) {
14577     bool SizeIsNegative;
14578     llvm::APSInt Oversized;
14579 
14580     TypeSourceInfo *FixedTInfo =
14581       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14582                                                     SizeIsNegative,
14583                                                     Oversized);
14584     if (FixedTInfo) {
14585       Diag(Loc, diag::warn_illegal_constant_array_size);
14586       TInfo = FixedTInfo;
14587       T = FixedTInfo->getType();
14588     } else {
14589       if (SizeIsNegative)
14590         Diag(Loc, diag::err_typecheck_negative_array_size);
14591       else if (Oversized.getBoolValue())
14592         Diag(Loc, diag::err_array_too_large)
14593           << Oversized.toString(10);
14594       else
14595         Diag(Loc, diag::err_typecheck_field_variable_size);
14596       InvalidDecl = true;
14597     }
14598   }
14599 
14600   // Fields can not have abstract class types
14601   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14602                                              diag::err_abstract_type_in_decl,
14603                                              AbstractFieldType))
14604     InvalidDecl = true;
14605 
14606   bool ZeroWidth = false;
14607   if (InvalidDecl)
14608     BitWidth = nullptr;
14609   // If this is declared as a bit-field, check the bit-field.
14610   if (BitWidth) {
14611     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14612                               &ZeroWidth).get();
14613     if (!BitWidth) {
14614       InvalidDecl = true;
14615       BitWidth = nullptr;
14616       ZeroWidth = false;
14617     }
14618   }
14619 
14620   // Check that 'mutable' is consistent with the type of the declaration.
14621   if (!InvalidDecl && Mutable) {
14622     unsigned DiagID = 0;
14623     if (T->isReferenceType())
14624       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14625                                         : diag::err_mutable_reference;
14626     else if (T.isConstQualified())
14627       DiagID = diag::err_mutable_const;
14628 
14629     if (DiagID) {
14630       SourceLocation ErrLoc = Loc;
14631       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14632         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14633       Diag(ErrLoc, DiagID);
14634       if (DiagID != diag::ext_mutable_reference) {
14635         Mutable = false;
14636         InvalidDecl = true;
14637       }
14638     }
14639   }
14640 
14641   // C++11 [class.union]p8 (DR1460):
14642   //   At most one variant member of a union may have a
14643   //   brace-or-equal-initializer.
14644   if (InitStyle != ICIS_NoInit)
14645     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14646 
14647   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14648                                        BitWidth, Mutable, InitStyle);
14649   if (InvalidDecl)
14650     NewFD->setInvalidDecl();
14651 
14652   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14653     Diag(Loc, diag::err_duplicate_member) << II;
14654     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14655     NewFD->setInvalidDecl();
14656   }
14657 
14658   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14659     if (Record->isUnion()) {
14660       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14661         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14662         if (RDecl->getDefinition()) {
14663           // C++ [class.union]p1: An object of a class with a non-trivial
14664           // constructor, a non-trivial copy constructor, a non-trivial
14665           // destructor, or a non-trivial copy assignment operator
14666           // cannot be a member of a union, nor can an array of such
14667           // objects.
14668           if (CheckNontrivialField(NewFD))
14669             NewFD->setInvalidDecl();
14670         }
14671       }
14672 
14673       // C++ [class.union]p1: If a union contains a member of reference type,
14674       // the program is ill-formed, except when compiling with MSVC extensions
14675       // enabled.
14676       if (EltTy->isReferenceType()) {
14677         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14678                                     diag::ext_union_member_of_reference_type :
14679                                     diag::err_union_member_of_reference_type)
14680           << NewFD->getDeclName() << EltTy;
14681         if (!getLangOpts().MicrosoftExt)
14682           NewFD->setInvalidDecl();
14683       }
14684     }
14685   }
14686 
14687   // FIXME: We need to pass in the attributes given an AST
14688   // representation, not a parser representation.
14689   if (D) {
14690     // FIXME: The current scope is almost... but not entirely... correct here.
14691     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14692 
14693     if (NewFD->hasAttrs())
14694       CheckAlignasUnderalignment(NewFD);
14695   }
14696 
14697   // In auto-retain/release, infer strong retension for fields of
14698   // retainable type.
14699   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14700     NewFD->setInvalidDecl();
14701 
14702   if (T.isObjCGCWeak())
14703     Diag(Loc, diag::warn_attribute_weak_on_field);
14704 
14705   NewFD->setAccess(AS);
14706   return NewFD;
14707 }
14708 
14709 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14710   assert(FD);
14711   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14712 
14713   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14714     return false;
14715 
14716   QualType EltTy = Context.getBaseElementType(FD->getType());
14717   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14718     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14719     if (RDecl->getDefinition()) {
14720       // We check for copy constructors before constructors
14721       // because otherwise we'll never get complaints about
14722       // copy constructors.
14723 
14724       CXXSpecialMember member = CXXInvalid;
14725       // We're required to check for any non-trivial constructors. Since the
14726       // implicit default constructor is suppressed if there are any
14727       // user-declared constructors, we just need to check that there is a
14728       // trivial default constructor and a trivial copy constructor. (We don't
14729       // worry about move constructors here, since this is a C++98 check.)
14730       if (RDecl->hasNonTrivialCopyConstructor())
14731         member = CXXCopyConstructor;
14732       else if (!RDecl->hasTrivialDefaultConstructor())
14733         member = CXXDefaultConstructor;
14734       else if (RDecl->hasNonTrivialCopyAssignment())
14735         member = CXXCopyAssignment;
14736       else if (RDecl->hasNonTrivialDestructor())
14737         member = CXXDestructor;
14738 
14739       if (member != CXXInvalid) {
14740         if (!getLangOpts().CPlusPlus11 &&
14741             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14742           // Objective-C++ ARC: it is an error to have a non-trivial field of
14743           // a union. However, system headers in Objective-C programs
14744           // occasionally have Objective-C lifetime objects within unions,
14745           // and rather than cause the program to fail, we make those
14746           // members unavailable.
14747           SourceLocation Loc = FD->getLocation();
14748           if (getSourceManager().isInSystemHeader(Loc)) {
14749             if (!FD->hasAttr<UnavailableAttr>())
14750               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14751                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14752             return false;
14753           }
14754         }
14755 
14756         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14757                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14758                diag::err_illegal_union_or_anon_struct_member)
14759           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14760         DiagnoseNontrivial(RDecl, member);
14761         return !getLangOpts().CPlusPlus11;
14762       }
14763     }
14764   }
14765 
14766   return false;
14767 }
14768 
14769 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14770 ///  AST enum value.
14771 static ObjCIvarDecl::AccessControl
14772 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14773   switch (ivarVisibility) {
14774   default: llvm_unreachable("Unknown visitibility kind");
14775   case tok::objc_private: return ObjCIvarDecl::Private;
14776   case tok::objc_public: return ObjCIvarDecl::Public;
14777   case tok::objc_protected: return ObjCIvarDecl::Protected;
14778   case tok::objc_package: return ObjCIvarDecl::Package;
14779   }
14780 }
14781 
14782 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14783 /// in order to create an IvarDecl object for it.
14784 Decl *Sema::ActOnIvar(Scope *S,
14785                                 SourceLocation DeclStart,
14786                                 Declarator &D, Expr *BitfieldWidth,
14787                                 tok::ObjCKeywordKind Visibility) {
14788 
14789   IdentifierInfo *II = D.getIdentifier();
14790   Expr *BitWidth = (Expr*)BitfieldWidth;
14791   SourceLocation Loc = DeclStart;
14792   if (II) Loc = D.getIdentifierLoc();
14793 
14794   // FIXME: Unnamed fields can be handled in various different ways, for
14795   // example, unnamed unions inject all members into the struct namespace!
14796 
14797   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14798   QualType T = TInfo->getType();
14799 
14800   if (BitWidth) {
14801     // 6.7.2.1p3, 6.7.2.1p4
14802     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14803     if (!BitWidth)
14804       D.setInvalidType();
14805   } else {
14806     // Not a bitfield.
14807 
14808     // validate II.
14809 
14810   }
14811   if (T->isReferenceType()) {
14812     Diag(Loc, diag::err_ivar_reference_type);
14813     D.setInvalidType();
14814   }
14815   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14816   // than a variably modified type.
14817   else if (T->isVariablyModifiedType()) {
14818     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14819     D.setInvalidType();
14820   }
14821 
14822   // Get the visibility (access control) for this ivar.
14823   ObjCIvarDecl::AccessControl ac =
14824     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14825                                         : ObjCIvarDecl::None;
14826   // Must set ivar's DeclContext to its enclosing interface.
14827   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14828   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14829     return nullptr;
14830   ObjCContainerDecl *EnclosingContext;
14831   if (ObjCImplementationDecl *IMPDecl =
14832       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14833     if (LangOpts.ObjCRuntime.isFragile()) {
14834     // Case of ivar declared in an implementation. Context is that of its class.
14835       EnclosingContext = IMPDecl->getClassInterface();
14836       assert(EnclosingContext && "Implementation has no class interface!");
14837     }
14838     else
14839       EnclosingContext = EnclosingDecl;
14840   } else {
14841     if (ObjCCategoryDecl *CDecl =
14842         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14843       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14844         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14845         return nullptr;
14846       }
14847     }
14848     EnclosingContext = EnclosingDecl;
14849   }
14850 
14851   // Construct the decl.
14852   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14853                                              DeclStart, Loc, II, T,
14854                                              TInfo, ac, (Expr *)BitfieldWidth);
14855 
14856   if (II) {
14857     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14858                                            ForVisibleRedeclaration);
14859     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14860         && !isa<TagDecl>(PrevDecl)) {
14861       Diag(Loc, diag::err_duplicate_member) << II;
14862       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14863       NewID->setInvalidDecl();
14864     }
14865   }
14866 
14867   // Process attributes attached to the ivar.
14868   ProcessDeclAttributes(S, NewID, D);
14869 
14870   if (D.isInvalidType())
14871     NewID->setInvalidDecl();
14872 
14873   // In ARC, infer 'retaining' for ivars of retainable type.
14874   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14875     NewID->setInvalidDecl();
14876 
14877   if (D.getDeclSpec().isModulePrivateSpecified())
14878     NewID->setModulePrivate();
14879 
14880   if (II) {
14881     // FIXME: When interfaces are DeclContexts, we'll need to add
14882     // these to the interface.
14883     S->AddDecl(NewID);
14884     IdResolver.AddDecl(NewID);
14885   }
14886 
14887   if (LangOpts.ObjCRuntime.isNonFragile() &&
14888       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14889     Diag(Loc, diag::warn_ivars_in_interface);
14890 
14891   return NewID;
14892 }
14893 
14894 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14895 /// class and class extensions. For every class \@interface and class
14896 /// extension \@interface, if the last ivar is a bitfield of any type,
14897 /// then add an implicit `char :0` ivar to the end of that interface.
14898 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14899                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14900   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14901     return;
14902 
14903   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14904   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14905 
14906   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14907     return;
14908   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14909   if (!ID) {
14910     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14911       if (!CD->IsClassExtension())
14912         return;
14913     }
14914     // No need to add this to end of @implementation.
14915     else
14916       return;
14917   }
14918   // All conditions are met. Add a new bitfield to the tail end of ivars.
14919   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14920   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14921 
14922   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14923                               DeclLoc, DeclLoc, nullptr,
14924                               Context.CharTy,
14925                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14926                                                                DeclLoc),
14927                               ObjCIvarDecl::Private, BW,
14928                               true);
14929   AllIvarDecls.push_back(Ivar);
14930 }
14931 
14932 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14933                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14934                        SourceLocation RBrac, AttributeList *Attr) {
14935   assert(EnclosingDecl && "missing record or interface decl");
14936 
14937   // If this is an Objective-C @implementation or category and we have
14938   // new fields here we should reset the layout of the interface since
14939   // it will now change.
14940   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14941     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14942     switch (DC->getKind()) {
14943     default: break;
14944     case Decl::ObjCCategory:
14945       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14946       break;
14947     case Decl::ObjCImplementation:
14948       Context.
14949         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14950       break;
14951     }
14952   }
14953 
14954   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14955 
14956   // Start counting up the number of named members; make sure to include
14957   // members of anonymous structs and unions in the total.
14958   unsigned NumNamedMembers = 0;
14959   if (Record) {
14960     for (const auto *I : Record->decls()) {
14961       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14962         if (IFD->getDeclName())
14963           ++NumNamedMembers;
14964     }
14965   }
14966 
14967   // Verify that all the fields are okay.
14968   SmallVector<FieldDecl*, 32> RecFields;
14969 
14970   bool ObjCFieldLifetimeErrReported = false;
14971   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14972        i != end; ++i) {
14973     FieldDecl *FD = cast<FieldDecl>(*i);
14974 
14975     // Get the type for the field.
14976     const Type *FDTy = FD->getType().getTypePtr();
14977 
14978     if (!FD->isAnonymousStructOrUnion()) {
14979       // Remember all fields written by the user.
14980       RecFields.push_back(FD);
14981     }
14982 
14983     // If the field is already invalid for some reason, don't emit more
14984     // diagnostics about it.
14985     if (FD->isInvalidDecl()) {
14986       EnclosingDecl->setInvalidDecl();
14987       continue;
14988     }
14989 
14990     // C99 6.7.2.1p2:
14991     //   A structure or union shall not contain a member with
14992     //   incomplete or function type (hence, a structure shall not
14993     //   contain an instance of itself, but may contain a pointer to
14994     //   an instance of itself), except that the last member of a
14995     //   structure with more than one named member may have incomplete
14996     //   array type; such a structure (and any union containing,
14997     //   possibly recursively, a member that is such a structure)
14998     //   shall not be a member of a structure or an element of an
14999     //   array.
15000     bool IsLastField = (i + 1 == Fields.end());
15001     if (FDTy->isFunctionType()) {
15002       // Field declared as a function.
15003       Diag(FD->getLocation(), diag::err_field_declared_as_function)
15004         << FD->getDeclName();
15005       FD->setInvalidDecl();
15006       EnclosingDecl->setInvalidDecl();
15007       continue;
15008     } else if (FDTy->isIncompleteArrayType() &&
15009                (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15010       if (Record) {
15011         // Flexible array member.
15012         // Microsoft and g++ is more permissive regarding flexible array.
15013         // It will accept flexible array in union and also
15014         // as the sole element of a struct/class.
15015         unsigned DiagID = 0;
15016         if (!Record->isUnion() && !IsLastField) {
15017           Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15018             << FD->getDeclName() << FD->getType() << Record->getTagKind();
15019           Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15020           FD->setInvalidDecl();
15021           EnclosingDecl->setInvalidDecl();
15022           continue;
15023         } else if (Record->isUnion())
15024           DiagID = getLangOpts().MicrosoftExt
15025                        ? diag::ext_flexible_array_union_ms
15026                        : getLangOpts().CPlusPlus
15027                              ? diag::ext_flexible_array_union_gnu
15028                              : diag::err_flexible_array_union;
15029         else if (NumNamedMembers < 1)
15030           DiagID = getLangOpts().MicrosoftExt
15031                        ? diag::ext_flexible_array_empty_aggregate_ms
15032                        : getLangOpts().CPlusPlus
15033                              ? diag::ext_flexible_array_empty_aggregate_gnu
15034                              : diag::err_flexible_array_empty_aggregate;
15035 
15036         if (DiagID)
15037           Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15038                                           << Record->getTagKind();
15039         // While the layout of types that contain virtual bases is not specified
15040         // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15041         // virtual bases after the derived members.  This would make a flexible
15042         // array member declared at the end of an object not adjacent to the end
15043         // of the type.
15044         if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15045           if (RD->getNumVBases() != 0)
15046             Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15047               << FD->getDeclName() << Record->getTagKind();
15048         if (!getLangOpts().C99)
15049           Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15050             << FD->getDeclName() << Record->getTagKind();
15051 
15052         // If the element type has a non-trivial destructor, we would not
15053         // implicitly destroy the elements, so disallow it for now.
15054         //
15055         // FIXME: GCC allows this. We should probably either implicitly delete
15056         // the destructor of the containing class, or just allow this.
15057         QualType BaseElem = Context.getBaseElementType(FD->getType());
15058         if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15059           Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15060             << FD->getDeclName() << FD->getType();
15061           FD->setInvalidDecl();
15062           EnclosingDecl->setInvalidDecl();
15063           continue;
15064         }
15065         // Okay, we have a legal flexible array member at the end of the struct.
15066         Record->setHasFlexibleArrayMember(true);
15067       } else {
15068         // In ObjCContainerDecl ivars with incomplete array type are accepted,
15069         // unless they are followed by another ivar. That check is done
15070         // elsewhere, after synthesized ivars are known.
15071       }
15072     } else if (!FDTy->isDependentType() &&
15073                RequireCompleteType(FD->getLocation(), FD->getType(),
15074                                    diag::err_field_incomplete)) {
15075       // Incomplete type
15076       FD->setInvalidDecl();
15077       EnclosingDecl->setInvalidDecl();
15078       continue;
15079     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15080       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15081         // A type which contains a flexible array member is considered to be a
15082         // flexible array member.
15083         Record->setHasFlexibleArrayMember(true);
15084         if (!Record->isUnion()) {
15085           // If this is a struct/class and this is not the last element, reject
15086           // it.  Note that GCC supports variable sized arrays in the middle of
15087           // structures.
15088           if (!IsLastField)
15089             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15090               << FD->getDeclName() << FD->getType();
15091           else {
15092             // We support flexible arrays at the end of structs in
15093             // other structs as an extension.
15094             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15095               << FD->getDeclName();
15096           }
15097         }
15098       }
15099       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15100           RequireNonAbstractType(FD->getLocation(), FD->getType(),
15101                                  diag::err_abstract_type_in_decl,
15102                                  AbstractIvarType)) {
15103         // Ivars can not have abstract class types
15104         FD->setInvalidDecl();
15105       }
15106       if (Record && FDTTy->getDecl()->hasObjectMember())
15107         Record->setHasObjectMember(true);
15108       if (Record && FDTTy->getDecl()->hasVolatileMember())
15109         Record->setHasVolatileMember(true);
15110     } else if (FDTy->isObjCObjectType()) {
15111       /// A field cannot be an Objective-c object
15112       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15113         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15114       QualType T = Context.getObjCObjectPointerType(FD->getType());
15115       FD->setType(T);
15116     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15117                Record && !ObjCFieldLifetimeErrReported &&
15118                (!getLangOpts().CPlusPlus || Record->isUnion())) {
15119       // It's an error in ARC or Weak if a field has lifetime.
15120       // We don't want to report this in a system header, though,
15121       // so we just make the field unavailable.
15122       // FIXME: that's really not sufficient; we need to make the type
15123       // itself invalid to, say, initialize or copy.
15124       QualType T = FD->getType();
15125       if (T.hasNonTrivialObjCLifetime()) {
15126         SourceLocation loc = FD->getLocation();
15127         if (getSourceManager().isInSystemHeader(loc)) {
15128           if (!FD->hasAttr<UnavailableAttr>()) {
15129             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15130                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15131           }
15132         } else {
15133           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15134             << T->isBlockPointerType() << Record->getTagKind();
15135         }
15136         ObjCFieldLifetimeErrReported = true;
15137       }
15138     } else if (getLangOpts().ObjC1 &&
15139                getLangOpts().getGC() != LangOptions::NonGC &&
15140                Record && !Record->hasObjectMember()) {
15141       if (FD->getType()->isObjCObjectPointerType() ||
15142           FD->getType().isObjCGCStrong())
15143         Record->setHasObjectMember(true);
15144       else if (Context.getAsArrayType(FD->getType())) {
15145         QualType BaseType = Context.getBaseElementType(FD->getType());
15146         if (BaseType->isRecordType() &&
15147             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15148           Record->setHasObjectMember(true);
15149         else if (BaseType->isObjCObjectPointerType() ||
15150                  BaseType.isObjCGCStrong())
15151                Record->setHasObjectMember(true);
15152       }
15153     }
15154     if (Record && FD->getType().isVolatileQualified())
15155       Record->setHasVolatileMember(true);
15156     // Keep track of the number of named members.
15157     if (FD->getIdentifier())
15158       ++NumNamedMembers;
15159   }
15160 
15161   // Okay, we successfully defined 'Record'.
15162   if (Record) {
15163     bool Completed = false;
15164     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15165       if (!CXXRecord->isInvalidDecl()) {
15166         // Set access bits correctly on the directly-declared conversions.
15167         for (CXXRecordDecl::conversion_iterator
15168                I = CXXRecord->conversion_begin(),
15169                E = CXXRecord->conversion_end(); I != E; ++I)
15170           I.setAccess((*I)->getAccess());
15171       }
15172 
15173       if (!CXXRecord->isDependentType()) {
15174         if (CXXRecord->hasUserDeclaredDestructor()) {
15175           // Adjust user-defined destructor exception spec.
15176           if (getLangOpts().CPlusPlus11)
15177             AdjustDestructorExceptionSpec(CXXRecord,
15178                                           CXXRecord->getDestructor());
15179         }
15180 
15181         if (!CXXRecord->isInvalidDecl()) {
15182           // Add any implicitly-declared members to this class.
15183           AddImplicitlyDeclaredMembersToClass(CXXRecord);
15184 
15185           // If we have virtual base classes, we may end up finding multiple
15186           // final overriders for a given virtual function. Check for this
15187           // problem now.
15188           if (CXXRecord->getNumVBases()) {
15189             CXXFinalOverriderMap FinalOverriders;
15190             CXXRecord->getFinalOverriders(FinalOverriders);
15191 
15192             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15193                                              MEnd = FinalOverriders.end();
15194                  M != MEnd; ++M) {
15195               for (OverridingMethods::iterator SO = M->second.begin(),
15196                                             SOEnd = M->second.end();
15197                    SO != SOEnd; ++SO) {
15198                 assert(SO->second.size() > 0 &&
15199                        "Virtual function without overridding functions?");
15200                 if (SO->second.size() == 1)
15201                   continue;
15202 
15203                 // C++ [class.virtual]p2:
15204                 //   In a derived class, if a virtual member function of a base
15205                 //   class subobject has more than one final overrider the
15206                 //   program is ill-formed.
15207                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15208                   << (const NamedDecl *)M->first << Record;
15209                 Diag(M->first->getLocation(),
15210                      diag::note_overridden_virtual_function);
15211                 for (OverridingMethods::overriding_iterator
15212                           OM = SO->second.begin(),
15213                        OMEnd = SO->second.end();
15214                      OM != OMEnd; ++OM)
15215                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15216                     << (const NamedDecl *)M->first << OM->Method->getParent();
15217 
15218                 Record->setInvalidDecl();
15219               }
15220             }
15221             CXXRecord->completeDefinition(&FinalOverriders);
15222             Completed = true;
15223           }
15224         }
15225       }
15226     }
15227 
15228     if (!Completed)
15229       Record->completeDefinition();
15230 
15231     // We may have deferred checking for a deleted destructor. Check now.
15232     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15233       auto *Dtor = CXXRecord->getDestructor();
15234       if (Dtor && Dtor->isImplicit() &&
15235           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15236         CXXRecord->setImplicitDestructorIsDeleted();
15237         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15238       }
15239     }
15240 
15241     if (Record->hasAttrs()) {
15242       CheckAlignasUnderalignment(Record);
15243 
15244       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15245         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15246                                            IA->getRange(), IA->getBestCase(),
15247                                            IA->getSemanticSpelling());
15248     }
15249 
15250     // Check if the structure/union declaration is a type that can have zero
15251     // size in C. For C this is a language extension, for C++ it may cause
15252     // compatibility problems.
15253     bool CheckForZeroSize;
15254     if (!getLangOpts().CPlusPlus) {
15255       CheckForZeroSize = true;
15256     } else {
15257       // For C++ filter out types that cannot be referenced in C code.
15258       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15259       CheckForZeroSize =
15260           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15261           !CXXRecord->isDependentType() &&
15262           CXXRecord->isCLike();
15263     }
15264     if (CheckForZeroSize) {
15265       bool ZeroSize = true;
15266       bool IsEmpty = true;
15267       unsigned NonBitFields = 0;
15268       for (RecordDecl::field_iterator I = Record->field_begin(),
15269                                       E = Record->field_end();
15270            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15271         IsEmpty = false;
15272         if (I->isUnnamedBitfield()) {
15273           if (I->getBitWidthValue(Context) > 0)
15274             ZeroSize = false;
15275         } else {
15276           ++NonBitFields;
15277           QualType FieldType = I->getType();
15278           if (FieldType->isIncompleteType() ||
15279               !Context.getTypeSizeInChars(FieldType).isZero())
15280             ZeroSize = false;
15281         }
15282       }
15283 
15284       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15285       // allowed in C++, but warn if its declaration is inside
15286       // extern "C" block.
15287       if (ZeroSize) {
15288         Diag(RecLoc, getLangOpts().CPlusPlus ?
15289                          diag::warn_zero_size_struct_union_in_extern_c :
15290                          diag::warn_zero_size_struct_union_compat)
15291           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15292       }
15293 
15294       // Structs without named members are extension in C (C99 6.7.2.1p7),
15295       // but are accepted by GCC.
15296       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15297         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15298                                diag::ext_no_named_members_in_struct_union)
15299           << Record->isUnion();
15300       }
15301     }
15302   } else {
15303     ObjCIvarDecl **ClsFields =
15304       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15305     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15306       ID->setEndOfDefinitionLoc(RBrac);
15307       // Add ivar's to class's DeclContext.
15308       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15309         ClsFields[i]->setLexicalDeclContext(ID);
15310         ID->addDecl(ClsFields[i]);
15311       }
15312       // Must enforce the rule that ivars in the base classes may not be
15313       // duplicates.
15314       if (ID->getSuperClass())
15315         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15316     } else if (ObjCImplementationDecl *IMPDecl =
15317                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15318       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15319       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15320         // Ivar declared in @implementation never belongs to the implementation.
15321         // Only it is in implementation's lexical context.
15322         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15323       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15324       IMPDecl->setIvarLBraceLoc(LBrac);
15325       IMPDecl->setIvarRBraceLoc(RBrac);
15326     } else if (ObjCCategoryDecl *CDecl =
15327                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15328       // case of ivars in class extension; all other cases have been
15329       // reported as errors elsewhere.
15330       // FIXME. Class extension does not have a LocEnd field.
15331       // CDecl->setLocEnd(RBrac);
15332       // Add ivar's to class extension's DeclContext.
15333       // Diagnose redeclaration of private ivars.
15334       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15335       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15336         if (IDecl) {
15337           if (const ObjCIvarDecl *ClsIvar =
15338               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15339             Diag(ClsFields[i]->getLocation(),
15340                  diag::err_duplicate_ivar_declaration);
15341             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15342             continue;
15343           }
15344           for (const auto *Ext : IDecl->known_extensions()) {
15345             if (const ObjCIvarDecl *ClsExtIvar
15346                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15347               Diag(ClsFields[i]->getLocation(),
15348                    diag::err_duplicate_ivar_declaration);
15349               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15350               continue;
15351             }
15352           }
15353         }
15354         ClsFields[i]->setLexicalDeclContext(CDecl);
15355         CDecl->addDecl(ClsFields[i]);
15356       }
15357       CDecl->setIvarLBraceLoc(LBrac);
15358       CDecl->setIvarRBraceLoc(RBrac);
15359     }
15360   }
15361 
15362   if (Attr)
15363     ProcessDeclAttributeList(S, Record, Attr);
15364 }
15365 
15366 /// \brief Determine whether the given integral value is representable within
15367 /// the given type T.
15368 static bool isRepresentableIntegerValue(ASTContext &Context,
15369                                         llvm::APSInt &Value,
15370                                         QualType T) {
15371   assert(T->isIntegralType(Context) && "Integral type required!");
15372   unsigned BitWidth = Context.getIntWidth(T);
15373 
15374   if (Value.isUnsigned() || Value.isNonNegative()) {
15375     if (T->isSignedIntegerOrEnumerationType())
15376       --BitWidth;
15377     return Value.getActiveBits() <= BitWidth;
15378   }
15379   return Value.getMinSignedBits() <= BitWidth;
15380 }
15381 
15382 // \brief Given an integral type, return the next larger integral type
15383 // (or a NULL type of no such type exists).
15384 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15385   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15386   // enum checking below.
15387   assert(T->isIntegralType(Context) && "Integral type required!");
15388   const unsigned NumTypes = 4;
15389   QualType SignedIntegralTypes[NumTypes] = {
15390     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15391   };
15392   QualType UnsignedIntegralTypes[NumTypes] = {
15393     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15394     Context.UnsignedLongLongTy
15395   };
15396 
15397   unsigned BitWidth = Context.getTypeSize(T);
15398   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15399                                                         : UnsignedIntegralTypes;
15400   for (unsigned I = 0; I != NumTypes; ++I)
15401     if (Context.getTypeSize(Types[I]) > BitWidth)
15402       return Types[I];
15403 
15404   return QualType();
15405 }
15406 
15407 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15408                                           EnumConstantDecl *LastEnumConst,
15409                                           SourceLocation IdLoc,
15410                                           IdentifierInfo *Id,
15411                                           Expr *Val) {
15412   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15413   llvm::APSInt EnumVal(IntWidth);
15414   QualType EltTy;
15415 
15416   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15417     Val = nullptr;
15418 
15419   if (Val)
15420     Val = DefaultLvalueConversion(Val).get();
15421 
15422   if (Val) {
15423     if (Enum->isDependentType() || Val->isTypeDependent())
15424       EltTy = Context.DependentTy;
15425     else {
15426       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15427           !getLangOpts().MSVCCompat) {
15428         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15429         // constant-expression in the enumerator-definition shall be a converted
15430         // constant expression of the underlying type.
15431         EltTy = Enum->getIntegerType();
15432         ExprResult Converted =
15433           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15434                                            CCEK_Enumerator);
15435         if (Converted.isInvalid())
15436           Val = nullptr;
15437         else
15438           Val = Converted.get();
15439       } else if (!Val->isValueDependent() &&
15440                  !(Val = VerifyIntegerConstantExpression(Val,
15441                                                          &EnumVal).get())) {
15442         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15443       } else {
15444         if (Enum->isFixed()) {
15445           EltTy = Enum->getIntegerType();
15446 
15447           // In Obj-C and Microsoft mode, require the enumeration value to be
15448           // representable in the underlying type of the enumeration. In C++11,
15449           // we perform a non-narrowing conversion as part of converted constant
15450           // expression checking.
15451           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15452             if (getLangOpts().MSVCCompat) {
15453               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15454               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15455             } else
15456               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15457           } else
15458             Val = ImpCastExprToType(Val, EltTy,
15459                                     EltTy->isBooleanType() ?
15460                                     CK_IntegralToBoolean : CK_IntegralCast)
15461                     .get();
15462         } else if (getLangOpts().CPlusPlus) {
15463           // C++11 [dcl.enum]p5:
15464           //   If the underlying type is not fixed, the type of each enumerator
15465           //   is the type of its initializing value:
15466           //     - If an initializer is specified for an enumerator, the
15467           //       initializing value has the same type as the expression.
15468           EltTy = Val->getType();
15469         } else {
15470           // C99 6.7.2.2p2:
15471           //   The expression that defines the value of an enumeration constant
15472           //   shall be an integer constant expression that has a value
15473           //   representable as an int.
15474 
15475           // Complain if the value is not representable in an int.
15476           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15477             Diag(IdLoc, diag::ext_enum_value_not_int)
15478               << EnumVal.toString(10) << Val->getSourceRange()
15479               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15480           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15481             // Force the type of the expression to 'int'.
15482             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15483           }
15484           EltTy = Val->getType();
15485         }
15486       }
15487     }
15488   }
15489 
15490   if (!Val) {
15491     if (Enum->isDependentType())
15492       EltTy = Context.DependentTy;
15493     else if (!LastEnumConst) {
15494       // C++0x [dcl.enum]p5:
15495       //   If the underlying type is not fixed, the type of each enumerator
15496       //   is the type of its initializing value:
15497       //     - If no initializer is specified for the first enumerator, the
15498       //       initializing value has an unspecified integral type.
15499       //
15500       // GCC uses 'int' for its unspecified integral type, as does
15501       // C99 6.7.2.2p3.
15502       if (Enum->isFixed()) {
15503         EltTy = Enum->getIntegerType();
15504       }
15505       else {
15506         EltTy = Context.IntTy;
15507       }
15508     } else {
15509       // Assign the last value + 1.
15510       EnumVal = LastEnumConst->getInitVal();
15511       ++EnumVal;
15512       EltTy = LastEnumConst->getType();
15513 
15514       // Check for overflow on increment.
15515       if (EnumVal < LastEnumConst->getInitVal()) {
15516         // C++0x [dcl.enum]p5:
15517         //   If the underlying type is not fixed, the type of each enumerator
15518         //   is the type of its initializing value:
15519         //
15520         //     - Otherwise the type of the initializing value is the same as
15521         //       the type of the initializing value of the preceding enumerator
15522         //       unless the incremented value is not representable in that type,
15523         //       in which case the type is an unspecified integral type
15524         //       sufficient to contain the incremented value. If no such type
15525         //       exists, the program is ill-formed.
15526         QualType T = getNextLargerIntegralType(Context, EltTy);
15527         if (T.isNull() || Enum->isFixed()) {
15528           // There is no integral type larger enough to represent this
15529           // value. Complain, then allow the value to wrap around.
15530           EnumVal = LastEnumConst->getInitVal();
15531           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15532           ++EnumVal;
15533           if (Enum->isFixed())
15534             // When the underlying type is fixed, this is ill-formed.
15535             Diag(IdLoc, diag::err_enumerator_wrapped)
15536               << EnumVal.toString(10)
15537               << EltTy;
15538           else
15539             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15540               << EnumVal.toString(10);
15541         } else {
15542           EltTy = T;
15543         }
15544 
15545         // Retrieve the last enumerator's value, extent that type to the
15546         // type that is supposed to be large enough to represent the incremented
15547         // value, then increment.
15548         EnumVal = LastEnumConst->getInitVal();
15549         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15550         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15551         ++EnumVal;
15552 
15553         // If we're not in C++, diagnose the overflow of enumerator values,
15554         // which in C99 means that the enumerator value is not representable in
15555         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15556         // permits enumerator values that are representable in some larger
15557         // integral type.
15558         if (!getLangOpts().CPlusPlus && !T.isNull())
15559           Diag(IdLoc, diag::warn_enum_value_overflow);
15560       } else if (!getLangOpts().CPlusPlus &&
15561                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15562         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15563         Diag(IdLoc, diag::ext_enum_value_not_int)
15564           << EnumVal.toString(10) << 1;
15565       }
15566     }
15567   }
15568 
15569   if (!EltTy->isDependentType()) {
15570     // Make the enumerator value match the signedness and size of the
15571     // enumerator's type.
15572     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15573     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15574   }
15575 
15576   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15577                                   Val, EnumVal);
15578 }
15579 
15580 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15581                                                 SourceLocation IILoc) {
15582   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15583       !getLangOpts().CPlusPlus)
15584     return SkipBodyInfo();
15585 
15586   // We have an anonymous enum definition. Look up the first enumerator to
15587   // determine if we should merge the definition with an existing one and
15588   // skip the body.
15589   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15590                                          forRedeclarationInCurContext());
15591   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15592   if (!PrevECD)
15593     return SkipBodyInfo();
15594 
15595   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15596   NamedDecl *Hidden;
15597   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15598     SkipBodyInfo Skip;
15599     Skip.Previous = Hidden;
15600     return Skip;
15601   }
15602 
15603   return SkipBodyInfo();
15604 }
15605 
15606 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15607                               SourceLocation IdLoc, IdentifierInfo *Id,
15608                               AttributeList *Attr,
15609                               SourceLocation EqualLoc, Expr *Val) {
15610   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15611   EnumConstantDecl *LastEnumConst =
15612     cast_or_null<EnumConstantDecl>(lastEnumConst);
15613 
15614   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15615   // we find one that is.
15616   S = getNonFieldDeclScope(S);
15617 
15618   // Verify that there isn't already something declared with this name in this
15619   // scope.
15620   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15621                                          ForVisibleRedeclaration);
15622   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15623     // Maybe we will complain about the shadowed template parameter.
15624     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15625     // Just pretend that we didn't see the previous declaration.
15626     PrevDecl = nullptr;
15627   }
15628 
15629   // C++ [class.mem]p15:
15630   // If T is the name of a class, then each of the following shall have a name
15631   // different from T:
15632   // - every enumerator of every member of class T that is an unscoped
15633   // enumerated type
15634   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15635     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15636                             DeclarationNameInfo(Id, IdLoc));
15637 
15638   EnumConstantDecl *New =
15639     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15640   if (!New)
15641     return nullptr;
15642 
15643   if (PrevDecl) {
15644     // When in C++, we may get a TagDecl with the same name; in this case the
15645     // enum constant will 'hide' the tag.
15646     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15647            "Received TagDecl when not in C++!");
15648     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15649       if (isa<EnumConstantDecl>(PrevDecl))
15650         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15651       else
15652         Diag(IdLoc, diag::err_redefinition) << Id;
15653       notePreviousDefinition(PrevDecl, IdLoc);
15654       return nullptr;
15655     }
15656   }
15657 
15658   // Process attributes.
15659   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15660   AddPragmaAttributes(S, New);
15661 
15662   // Register this decl in the current scope stack.
15663   New->setAccess(TheEnumDecl->getAccess());
15664   PushOnScopeChains(New, S);
15665 
15666   ActOnDocumentableDecl(New);
15667 
15668   return New;
15669 }
15670 
15671 // Returns true when the enum initial expression does not trigger the
15672 // duplicate enum warning.  A few common cases are exempted as follows:
15673 // Element2 = Element1
15674 // Element2 = Element1 + 1
15675 // Element2 = Element1 - 1
15676 // Where Element2 and Element1 are from the same enum.
15677 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15678   Expr *InitExpr = ECD->getInitExpr();
15679   if (!InitExpr)
15680     return true;
15681   InitExpr = InitExpr->IgnoreImpCasts();
15682 
15683   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15684     if (!BO->isAdditiveOp())
15685       return true;
15686     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15687     if (!IL)
15688       return true;
15689     if (IL->getValue() != 1)
15690       return true;
15691 
15692     InitExpr = BO->getLHS();
15693   }
15694 
15695   // This checks if the elements are from the same enum.
15696   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15697   if (!DRE)
15698     return true;
15699 
15700   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15701   if (!EnumConstant)
15702     return true;
15703 
15704   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15705       Enum)
15706     return true;
15707 
15708   return false;
15709 }
15710 
15711 namespace {
15712 struct DupKey {
15713   int64_t val;
15714   bool isTombstoneOrEmptyKey;
15715   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15716     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15717 };
15718 
15719 static DupKey GetDupKey(const llvm::APSInt& Val) {
15720   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15721                 false);
15722 }
15723 
15724 struct DenseMapInfoDupKey {
15725   static DupKey getEmptyKey() { return DupKey(0, true); }
15726   static DupKey getTombstoneKey() { return DupKey(1, true); }
15727   static unsigned getHashValue(const DupKey Key) {
15728     return (unsigned)(Key.val * 37);
15729   }
15730   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15731     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15732            LHS.val == RHS.val;
15733   }
15734 };
15735 } // end anonymous namespace
15736 
15737 // Emits a warning when an element is implicitly set a value that
15738 // a previous element has already been set to.
15739 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15740                                         EnumDecl *Enum,
15741                                         QualType EnumType) {
15742   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15743     return;
15744   // Avoid anonymous enums
15745   if (!Enum->getIdentifier())
15746     return;
15747 
15748   // Only check for small enums.
15749   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15750     return;
15751 
15752   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15753   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15754 
15755   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15756   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15757           ValueToVectorMap;
15758 
15759   DuplicatesVector DupVector;
15760   ValueToVectorMap EnumMap;
15761 
15762   // Populate the EnumMap with all values represented by enum constants without
15763   // an initialier.
15764   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15765     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15766 
15767     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15768     // this constant.  Skip this enum since it may be ill-formed.
15769     if (!ECD) {
15770       return;
15771     }
15772 
15773     if (ECD->getInitExpr())
15774       continue;
15775 
15776     DupKey Key = GetDupKey(ECD->getInitVal());
15777     DeclOrVector &Entry = EnumMap[Key];
15778 
15779     // First time encountering this value.
15780     if (Entry.isNull())
15781       Entry = ECD;
15782   }
15783 
15784   // Create vectors for any values that has duplicates.
15785   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15786     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15787     if (!ValidDuplicateEnum(ECD, Enum))
15788       continue;
15789 
15790     DupKey Key = GetDupKey(ECD->getInitVal());
15791 
15792     DeclOrVector& Entry = EnumMap[Key];
15793     if (Entry.isNull())
15794       continue;
15795 
15796     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15797       // Ensure constants are different.
15798       if (D == ECD)
15799         continue;
15800 
15801       // Create new vector and push values onto it.
15802       ECDVector *Vec = new ECDVector();
15803       Vec->push_back(D);
15804       Vec->push_back(ECD);
15805 
15806       // Update entry to point to the duplicates vector.
15807       Entry = Vec;
15808 
15809       // Store the vector somewhere we can consult later for quick emission of
15810       // diagnostics.
15811       DupVector.push_back(Vec);
15812       continue;
15813     }
15814 
15815     ECDVector *Vec = Entry.get<ECDVector*>();
15816     // Make sure constants are not added more than once.
15817     if (*Vec->begin() == ECD)
15818       continue;
15819 
15820     Vec->push_back(ECD);
15821   }
15822 
15823   // Emit diagnostics.
15824   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15825                                   DupVectorEnd = DupVector.end();
15826        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15827     ECDVector *Vec = *DupVectorIter;
15828     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15829 
15830     // Emit warning for one enum constant.
15831     ECDVector::iterator I = Vec->begin();
15832     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15833       << (*I)->getName() << (*I)->getInitVal().toString(10)
15834       << (*I)->getSourceRange();
15835     ++I;
15836 
15837     // Emit one note for each of the remaining enum constants with
15838     // the same value.
15839     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15840       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15841         << (*I)->getName() << (*I)->getInitVal().toString(10)
15842         << (*I)->getSourceRange();
15843     delete Vec;
15844   }
15845 }
15846 
15847 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15848                              bool AllowMask) const {
15849   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15850   assert(ED->isCompleteDefinition() && "expected enum definition");
15851 
15852   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15853   llvm::APInt &FlagBits = R.first->second;
15854 
15855   if (R.second) {
15856     for (auto *E : ED->enumerators()) {
15857       const auto &EVal = E->getInitVal();
15858       // Only single-bit enumerators introduce new flag values.
15859       if (EVal.isPowerOf2())
15860         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15861     }
15862   }
15863 
15864   // A value is in a flag enum if either its bits are a subset of the enum's
15865   // flag bits (the first condition) or we are allowing masks and the same is
15866   // true of its complement (the second condition). When masks are allowed, we
15867   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15868   //
15869   // While it's true that any value could be used as a mask, the assumption is
15870   // that a mask will have all of the insignificant bits set. Anything else is
15871   // likely a logic error.
15872   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15873   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15874 }
15875 
15876 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15877                          Decl *EnumDeclX,
15878                          ArrayRef<Decl *> Elements,
15879                          Scope *S, AttributeList *Attr) {
15880   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15881   QualType EnumType = Context.getTypeDeclType(Enum);
15882 
15883   if (Attr)
15884     ProcessDeclAttributeList(S, Enum, Attr);
15885 
15886   if (Enum->isDependentType()) {
15887     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15888       EnumConstantDecl *ECD =
15889         cast_or_null<EnumConstantDecl>(Elements[i]);
15890       if (!ECD) continue;
15891 
15892       ECD->setType(EnumType);
15893     }
15894 
15895     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15896     return;
15897   }
15898 
15899   // TODO: If the result value doesn't fit in an int, it must be a long or long
15900   // long value.  ISO C does not support this, but GCC does as an extension,
15901   // emit a warning.
15902   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15903   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15904   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15905 
15906   // Verify that all the values are okay, compute the size of the values, and
15907   // reverse the list.
15908   unsigned NumNegativeBits = 0;
15909   unsigned NumPositiveBits = 0;
15910 
15911   // Keep track of whether all elements have type int.
15912   bool AllElementsInt = true;
15913 
15914   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15915     EnumConstantDecl *ECD =
15916       cast_or_null<EnumConstantDecl>(Elements[i]);
15917     if (!ECD) continue;  // Already issued a diagnostic.
15918 
15919     const llvm::APSInt &InitVal = ECD->getInitVal();
15920 
15921     // Keep track of the size of positive and negative values.
15922     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15923       NumPositiveBits = std::max(NumPositiveBits,
15924                                  (unsigned)InitVal.getActiveBits());
15925     else
15926       NumNegativeBits = std::max(NumNegativeBits,
15927                                  (unsigned)InitVal.getMinSignedBits());
15928 
15929     // Keep track of whether every enum element has type int (very commmon).
15930     if (AllElementsInt)
15931       AllElementsInt = ECD->getType() == Context.IntTy;
15932   }
15933 
15934   // Figure out the type that should be used for this enum.
15935   QualType BestType;
15936   unsigned BestWidth;
15937 
15938   // C++0x N3000 [conv.prom]p3:
15939   //   An rvalue of an unscoped enumeration type whose underlying
15940   //   type is not fixed can be converted to an rvalue of the first
15941   //   of the following types that can represent all the values of
15942   //   the enumeration: int, unsigned int, long int, unsigned long
15943   //   int, long long int, or unsigned long long int.
15944   // C99 6.4.4.3p2:
15945   //   An identifier declared as an enumeration constant has type int.
15946   // The C99 rule is modified by a gcc extension
15947   QualType BestPromotionType;
15948 
15949   bool Packed = Enum->hasAttr<PackedAttr>();
15950   // -fshort-enums is the equivalent to specifying the packed attribute on all
15951   // enum definitions.
15952   if (LangOpts.ShortEnums)
15953     Packed = true;
15954 
15955   if (Enum->isFixed()) {
15956     BestType = Enum->getIntegerType();
15957     if (BestType->isPromotableIntegerType())
15958       BestPromotionType = Context.getPromotedIntegerType(BestType);
15959     else
15960       BestPromotionType = BestType;
15961 
15962     BestWidth = Context.getIntWidth(BestType);
15963   }
15964   else if (NumNegativeBits) {
15965     // If there is a negative value, figure out the smallest integer type (of
15966     // int/long/longlong) that fits.
15967     // If it's packed, check also if it fits a char or a short.
15968     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15969       BestType = Context.SignedCharTy;
15970       BestWidth = CharWidth;
15971     } else if (Packed && NumNegativeBits <= ShortWidth &&
15972                NumPositiveBits < ShortWidth) {
15973       BestType = Context.ShortTy;
15974       BestWidth = ShortWidth;
15975     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15976       BestType = Context.IntTy;
15977       BestWidth = IntWidth;
15978     } else {
15979       BestWidth = Context.getTargetInfo().getLongWidth();
15980 
15981       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15982         BestType = Context.LongTy;
15983       } else {
15984         BestWidth = Context.getTargetInfo().getLongLongWidth();
15985 
15986         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15987           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15988         BestType = Context.LongLongTy;
15989       }
15990     }
15991     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15992   } else {
15993     // If there is no negative value, figure out the smallest type that fits
15994     // all of the enumerator values.
15995     // If it's packed, check also if it fits a char or a short.
15996     if (Packed && NumPositiveBits <= CharWidth) {
15997       BestType = Context.UnsignedCharTy;
15998       BestPromotionType = Context.IntTy;
15999       BestWidth = CharWidth;
16000     } else if (Packed && NumPositiveBits <= ShortWidth) {
16001       BestType = Context.UnsignedShortTy;
16002       BestPromotionType = Context.IntTy;
16003       BestWidth = ShortWidth;
16004     } else if (NumPositiveBits <= IntWidth) {
16005       BestType = Context.UnsignedIntTy;
16006       BestWidth = IntWidth;
16007       BestPromotionType
16008         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16009                            ? Context.UnsignedIntTy : Context.IntTy;
16010     } else if (NumPositiveBits <=
16011                (BestWidth = Context.getTargetInfo().getLongWidth())) {
16012       BestType = Context.UnsignedLongTy;
16013       BestPromotionType
16014         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16015                            ? Context.UnsignedLongTy : Context.LongTy;
16016     } else {
16017       BestWidth = Context.getTargetInfo().getLongLongWidth();
16018       assert(NumPositiveBits <= BestWidth &&
16019              "How could an initializer get larger than ULL?");
16020       BestType = Context.UnsignedLongLongTy;
16021       BestPromotionType
16022         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16023                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
16024     }
16025   }
16026 
16027   // Loop over all of the enumerator constants, changing their types to match
16028   // the type of the enum if needed.
16029   for (auto *D : Elements) {
16030     auto *ECD = cast_or_null<EnumConstantDecl>(D);
16031     if (!ECD) continue;  // Already issued a diagnostic.
16032 
16033     // Standard C says the enumerators have int type, but we allow, as an
16034     // extension, the enumerators to be larger than int size.  If each
16035     // enumerator value fits in an int, type it as an int, otherwise type it the
16036     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16037     // that X has type 'int', not 'unsigned'.
16038 
16039     // Determine whether the value fits into an int.
16040     llvm::APSInt InitVal = ECD->getInitVal();
16041 
16042     // If it fits into an integer type, force it.  Otherwise force it to match
16043     // the enum decl type.
16044     QualType NewTy;
16045     unsigned NewWidth;
16046     bool NewSign;
16047     if (!getLangOpts().CPlusPlus &&
16048         !Enum->isFixed() &&
16049         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16050       NewTy = Context.IntTy;
16051       NewWidth = IntWidth;
16052       NewSign = true;
16053     } else if (ECD->getType() == BestType) {
16054       // Already the right type!
16055       if (getLangOpts().CPlusPlus)
16056         // C++ [dcl.enum]p4: Following the closing brace of an
16057         // enum-specifier, each enumerator has the type of its
16058         // enumeration.
16059         ECD->setType(EnumType);
16060       continue;
16061     } else {
16062       NewTy = BestType;
16063       NewWidth = BestWidth;
16064       NewSign = BestType->isSignedIntegerOrEnumerationType();
16065     }
16066 
16067     // Adjust the APSInt value.
16068     InitVal = InitVal.extOrTrunc(NewWidth);
16069     InitVal.setIsSigned(NewSign);
16070     ECD->setInitVal(InitVal);
16071 
16072     // Adjust the Expr initializer and type.
16073     if (ECD->getInitExpr() &&
16074         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16075       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16076                                                 CK_IntegralCast,
16077                                                 ECD->getInitExpr(),
16078                                                 /*base paths*/ nullptr,
16079                                                 VK_RValue));
16080     if (getLangOpts().CPlusPlus)
16081       // C++ [dcl.enum]p4: Following the closing brace of an
16082       // enum-specifier, each enumerator has the type of its
16083       // enumeration.
16084       ECD->setType(EnumType);
16085     else
16086       ECD->setType(NewTy);
16087   }
16088 
16089   Enum->completeDefinition(BestType, BestPromotionType,
16090                            NumPositiveBits, NumNegativeBits);
16091 
16092   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16093 
16094   if (Enum->isClosedFlag()) {
16095     for (Decl *D : Elements) {
16096       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16097       if (!ECD) continue;  // Already issued a diagnostic.
16098 
16099       llvm::APSInt InitVal = ECD->getInitVal();
16100       if (InitVal != 0 && !InitVal.isPowerOf2() &&
16101           !IsValueInFlagEnum(Enum, InitVal, true))
16102         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16103           << ECD << Enum;
16104     }
16105   }
16106 
16107   // Now that the enum type is defined, ensure it's not been underaligned.
16108   if (Enum->hasAttrs())
16109     CheckAlignasUnderalignment(Enum);
16110 }
16111 
16112 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16113                                   SourceLocation StartLoc,
16114                                   SourceLocation EndLoc) {
16115   StringLiteral *AsmString = cast<StringLiteral>(expr);
16116 
16117   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16118                                                    AsmString, StartLoc,
16119                                                    EndLoc);
16120   CurContext->addDecl(New);
16121   return New;
16122 }
16123 
16124 static void checkModuleImportContext(Sema &S, Module *M,
16125                                      SourceLocation ImportLoc, DeclContext *DC,
16126                                      bool FromInclude = false) {
16127   SourceLocation ExternCLoc;
16128 
16129   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16130     switch (LSD->getLanguage()) {
16131     case LinkageSpecDecl::lang_c:
16132       if (ExternCLoc.isInvalid())
16133         ExternCLoc = LSD->getLocStart();
16134       break;
16135     case LinkageSpecDecl::lang_cxx:
16136       break;
16137     }
16138     DC = LSD->getParent();
16139   }
16140 
16141   while (isa<LinkageSpecDecl>(DC))
16142     DC = DC->getParent();
16143 
16144   if (!isa<TranslationUnitDecl>(DC)) {
16145     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16146                           ? diag::ext_module_import_not_at_top_level_noop
16147                           : diag::err_module_import_not_at_top_level_fatal)
16148         << M->getFullModuleName() << DC;
16149     S.Diag(cast<Decl>(DC)->getLocStart(),
16150            diag::note_module_import_not_at_top_level) << DC;
16151   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16152     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16153       << M->getFullModuleName();
16154     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16155   }
16156 }
16157 
16158 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16159                                            SourceLocation ModuleLoc,
16160                                            ModuleDeclKind MDK,
16161                                            ModuleIdPath Path) {
16162   assert(getLangOpts().ModulesTS &&
16163          "should only have module decl in modules TS");
16164 
16165   // A module implementation unit requires that we are not compiling a module
16166   // of any kind. A module interface unit requires that we are not compiling a
16167   // module map.
16168   switch (getLangOpts().getCompilingModule()) {
16169   case LangOptions::CMK_None:
16170     // It's OK to compile a module interface as a normal translation unit.
16171     break;
16172 
16173   case LangOptions::CMK_ModuleInterface:
16174     if (MDK != ModuleDeclKind::Implementation)
16175       break;
16176 
16177     // We were asked to compile a module interface unit but this is a module
16178     // implementation unit. That indicates the 'export' is missing.
16179     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16180       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16181     MDK = ModuleDeclKind::Interface;
16182     break;
16183 
16184   case LangOptions::CMK_ModuleMap:
16185     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16186     return nullptr;
16187   }
16188 
16189   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16190 
16191   // FIXME: Most of this work should be done by the preprocessor rather than
16192   // here, in order to support macro import.
16193 
16194   // Only one module-declaration is permitted per source file.
16195   if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16196     Diag(ModuleLoc, diag::err_module_redeclaration);
16197     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16198          diag::note_prev_module_declaration);
16199     return nullptr;
16200   }
16201 
16202   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16203   // modules, the dots here are just another character that can appear in a
16204   // module name.
16205   std::string ModuleName;
16206   for (auto &Piece : Path) {
16207     if (!ModuleName.empty())
16208       ModuleName += ".";
16209     ModuleName += Piece.first->getName();
16210   }
16211 
16212   // If a module name was explicitly specified on the command line, it must be
16213   // correct.
16214   if (!getLangOpts().CurrentModule.empty() &&
16215       getLangOpts().CurrentModule != ModuleName) {
16216     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16217         << SourceRange(Path.front().second, Path.back().second)
16218         << getLangOpts().CurrentModule;
16219     return nullptr;
16220   }
16221   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16222 
16223   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16224   Module *Mod;
16225 
16226   switch (MDK) {
16227   case ModuleDeclKind::Interface: {
16228     // We can't have parsed or imported a definition of this module or parsed a
16229     // module map defining it already.
16230     if (auto *M = Map.findModule(ModuleName)) {
16231       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16232       if (M->DefinitionLoc.isValid())
16233         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16234       else if (const auto *FE = M->getASTFile())
16235         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16236             << FE->getName();
16237       Mod = M;
16238       break;
16239     }
16240 
16241     // Create a Module for the module that we're defining.
16242     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16243                                            ModuleScopes.front().Module);
16244     assert(Mod && "module creation should not fail");
16245     break;
16246   }
16247 
16248   case ModuleDeclKind::Partition:
16249     // FIXME: Check we are in a submodule of the named module.
16250     return nullptr;
16251 
16252   case ModuleDeclKind::Implementation:
16253     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16254         PP.getIdentifierInfo(ModuleName), Path[0].second);
16255     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16256                                        /*IsIncludeDirective=*/false);
16257     if (!Mod) {
16258       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16259       // Create an empty module interface unit for error recovery.
16260       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16261                                              ModuleScopes.front().Module);
16262     }
16263     break;
16264   }
16265 
16266   // Switch from the global module to the named module.
16267   ModuleScopes.back().Module = Mod;
16268   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16269   VisibleModules.setVisible(Mod, ModuleLoc);
16270 
16271   // From now on, we have an owning module for all declarations we see.
16272   // However, those declarations are module-private unless explicitly
16273   // exported.
16274   auto *TU = Context.getTranslationUnitDecl();
16275   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16276   TU->setLocalOwningModule(Mod);
16277 
16278   // FIXME: Create a ModuleDecl.
16279   return nullptr;
16280 }
16281 
16282 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16283                                    SourceLocation ImportLoc,
16284                                    ModuleIdPath Path) {
16285   Module *Mod =
16286       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16287                                    /*IsIncludeDirective=*/false);
16288   if (!Mod)
16289     return true;
16290 
16291   VisibleModules.setVisible(Mod, ImportLoc);
16292 
16293   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16294 
16295   // FIXME: we should support importing a submodule within a different submodule
16296   // of the same top-level module. Until we do, make it an error rather than
16297   // silently ignoring the import.
16298   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16299   // warn on a redundant import of the current module?
16300   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16301       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16302     Diag(ImportLoc, getLangOpts().isCompilingModule()
16303                         ? diag::err_module_self_import
16304                         : diag::err_module_import_in_implementation)
16305         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16306 
16307   SmallVector<SourceLocation, 2> IdentifierLocs;
16308   Module *ModCheck = Mod;
16309   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16310     // If we've run out of module parents, just drop the remaining identifiers.
16311     // We need the length to be consistent.
16312     if (!ModCheck)
16313       break;
16314     ModCheck = ModCheck->Parent;
16315 
16316     IdentifierLocs.push_back(Path[I].second);
16317   }
16318 
16319   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16320   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16321                                           Mod, IdentifierLocs);
16322   if (!ModuleScopes.empty())
16323     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16324   TU->addDecl(Import);
16325   return Import;
16326 }
16327 
16328 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16329   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16330   BuildModuleInclude(DirectiveLoc, Mod);
16331 }
16332 
16333 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16334   // Determine whether we're in the #include buffer for a module. The #includes
16335   // in that buffer do not qualify as module imports; they're just an
16336   // implementation detail of us building the module.
16337   //
16338   // FIXME: Should we even get ActOnModuleInclude calls for those?
16339   bool IsInModuleIncludes =
16340       TUKind == TU_Module &&
16341       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16342 
16343   bool ShouldAddImport = !IsInModuleIncludes;
16344 
16345   // If this module import was due to an inclusion directive, create an
16346   // implicit import declaration to capture it in the AST.
16347   if (ShouldAddImport) {
16348     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16349     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16350                                                      DirectiveLoc, Mod,
16351                                                      DirectiveLoc);
16352     if (!ModuleScopes.empty())
16353       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16354     TU->addDecl(ImportD);
16355     Consumer.HandleImplicitImportDecl(ImportD);
16356   }
16357 
16358   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16359   VisibleModules.setVisible(Mod, DirectiveLoc);
16360 }
16361 
16362 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16363   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16364 
16365   ModuleScopes.push_back({});
16366   ModuleScopes.back().Module = Mod;
16367   if (getLangOpts().ModulesLocalVisibility)
16368     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16369 
16370   VisibleModules.setVisible(Mod, DirectiveLoc);
16371 
16372   // The enclosing context is now part of this module.
16373   // FIXME: Consider creating a child DeclContext to hold the entities
16374   // lexically within the module.
16375   if (getLangOpts().trackLocalOwningModule()) {
16376     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16377       cast<Decl>(DC)->setModuleOwnershipKind(
16378           getLangOpts().ModulesLocalVisibility
16379               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16380               : Decl::ModuleOwnershipKind::Visible);
16381       cast<Decl>(DC)->setLocalOwningModule(Mod);
16382     }
16383   }
16384 }
16385 
16386 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16387   if (getLangOpts().ModulesLocalVisibility) {
16388     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16389     // Leaving a module hides namespace names, so our visible namespace cache
16390     // is now out of date.
16391     VisibleNamespaceCache.clear();
16392   }
16393 
16394   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16395          "left the wrong module scope");
16396   ModuleScopes.pop_back();
16397 
16398   // We got to the end of processing a local module. Create an
16399   // ImportDecl as we would for an imported module.
16400   FileID File = getSourceManager().getFileID(EomLoc);
16401   SourceLocation DirectiveLoc;
16402   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16403     // We reached the end of a #included module header. Use the #include loc.
16404     assert(File != getSourceManager().getMainFileID() &&
16405            "end of submodule in main source file");
16406     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16407   } else {
16408     // We reached an EOM pragma. Use the pragma location.
16409     DirectiveLoc = EomLoc;
16410   }
16411   BuildModuleInclude(DirectiveLoc, Mod);
16412 
16413   // Any further declarations are in whatever module we returned to.
16414   if (getLangOpts().trackLocalOwningModule()) {
16415     // The parser guarantees that this is the same context that we entered
16416     // the module within.
16417     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16418       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16419       if (!getCurrentModule())
16420         cast<Decl>(DC)->setModuleOwnershipKind(
16421             Decl::ModuleOwnershipKind::Unowned);
16422     }
16423   }
16424 }
16425 
16426 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16427                                                       Module *Mod) {
16428   // Bail if we're not allowed to implicitly import a module here.
16429   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16430       VisibleModules.isVisible(Mod))
16431     return;
16432 
16433   // Create the implicit import declaration.
16434   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16435   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16436                                                    Loc, Mod, Loc);
16437   TU->addDecl(ImportD);
16438   Consumer.HandleImplicitImportDecl(ImportD);
16439 
16440   // Make the module visible.
16441   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16442   VisibleModules.setVisible(Mod, Loc);
16443 }
16444 
16445 /// We have parsed the start of an export declaration, including the '{'
16446 /// (if present).
16447 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16448                                  SourceLocation LBraceLoc) {
16449   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16450 
16451   // C++ Modules TS draft:
16452   //   An export-declaration shall appear in the purview of a module other than
16453   //   the global module.
16454   if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16455     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16456 
16457   //   An export-declaration [...] shall not contain more than one
16458   //   export keyword.
16459   //
16460   // The intent here is that an export-declaration cannot appear within another
16461   // export-declaration.
16462   if (D->isExported())
16463     Diag(ExportLoc, diag::err_export_within_export);
16464 
16465   CurContext->addDecl(D);
16466   PushDeclContext(S, D);
16467   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16468   return D;
16469 }
16470 
16471 /// Complete the definition of an export declaration.
16472 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16473   auto *ED = cast<ExportDecl>(D);
16474   if (RBraceLoc.isValid())
16475     ED->setRBraceLoc(RBraceLoc);
16476 
16477   // FIXME: Diagnose export of internal-linkage declaration (including
16478   // anonymous namespace).
16479 
16480   PopDeclContext();
16481   return D;
16482 }
16483 
16484 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16485                                       IdentifierInfo* AliasName,
16486                                       SourceLocation PragmaLoc,
16487                                       SourceLocation NameLoc,
16488                                       SourceLocation AliasNameLoc) {
16489   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16490                                          LookupOrdinaryName);
16491   AsmLabelAttr *Attr =
16492       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16493 
16494   // If a declaration that:
16495   // 1) declares a function or a variable
16496   // 2) has external linkage
16497   // already exists, add a label attribute to it.
16498   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16499     if (isDeclExternC(PrevDecl))
16500       PrevDecl->addAttr(Attr);
16501     else
16502       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16503           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16504   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16505   } else
16506     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16507 }
16508 
16509 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16510                              SourceLocation PragmaLoc,
16511                              SourceLocation NameLoc) {
16512   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16513 
16514   if (PrevDecl) {
16515     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16516   } else {
16517     (void)WeakUndeclaredIdentifiers.insert(
16518       std::pair<IdentifierInfo*,WeakInfo>
16519         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16520   }
16521 }
16522 
16523 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16524                                 IdentifierInfo* AliasName,
16525                                 SourceLocation PragmaLoc,
16526                                 SourceLocation NameLoc,
16527                                 SourceLocation AliasNameLoc) {
16528   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16529                                     LookupOrdinaryName);
16530   WeakInfo W = WeakInfo(Name, NameLoc);
16531 
16532   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16533     if (!PrevDecl->hasAttr<AliasAttr>())
16534       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16535         DeclApplyPragmaWeak(TUScope, ND, W);
16536   } else {
16537     (void)WeakUndeclaredIdentifiers.insert(
16538       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16539   }
16540 }
16541 
16542 Decl *Sema::getObjCDeclContext() const {
16543   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16544 }
16545