1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67    TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68                         bool AllowTemplates = false,
69                         bool AllowNonTemplates = true)
70        : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71          AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72      WantExpressionKeywords = false;
73      WantCXXNamedCasts = false;
74      WantRemainingKeywords = false;
75   }
76 
77   bool ValidateCandidate(const TypoCorrection &candidate) override {
78     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79       if (!AllowInvalidDecl && ND->isInvalidDecl())
80         return false;
81 
82       if (getAsTypeTemplateDecl(ND))
83         return AllowTemplates;
84 
85       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86       if (!IsType)
87         return false;
88 
89       if (AllowNonTemplates)
90         return true;
91 
92       // An injected-class-name of a class template (specialization) is valid
93       // as a template or as a non-template.
94       if (AllowTemplates) {
95         auto *RD = dyn_cast<CXXRecordDecl>(ND);
96         if (!RD || !RD->isInjectedClassName())
97           return false;
98         RD = cast<CXXRecordDecl>(RD->getDeclContext());
99         return RD->getDescribedClassTemplate() ||
100                isa<ClassTemplateSpecializationDecl>(RD);
101       }
102 
103       return false;
104     }
105 
106     return !WantClassName && candidate.isKeyword();
107   }
108 
109  private:
110   bool AllowInvalidDecl;
111   bool WantClassName;
112   bool AllowTemplates;
113   bool AllowNonTemplates;
114 };
115 
116 } // end anonymous namespace
117 
118 /// \brief Determine whether the token kind starts a simple-type-specifier.
119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120   switch (Kind) {
121   // FIXME: Take into account the current language when deciding whether a
122   // token kind is a valid type specifier
123   case tok::kw_short:
124   case tok::kw_long:
125   case tok::kw___int64:
126   case tok::kw___int128:
127   case tok::kw_signed:
128   case tok::kw_unsigned:
129   case tok::kw_void:
130   case tok::kw_char:
131   case tok::kw_int:
132   case tok::kw_half:
133   case tok::kw_float:
134   case tok::kw_double:
135   case tok::kw__Float16:
136   case tok::kw___float128:
137   case tok::kw_wchar_t:
138   case tok::kw_bool:
139   case tok::kw___underlying_type:
140   case tok::kw___auto_type:
141     return true;
142 
143   case tok::annot_typename:
144   case tok::kw_char16_t:
145   case tok::kw_char32_t:
146   case tok::kw_typeof:
147   case tok::annot_decltype:
148   case tok::kw_decltype:
149     return getLangOpts().CPlusPlus;
150 
151   default:
152     break;
153   }
154 
155   return false;
156 }
157 
158 namespace {
159 enum class UnqualifiedTypeNameLookupResult {
160   NotFound,
161   FoundNonType,
162   FoundType
163 };
164 } // end anonymous namespace
165 
166 /// \brief Tries to perform unqualified lookup of the type decls in bases for
167 /// dependent class.
168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169 /// type decl, \a FoundType if only type decls are found.
170 static UnqualifiedTypeNameLookupResult
171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
172                                 SourceLocation NameLoc,
173                                 const CXXRecordDecl *RD) {
174   if (!RD->hasDefinition())
175     return UnqualifiedTypeNameLookupResult::NotFound;
176   // Look for type decls in base classes.
177   UnqualifiedTypeNameLookupResult FoundTypeDecl =
178       UnqualifiedTypeNameLookupResult::NotFound;
179   for (const auto &Base : RD->bases()) {
180     const CXXRecordDecl *BaseRD = nullptr;
181     if (auto *BaseTT = Base.getType()->getAs<TagType>())
182       BaseRD = BaseTT->getAsCXXRecordDecl();
183     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184       // Look for type decls in dependent base classes that have known primary
185       // templates.
186       if (!TST || !TST->isDependentType())
187         continue;
188       auto *TD = TST->getTemplateName().getAsTemplateDecl();
189       if (!TD)
190         continue;
191       if (auto *BasePrimaryTemplate =
192           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194           BaseRD = BasePrimaryTemplate;
195         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
196           if (const ClassTemplatePartialSpecializationDecl *PS =
197                   CTD->findPartialSpecialization(Base.getType()))
198             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199               BaseRD = PS;
200         }
201       }
202     }
203     if (BaseRD) {
204       for (NamedDecl *ND : BaseRD->lookup(&II)) {
205         if (!isa<TypeDecl>(ND))
206           return UnqualifiedTypeNameLookupResult::FoundNonType;
207         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208       }
209       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211         case UnqualifiedTypeNameLookupResult::FoundNonType:
212           return UnqualifiedTypeNameLookupResult::FoundNonType;
213         case UnqualifiedTypeNameLookupResult::FoundType:
214           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215           break;
216         case UnqualifiedTypeNameLookupResult::NotFound:
217           break;
218         }
219       }
220     }
221   }
222 
223   return FoundTypeDecl;
224 }
225 
226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
227                                                       const IdentifierInfo &II,
228                                                       SourceLocation NameLoc) {
229   // Lookup in the parent class template context, if any.
230   const CXXRecordDecl *RD = nullptr;
231   UnqualifiedTypeNameLookupResult FoundTypeDecl =
232       UnqualifiedTypeNameLookupResult::NotFound;
233   for (DeclContext *DC = S.CurContext;
234        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235        DC = DC->getParent()) {
236     // Look for type decls in dependent base classes that have known primary
237     // templates.
238     RD = dyn_cast<CXXRecordDecl>(DC);
239     if (RD && RD->getDescribedClassTemplate())
240       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241   }
242   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243     return nullptr;
244 
245   // We found some types in dependent base classes.  Recover as if the user
246   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
247   // lookup during template instantiation.
248   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249 
250   ASTContext &Context = S.Context;
251   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252                                           cast<Type>(Context.getRecordType(RD)));
253   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254 
255   CXXScopeSpec SS;
256   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257 
258   TypeLocBuilder Builder;
259   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
260   DepTL.setNameLoc(NameLoc);
261   DepTL.setElaboratedKeywordLoc(SourceLocation());
262   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264 }
265 
266 /// \brief If the identifier refers to a type name within this scope,
267 /// return the declaration of that type.
268 ///
269 /// This routine performs ordinary name lookup of the identifier II
270 /// within the given scope, with optional C++ scope specifier SS, to
271 /// determine whether the name refers to a type. If so, returns an
272 /// opaque pointer (actually a QualType) corresponding to that
273 /// type. Otherwise, returns NULL.
274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275                              Scope *S, CXXScopeSpec *SS,
276                              bool isClassName, bool HasTrailingDot,
277                              ParsedType ObjectTypePtr,
278                              bool IsCtorOrDtorName,
279                              bool WantNontrivialTypeSourceInfo,
280                              bool IsClassTemplateDeductionContext,
281                              IdentifierInfo **CorrectedII) {
282   // FIXME: Consider allowing this outside C++1z mode as an extension.
283   bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284                               getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
285                               !isClassName && !HasTrailingDot;
286 
287   // Determine where we will perform name lookup.
288   DeclContext *LookupCtx = nullptr;
289   if (ObjectTypePtr) {
290     QualType ObjectType = ObjectTypePtr.get();
291     if (ObjectType->isRecordType())
292       LookupCtx = computeDeclContext(ObjectType);
293   } else if (SS && SS->isNotEmpty()) {
294     LookupCtx = computeDeclContext(*SS, false);
295 
296     if (!LookupCtx) {
297       if (isDependentScopeSpecifier(*SS)) {
298         // C++ [temp.res]p3:
299         //   A qualified-id that refers to a type and in which the
300         //   nested-name-specifier depends on a template-parameter (14.6.2)
301         //   shall be prefixed by the keyword typename to indicate that the
302         //   qualified-id denotes a type, forming an
303         //   elaborated-type-specifier (7.1.5.3).
304         //
305         // We therefore do not perform any name lookup if the result would
306         // refer to a member of an unknown specialization.
307         if (!isClassName && !IsCtorOrDtorName)
308           return nullptr;
309 
310         // We know from the grammar that this name refers to a type,
311         // so build a dependent node to describe the type.
312         if (WantNontrivialTypeSourceInfo)
313           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314 
315         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317                                        II, NameLoc);
318         return ParsedType::make(T);
319       }
320 
321       return nullptr;
322     }
323 
324     if (!LookupCtx->isDependentContext() &&
325         RequireCompleteDeclContext(*SS, LookupCtx))
326       return nullptr;
327   }
328 
329   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330   // lookup for class-names.
331   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332                                       LookupOrdinaryName;
333   LookupResult Result(*this, &II, NameLoc, Kind);
334   if (LookupCtx) {
335     // Perform "qualified" name lookup into the declaration context we
336     // computed, which is either the type of the base of a member access
337     // expression or the declaration context associated with a prior
338     // nested-name-specifier.
339     LookupQualifiedName(Result, LookupCtx);
340 
341     if (ObjectTypePtr && Result.empty()) {
342       // C++ [basic.lookup.classref]p3:
343       //   If the unqualified-id is ~type-name, the type-name is looked up
344       //   in the context of the entire postfix-expression. If the type T of
345       //   the object expression is of a class type C, the type-name is also
346       //   looked up in the scope of class C. At least one of the lookups shall
347       //   find a name that refers to (possibly cv-qualified) T.
348       LookupName(Result, S);
349     }
350   } else {
351     // Perform unqualified name lookup.
352     LookupName(Result, S);
353 
354     // For unqualified lookup in a class template in MSVC mode, look into
355     // dependent base classes where the primary class template is known.
356     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357       if (ParsedType TypeInBase =
358               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359         return TypeInBase;
360     }
361   }
362 
363   NamedDecl *IIDecl = nullptr;
364   switch (Result.getResultKind()) {
365   case LookupResult::NotFound:
366   case LookupResult::NotFoundInCurrentInstantiation:
367     if (CorrectedII) {
368       TypoCorrection Correction =
369           CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370                       llvm::make_unique<TypeNameValidatorCCC>(
371                           true, isClassName, AllowDeducedTemplate),
372                       CTK_ErrorRecovery);
373       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374       TemplateTy Template;
375       bool MemberOfUnknownSpecialization;
376       UnqualifiedId TemplateName;
377       TemplateName.setIdentifier(NewII, NameLoc);
378       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379       CXXScopeSpec NewSS, *NewSSPtr = SS;
380       if (SS && NNS) {
381         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382         NewSSPtr = &NewSS;
383       }
384       if (Correction && (NNS || NewII != &II) &&
385           // Ignore a correction to a template type as the to-be-corrected
386           // identifier is not a template (typo correction for template names
387           // is handled elsewhere).
388           !(getLangOpts().CPlusPlus && NewSSPtr &&
389             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390                            Template, MemberOfUnknownSpecialization))) {
391         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392                                     isClassName, HasTrailingDot, ObjectTypePtr,
393                                     IsCtorOrDtorName,
394                                     WantNontrivialTypeSourceInfo,
395                                     IsClassTemplateDeductionContext);
396         if (Ty) {
397           diagnoseTypo(Correction,
398                        PDiag(diag::err_unknown_type_or_class_name_suggest)
399                          << Result.getLookupName() << isClassName);
400           if (SS && NNS)
401             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402           *CorrectedII = NewII;
403           return Ty;
404         }
405       }
406     }
407     // If typo correction failed or was not performed, fall through
408     LLVM_FALLTHROUGH;
409   case LookupResult::FoundOverloaded:
410   case LookupResult::FoundUnresolvedValue:
411     Result.suppressDiagnostics();
412     return nullptr;
413 
414   case LookupResult::Ambiguous:
415     // Recover from type-hiding ambiguities by hiding the type.  We'll
416     // do the lookup again when looking for an object, and we can
417     // diagnose the error then.  If we don't do this, then the error
418     // about hiding the type will be immediately followed by an error
419     // that only makes sense if the identifier was treated like a type.
420     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
421       Result.suppressDiagnostics();
422       return nullptr;
423     }
424 
425     // Look to see if we have a type anywhere in the list of results.
426     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427          Res != ResEnd; ++Res) {
428       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429           (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430         if (!IIDecl ||
431             (*Res)->getLocation().getRawEncoding() <
432               IIDecl->getLocation().getRawEncoding())
433           IIDecl = *Res;
434       }
435     }
436 
437     if (!IIDecl) {
438       // None of the entities we found is a type, so there is no way
439       // to even assume that the result is a type. In this case, don't
440       // complain about the ambiguity. The parser will either try to
441       // perform this lookup again (e.g., as an object name), which
442       // will produce the ambiguity, or will complain that it expected
443       // a type name.
444       Result.suppressDiagnostics();
445       return nullptr;
446     }
447 
448     // We found a type within the ambiguous lookup; diagnose the
449     // ambiguity and then return that type. This might be the right
450     // answer, or it might not be, but it suppresses any attempt to
451     // perform the name lookup again.
452     break;
453 
454   case LookupResult::Found:
455     IIDecl = Result.getFoundDecl();
456     break;
457   }
458 
459   assert(IIDecl && "Didn't find decl");
460 
461   QualType T;
462   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463     // C++ [class.qual]p2: A lookup that would find the injected-class-name
464     // instead names the constructors of the class, except when naming a class.
465     // This is ill-formed when we're not actually forming a ctor or dtor name.
466     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469         FoundRD->isInjectedClassName() &&
470         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472           << &II << /*Type*/1;
473 
474     DiagnoseUseOfDecl(IIDecl, NameLoc);
475 
476     T = Context.getTypeDeclType(TD);
477     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480     if (!HasTrailingDot)
481       T = Context.getObjCInterfaceType(IDecl);
482   } else if (AllowDeducedTemplate) {
483     if (auto *TD = getAsTypeTemplateDecl(IIDecl))
484       T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
485                                                        QualType(), false);
486   }
487 
488   if (T.isNull()) {
489     // If it's not plausibly a type, suppress diagnostics.
490     Result.suppressDiagnostics();
491     return nullptr;
492   }
493 
494   // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495   // constructor or destructor name (in such a case, the scope specifier
496   // will be attached to the enclosing Expr or Decl node).
497   if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498       !isa<ObjCInterfaceDecl>(IIDecl)) {
499     if (WantNontrivialTypeSourceInfo) {
500       // Construct a type with type-source information.
501       TypeLocBuilder Builder;
502       Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503 
504       T = getElaboratedType(ETK_None, *SS, T);
505       ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
506       ElabTL.setElaboratedKeywordLoc(SourceLocation());
507       ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508       return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509     } else {
510       T = getElaboratedType(ETK_None, *SS, T);
511     }
512   }
513 
514   return ParsedType::make(T);
515 }
516 
517 // Builds a fake NNS for the given decl context.
518 static NestedNameSpecifier *
519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
520   for (;; DC = DC->getLookupParent()) {
521     DC = DC->getPrimaryContext();
522     auto *ND = dyn_cast<NamespaceDecl>(DC);
523     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524       return NestedNameSpecifier::Create(Context, nullptr, ND);
525     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527                                          RD->getTypeForDecl());
528     else if (isa<TranslationUnitDecl>(DC))
529       return NestedNameSpecifier::GlobalSpecifier(Context);
530   }
531   llvm_unreachable("something isn't in TU scope?");
532 }
533 
534 /// Find the parent class with dependent bases of the innermost enclosing method
535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536 /// up allowing unqualified dependent type names at class-level, which MSVC
537 /// correctly rejects.
538 static const CXXRecordDecl *
539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
540   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541     DC = DC->getPrimaryContext();
542     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543       if (MD->getParent()->hasAnyDependentBases())
544         return MD->getParent();
545   }
546   return nullptr;
547 }
548 
549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
550                                           SourceLocation NameLoc,
551                                           bool IsTemplateTypeArg) {
552   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
553 
554   NestedNameSpecifier *NNS = nullptr;
555   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556     // If we weren't able to parse a default template argument, delay lookup
557     // until instantiation time by making a non-dependent DependentTypeName. We
558     // pretend we saw a NestedNameSpecifier referring to the current scope, and
559     // lookup is retried.
560     // FIXME: This hurts our diagnostic quality, since we get errors like "no
561     // type named 'Foo' in 'current_namespace'" when the user didn't write any
562     // name specifiers.
563     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565   } else if (const CXXRecordDecl *RD =
566                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
567     // Build a DependentNameType that will perform lookup into RD at
568     // instantiation time.
569     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570                                       RD->getTypeForDecl());
571 
572     // Diagnose that this identifier was undeclared, and retry the lookup during
573     // template instantiation.
574     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575                                                                       << RD;
576   } else {
577     // This is not a situation that we should recover from.
578     return ParsedType();
579   }
580 
581   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582 
583   // Build type location information.  We synthesized the qualifier, so we have
584   // to build a fake NestedNameSpecifierLoc.
585   NestedNameSpecifierLocBuilder NNSLocBuilder;
586   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588 
589   TypeLocBuilder Builder;
590   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
591   DepTL.setNameLoc(NameLoc);
592   DepTL.setElaboratedKeywordLoc(SourceLocation());
593   DepTL.setQualifierLoc(QualifierLoc);
594   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595 }
596 
597 /// isTagName() - This method is called *for error recovery purposes only*
598 /// to determine if the specified name is a valid tag name ("struct foo").  If
599 /// so, this returns the TST for the tag corresponding to it (TST_enum,
600 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
601 /// cases in C where the user forgot to specify the tag.
602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
603   // Do a tag name lookup in this scope.
604   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605   LookupName(R, S, false);
606   R.suppressDiagnostics();
607   if (R.getResultKind() == LookupResult::Found)
608     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609       switch (TD->getTagKind()) {
610       case TTK_Struct: return DeclSpec::TST_struct;
611       case TTK_Interface: return DeclSpec::TST_interface;
612       case TTK_Union:  return DeclSpec::TST_union;
613       case TTK_Class:  return DeclSpec::TST_class;
614       case TTK_Enum:   return DeclSpec::TST_enum;
615       }
616     }
617 
618   return DeclSpec::TST_unspecified;
619 }
620 
621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
623 /// then downgrade the missing typename error to a warning.
624 /// This is needed for MSVC compatibility; Example:
625 /// @code
626 /// template<class T> class A {
627 /// public:
628 ///   typedef int TYPE;
629 /// };
630 /// template<class T> class B : public A<T> {
631 /// public:
632 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
633 /// };
634 /// @endcode
635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
636   if (CurContext->isRecord()) {
637     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638       return true;
639 
640     const Type *Ty = SS->getScopeRep()->getAsType();
641 
642     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643     for (const auto &Base : RD->bases())
644       if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645         return true;
646     return S->isFunctionPrototypeScope();
647   }
648   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649 }
650 
651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
652                                    SourceLocation IILoc,
653                                    Scope *S,
654                                    CXXScopeSpec *SS,
655                                    ParsedType &SuggestedType,
656                                    bool IsTemplateName) {
657   // Don't report typename errors for editor placeholders.
658   if (II->isEditorPlaceholder())
659     return;
660   // We don't have anything to suggest (yet).
661   SuggestedType = nullptr;
662 
663   // There may have been a typo in the name of the type. Look up typo
664   // results, in case we have something that we can suggest.
665   if (TypoCorrection Corrected =
666           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667                       llvm::make_unique<TypeNameValidatorCCC>(
668                           false, false, IsTemplateName, !IsTemplateName),
669                       CTK_ErrorRecovery)) {
670     // FIXME: Support error recovery for the template-name case.
671     bool CanRecover = !IsTemplateName;
672     if (Corrected.isKeyword()) {
673       // We corrected to a keyword.
674       diagnoseTypo(Corrected,
675                    PDiag(IsTemplateName ? diag::err_no_template_suggest
676                                         : diag::err_unknown_typename_suggest)
677                        << II);
678       II = Corrected.getCorrectionAsIdentifierInfo();
679     } else {
680       // We found a similarly-named type or interface; suggest that.
681       if (!SS || !SS->isSet()) {
682         diagnoseTypo(Corrected,
683                      PDiag(IsTemplateName ? diag::err_no_template_suggest
684                                           : diag::err_unknown_typename_suggest)
685                          << II, CanRecover);
686       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689                                 II->getName().equals(CorrectedStr);
690         diagnoseTypo(Corrected,
691                      PDiag(IsTemplateName
692                                ? diag::err_no_member_template_suggest
693                                : diag::err_unknown_nested_typename_suggest)
694                          << II << DC << DroppedSpecifier << SS->getRange(),
695                      CanRecover);
696       } else {
697         llvm_unreachable("could not have corrected a typo here");
698       }
699 
700       if (!CanRecover)
701         return;
702 
703       CXXScopeSpec tmpSS;
704       if (Corrected.getCorrectionSpecifier())
705         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706                           SourceRange(IILoc));
707       // FIXME: Support class template argument deduction here.
708       SuggestedType =
709           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711                       /*IsCtorOrDtorName=*/false,
712                       /*NonTrivialTypeSourceInfo=*/true);
713     }
714     return;
715   }
716 
717   if (getLangOpts().CPlusPlus && !IsTemplateName) {
718     // See if II is a class template that the user forgot to pass arguments to.
719     UnqualifiedId Name;
720     Name.setIdentifier(II, IILoc);
721     CXXScopeSpec EmptySS;
722     TemplateTy TemplateResult;
723     bool MemberOfUnknownSpecialization;
724     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725                        Name, nullptr, true, TemplateResult,
726                        MemberOfUnknownSpecialization) == TNK_Type_template) {
727       TemplateName TplName = TemplateResult.get();
728       Diag(IILoc, diag::err_template_missing_args)
729         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732           << TplDecl->getTemplateParameters()->getSourceRange();
733       }
734       return;
735     }
736   }
737 
738   // FIXME: Should we move the logic that tries to recover from a missing tag
739   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740 
741   if (!SS || (!SS->isSet() && !SS->isInvalid()))
742     Diag(IILoc, IsTemplateName ? diag::err_no_template
743                                : diag::err_unknown_typename)
744         << II;
745   else if (DeclContext *DC = computeDeclContext(*SS, false))
746     Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747                                : diag::err_typename_nested_not_found)
748         << II << DC << SS->getRange();
749   else if (isDependentScopeSpecifier(*SS)) {
750     unsigned DiagID = diag::err_typename_missing;
751     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752       DiagID = diag::ext_typename_missing;
753 
754     Diag(SS->getRange().getBegin(), DiagID)
755       << SS->getScopeRep() << II->getName()
756       << SourceRange(SS->getRange().getBegin(), IILoc)
757       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758     SuggestedType = ActOnTypenameType(S, SourceLocation(),
759                                       *SS, *II, IILoc).get();
760   } else {
761     assert(SS && SS->isInvalid() &&
762            "Invalid scope specifier has already been diagnosed");
763   }
764 }
765 
766 /// \brief Determine whether the given result set contains either a type name
767 /// or
768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770                        NextToken.is(tok::less);
771 
772   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774       return true;
775 
776     if (CheckTemplate && isa<TemplateDecl>(*I))
777       return true;
778   }
779 
780   return false;
781 }
782 
783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784                                     Scope *S, CXXScopeSpec &SS,
785                                     IdentifierInfo *&Name,
786                                     SourceLocation NameLoc) {
787   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788   SemaRef.LookupParsedName(R, S, &SS);
789   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790     StringRef FixItTagName;
791     switch (Tag->getTagKind()) {
792       case TTK_Class:
793         FixItTagName = "class ";
794         break;
795 
796       case TTK_Enum:
797         FixItTagName = "enum ";
798         break;
799 
800       case TTK_Struct:
801         FixItTagName = "struct ";
802         break;
803 
804       case TTK_Interface:
805         FixItTagName = "__interface ";
806         break;
807 
808       case TTK_Union:
809         FixItTagName = "union ";
810         break;
811     }
812 
813     StringRef TagName = FixItTagName.drop_back();
814     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817 
818     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819          I != IEnd; ++I)
820       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821         << Name << TagName;
822 
823     // Replace lookup results with just the tag decl.
824     Result.clear(Sema::LookupTagName);
825     SemaRef.LookupParsedName(Result, S, &SS);
826     return true;
827   }
828 
829   return false;
830 }
831 
832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834                                   QualType T, SourceLocation NameLoc) {
835   ASTContext &Context = S.Context;
836 
837   TypeLocBuilder Builder;
838   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839 
840   T = S.getElaboratedType(ETK_None, SS, T);
841   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842   ElabTL.setElaboratedKeywordLoc(SourceLocation());
843   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845 }
846 
847 Sema::NameClassification
848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849                    SourceLocation NameLoc, const Token &NextToken,
850                    bool IsAddressOfOperand,
851                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
852   DeclarationNameInfo NameInfo(Name, NameLoc);
853   ObjCMethodDecl *CurMethod = getCurMethodDecl();
854 
855   if (NextToken.is(tok::coloncolon)) {
856     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859              isCurrentClassName(*Name, S, &SS)) {
860     // Per [class.qual]p2, this names the constructors of SS, not the
861     // injected-class-name. We don't have a classification for that.
862     // There's not much point caching this result, since the parser
863     // will reject it later.
864     return NameClassification::Unknown();
865   }
866 
867   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868   LookupParsedName(Result, S, &SS, !CurMethod);
869 
870   // For unqualified lookup in a class template in MSVC mode, look into
871   // dependent base classes where the primary class template is known.
872   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873     if (ParsedType TypeInBase =
874             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875       return TypeInBase;
876   }
877 
878   // Perform lookup for Objective-C instance variables (including automatically
879   // synthesized instance variables), if we're in an Objective-C method.
880   // FIXME: This lookup really, really needs to be folded in to the normal
881   // unqualified lookup mechanism.
882   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884     if (E.get() || E.isInvalid())
885       return E;
886   }
887 
888   bool SecondTry = false;
889   bool IsFilteredTemplateName = false;
890 
891 Corrected:
892   switch (Result.getResultKind()) {
893   case LookupResult::NotFound:
894     // If an unqualified-id is followed by a '(', then we have a function
895     // call.
896     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897       // In C++, this is an ADL-only call.
898       // FIXME: Reference?
899       if (getLangOpts().CPlusPlus)
900         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901 
902       // C90 6.3.2.2:
903       //   If the expression that precedes the parenthesized argument list in a
904       //   function call consists solely of an identifier, and if no
905       //   declaration is visible for this identifier, the identifier is
906       //   implicitly declared exactly as if, in the innermost block containing
907       //   the function call, the declaration
908       //
909       //     extern int identifier ();
910       //
911       //   appeared.
912       //
913       // We also allow this in C99 as an extension.
914       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915         Result.addDecl(D);
916         Result.resolveKind();
917         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918       }
919     }
920 
921     // In C, we first see whether there is a tag type by the same name, in
922     // which case it's likely that the user just forgot to write "enum",
923     // "struct", or "union".
924     if (!getLangOpts().CPlusPlus && !SecondTry &&
925         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926       break;
927     }
928 
929     // Perform typo correction to determine if there is another name that is
930     // close to this name.
931     if (!SecondTry && CCC) {
932       SecondTry = true;
933       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934                                                  Result.getLookupKind(), S,
935                                                  &SS, std::move(CCC),
936                                                  CTK_ErrorRecovery)) {
937         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938         unsigned QualifiedDiag = diag::err_no_member_suggest;
939 
940         NamedDecl *FirstDecl = Corrected.getFoundDecl();
941         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944           UnqualifiedDiag = diag::err_no_template_suggest;
945           QualifiedDiag = diag::err_no_member_template_suggest;
946         } else if (UnderlyingFirstDecl &&
947                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
948                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950           UnqualifiedDiag = diag::err_unknown_typename_suggest;
951           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952         }
953 
954         if (SS.isEmpty()) {
955           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956         } else {// FIXME: is this even reachable? Test it.
957           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959                                   Name->getName().equals(CorrectedStr);
960           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961                                     << Name << computeDeclContext(SS, false)
962                                     << DroppedSpecifier << SS.getRange());
963         }
964 
965         // Update the name, so that the caller has the new name.
966         Name = Corrected.getCorrectionAsIdentifierInfo();
967 
968         // Typo correction corrected to a keyword.
969         if (Corrected.isKeyword())
970           return Name;
971 
972         // Also update the LookupResult...
973         // FIXME: This should probably go away at some point
974         Result.clear();
975         Result.setLookupName(Corrected.getCorrection());
976         if (FirstDecl)
977           Result.addDecl(FirstDecl);
978 
979         // If we found an Objective-C instance variable, let
980         // LookupInObjCMethod build the appropriate expression to
981         // reference the ivar.
982         // FIXME: This is a gross hack.
983         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984           Result.clear();
985           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986           return E;
987         }
988 
989         goto Corrected;
990       }
991     }
992 
993     // We failed to correct; just fall through and let the parser deal with it.
994     Result.suppressDiagnostics();
995     return NameClassification::Unknown();
996 
997   case LookupResult::NotFoundInCurrentInstantiation: {
998     // We performed name lookup into the current instantiation, and there were
999     // dependent bases, so we treat this result the same way as any other
1000     // dependent nested-name-specifier.
1001 
1002     // C++ [temp.res]p2:
1003     //   A name used in a template declaration or definition and that is
1004     //   dependent on a template-parameter is assumed not to name a type
1005     //   unless the applicable name lookup finds a type name or the name is
1006     //   qualified by the keyword typename.
1007     //
1008     // FIXME: If the next token is '<', we might want to ask the parser to
1009     // perform some heroics to see if we actually have a
1010     // template-argument-list, which would indicate a missing 'template'
1011     // keyword here.
1012     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013                                       NameInfo, IsAddressOfOperand,
1014                                       /*TemplateArgs=*/nullptr);
1015   }
1016 
1017   case LookupResult::Found:
1018   case LookupResult::FoundOverloaded:
1019   case LookupResult::FoundUnresolvedValue:
1020     break;
1021 
1022   case LookupResult::Ambiguous:
1023     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024         hasAnyAcceptableTemplateNames(Result)) {
1025       // C++ [temp.local]p3:
1026       //   A lookup that finds an injected-class-name (10.2) can result in an
1027       //   ambiguity in certain cases (for example, if it is found in more than
1028       //   one base class). If all of the injected-class-names that are found
1029       //   refer to specializations of the same class template, and if the name
1030       //   is followed by a template-argument-list, the reference refers to the
1031       //   class template itself and not a specialization thereof, and is not
1032       //   ambiguous.
1033       //
1034       // This filtering can make an ambiguous result into an unambiguous one,
1035       // so try again after filtering out template names.
1036       FilterAcceptableTemplateNames(Result);
1037       if (!Result.isAmbiguous()) {
1038         IsFilteredTemplateName = true;
1039         break;
1040       }
1041     }
1042 
1043     // Diagnose the ambiguity and return an error.
1044     return NameClassification::Error();
1045   }
1046 
1047   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049     // C++ [temp.names]p3:
1050     //   After name lookup (3.4) finds that a name is a template-name or that
1051     //   an operator-function-id or a literal- operator-id refers to a set of
1052     //   overloaded functions any member of which is a function template if
1053     //   this is followed by a <, the < is always taken as the delimiter of a
1054     //   template-argument-list and never as the less-than operator.
1055     if (!IsFilteredTemplateName)
1056       FilterAcceptableTemplateNames(Result);
1057 
1058     if (!Result.empty()) {
1059       bool IsFunctionTemplate;
1060       bool IsVarTemplate;
1061       TemplateName Template;
1062       if (Result.end() - Result.begin() > 1) {
1063         IsFunctionTemplate = true;
1064         Template = Context.getOverloadedTemplateName(Result.begin(),
1065                                                      Result.end());
1066       } else {
1067         TemplateDecl *TD
1068           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070         IsVarTemplate = isa<VarTemplateDecl>(TD);
1071 
1072         if (SS.isSet() && !SS.isInvalid())
1073           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074                                                     /*TemplateKeyword=*/false,
1075                                                       TD);
1076         else
1077           Template = TemplateName(TD);
1078       }
1079 
1080       if (IsFunctionTemplate) {
1081         // Function templates always go through overload resolution, at which
1082         // point we'll perform the various checks (e.g., accessibility) we need
1083         // to based on which function we selected.
1084         Result.suppressDiagnostics();
1085 
1086         return NameClassification::FunctionTemplate(Template);
1087       }
1088 
1089       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090                            : NameClassification::TypeTemplate(Template);
1091     }
1092   }
1093 
1094   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096     DiagnoseUseOfDecl(Type, NameLoc);
1097     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098     QualType T = Context.getTypeDeclType(Type);
1099     if (SS.isNotEmpty())
1100       return buildNestedType(*this, SS, T, NameLoc);
1101     return ParsedType::make(T);
1102   }
1103 
1104   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105   if (!Class) {
1106     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107     if (ObjCCompatibleAliasDecl *Alias =
1108             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109       Class = Alias->getClassInterface();
1110   }
1111 
1112   if (Class) {
1113     DiagnoseUseOfDecl(Class, NameLoc);
1114 
1115     if (NextToken.is(tok::period)) {
1116       // Interface. <something> is parsed as a property reference expression.
1117       // Just return "unknown" as a fall-through for now.
1118       Result.suppressDiagnostics();
1119       return NameClassification::Unknown();
1120     }
1121 
1122     QualType T = Context.getObjCInterfaceType(Class);
1123     return ParsedType::make(T);
1124   }
1125 
1126   // We can have a type template here if we're classifying a template argument.
1127   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128       !isa<VarTemplateDecl>(FirstDecl))
1129     return NameClassification::TypeTemplate(
1130         TemplateName(cast<TemplateDecl>(FirstDecl)));
1131 
1132   // Check for a tag type hidden by a non-type decl in a few cases where it
1133   // seems likely a type is wanted instead of the non-type that was found.
1134   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135   if ((NextToken.is(tok::identifier) ||
1136        (NextIsOp &&
1137         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140     DiagnoseUseOfDecl(Type, NameLoc);
1141     QualType T = Context.getTypeDeclType(Type);
1142     if (SS.isNotEmpty())
1143       return buildNestedType(*this, SS, T, NameLoc);
1144     return ParsedType::make(T);
1145   }
1146 
1147   if (FirstDecl->isCXXClassMember())
1148     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149                                            nullptr, S);
1150 
1151   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152   return BuildDeclarationNameExpr(SS, Result, ADL);
1153 }
1154 
1155 Sema::TemplateNameKindForDiagnostics
1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157   auto *TD = Name.getAsTemplateDecl();
1158   if (!TD)
1159     return TemplateNameKindForDiagnostics::DependentTemplate;
1160   if (isa<ClassTemplateDecl>(TD))
1161     return TemplateNameKindForDiagnostics::ClassTemplate;
1162   if (isa<FunctionTemplateDecl>(TD))
1163     return TemplateNameKindForDiagnostics::FunctionTemplate;
1164   if (isa<VarTemplateDecl>(TD))
1165     return TemplateNameKindForDiagnostics::VarTemplate;
1166   if (isa<TypeAliasTemplateDecl>(TD))
1167     return TemplateNameKindForDiagnostics::AliasTemplate;
1168   if (isa<TemplateTemplateParmDecl>(TD))
1169     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170   return TemplateNameKindForDiagnostics::DependentTemplate;
1171 }
1172 
1173 // Determines the context to return to after temporarily entering a
1174 // context.  This depends in an unnecessarily complicated way on the
1175 // exact ordering of callbacks from the parser.
1176 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177 
1178   // Functions defined inline within classes aren't parsed until we've
1179   // finished parsing the top-level class, so the top-level class is
1180   // the context we'll need to return to.
1181   // A Lambda call operator whose parent is a class must not be treated
1182   // as an inline member function.  A Lambda can be used legally
1183   // either as an in-class member initializer or a default argument.  These
1184   // are parsed once the class has been marked complete and so the containing
1185   // context would be the nested class (when the lambda is defined in one);
1186   // If the class is not complete, then the lambda is being used in an
1187   // ill-formed fashion (such as to specify the width of a bit-field, or
1188   // in an array-bound) - in which case we still want to return the
1189   // lexically containing DC (which could be a nested class).
1190   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191     DC = DC->getLexicalParent();
1192 
1193     // A function not defined within a class will always return to its
1194     // lexical context.
1195     if (!isa<CXXRecordDecl>(DC))
1196       return DC;
1197 
1198     // A C++ inline method/friend is parsed *after* the topmost class
1199     // it was declared in is fully parsed ("complete");  the topmost
1200     // class is the context we need to return to.
1201     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202       DC = RD;
1203 
1204     // Return the declaration context of the topmost class the inline method is
1205     // declared in.
1206     return DC;
1207   }
1208 
1209   return DC->getLexicalParent();
1210 }
1211 
1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213   assert(getContainingDC(DC) == CurContext &&
1214       "The next DeclContext should be lexically contained in the current one.");
1215   CurContext = DC;
1216   S->setEntity(DC);
1217 }
1218 
1219 void Sema::PopDeclContext() {
1220   assert(CurContext && "DeclContext imbalance!");
1221 
1222   CurContext = getContainingDC(CurContext);
1223   assert(CurContext && "Popped translation unit!");
1224 }
1225 
1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227                                                                     Decl *D) {
1228   // Unlike PushDeclContext, the context to which we return is not necessarily
1229   // the containing DC of TD, because the new context will be some pre-existing
1230   // TagDecl definition instead of a fresh one.
1231   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232   CurContext = cast<TagDecl>(D)->getDefinition();
1233   assert(CurContext && "skipping definition of undefined tag");
1234   // Start lookups from the parent of the current context; we don't want to look
1235   // into the pre-existing complete definition.
1236   S->setEntity(CurContext->getLookupParent());
1237   return Result;
1238 }
1239 
1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241   CurContext = static_cast<decltype(CurContext)>(Context);
1242 }
1243 
1244 /// EnterDeclaratorContext - Used when we must lookup names in the context
1245 /// of a declarator's nested name specifier.
1246 ///
1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248   // C++0x [basic.lookup.unqual]p13:
1249   //   A name used in the definition of a static data member of class
1250   //   X (after the qualified-id of the static member) is looked up as
1251   //   if the name was used in a member function of X.
1252   // C++0x [basic.lookup.unqual]p14:
1253   //   If a variable member of a namespace is defined outside of the
1254   //   scope of its namespace then any name used in the definition of
1255   //   the variable member (after the declarator-id) is looked up as
1256   //   if the definition of the variable member occurred in its
1257   //   namespace.
1258   // Both of these imply that we should push a scope whose context
1259   // is the semantic context of the declaration.  We can't use
1260   // PushDeclContext here because that context is not necessarily
1261   // lexically contained in the current context.  Fortunately,
1262   // the containing scope should have the appropriate information.
1263 
1264   assert(!S->getEntity() && "scope already has entity");
1265 
1266 #ifndef NDEBUG
1267   Scope *Ancestor = S->getParent();
1268   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1270 #endif
1271 
1272   CurContext = DC;
1273   S->setEntity(DC);
1274 }
1275 
1276 void Sema::ExitDeclaratorContext(Scope *S) {
1277   assert(S->getEntity() == CurContext && "Context imbalance!");
1278 
1279   // Switch back to the lexical context.  The safety of this is
1280   // enforced by an assert in EnterDeclaratorContext.
1281   Scope *Ancestor = S->getParent();
1282   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283   CurContext = Ancestor->getEntity();
1284 
1285   // We don't need to do anything with the scope, which is going to
1286   // disappear.
1287 }
1288 
1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290   // We assume that the caller has already called
1291   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292   FunctionDecl *FD = D->getAsFunction();
1293   if (!FD)
1294     return;
1295 
1296   // Same implementation as PushDeclContext, but enters the context
1297   // from the lexical parent, rather than the top-level class.
1298   assert(CurContext == FD->getLexicalParent() &&
1299     "The next DeclContext should be lexically contained in the current one.");
1300   CurContext = FD;
1301   S->setEntity(CurContext);
1302 
1303   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304     ParmVarDecl *Param = FD->getParamDecl(P);
1305     // If the parameter has an identifier, then add it to the scope
1306     if (Param->getIdentifier()) {
1307       S->AddDecl(Param);
1308       IdResolver.AddDecl(Param);
1309     }
1310   }
1311 }
1312 
1313 void Sema::ActOnExitFunctionContext() {
1314   // Same implementation as PopDeclContext, but returns to the lexical parent,
1315   // rather than the top-level class.
1316   assert(CurContext && "DeclContext imbalance!");
1317   CurContext = CurContext->getLexicalParent();
1318   assert(CurContext && "Popped translation unit!");
1319 }
1320 
1321 /// \brief Determine whether we allow overloading of the function
1322 /// PrevDecl with another declaration.
1323 ///
1324 /// This routine determines whether overloading is possible, not
1325 /// whether some new function is actually an overload. It will return
1326 /// true in C++ (where we can always provide overloads) or, as an
1327 /// extension, in C when the previous function is already an
1328 /// overloaded function declaration or has the "overloadable"
1329 /// attribute.
1330 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331                                        ASTContext &Context,
1332                                        const FunctionDecl *New) {
1333   if (Context.getLangOpts().CPlusPlus)
1334     return true;
1335 
1336   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337     return true;
1338 
1339   return Previous.getResultKind() == LookupResult::Found &&
1340          (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341           New->hasAttr<OverloadableAttr>());
1342 }
1343 
1344 /// Add this decl to the scope shadowed decl chains.
1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346   // Move up the scope chain until we find the nearest enclosing
1347   // non-transparent context. The declaration will be introduced into this
1348   // scope.
1349   while (S->getEntity() && S->getEntity()->isTransparentContext())
1350     S = S->getParent();
1351 
1352   // Add scoped declarations into their context, so that they can be
1353   // found later. Declarations without a context won't be inserted
1354   // into any context.
1355   if (AddToContext)
1356     CurContext->addDecl(D);
1357 
1358   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359   // are function-local declarations.
1360   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361       !D->getDeclContext()->getRedeclContext()->Equals(
1362         D->getLexicalDeclContext()->getRedeclContext()) &&
1363       !D->getLexicalDeclContext()->isFunctionOrMethod())
1364     return;
1365 
1366   // Template instantiations should also not be pushed into scope.
1367   if (isa<FunctionDecl>(D) &&
1368       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369     return;
1370 
1371   // If this replaces anything in the current scope,
1372   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373                                IEnd = IdResolver.end();
1374   for (; I != IEnd; ++I) {
1375     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376       S->RemoveDecl(*I);
1377       IdResolver.RemoveDecl(*I);
1378 
1379       // Should only need to replace one decl.
1380       break;
1381     }
1382   }
1383 
1384   S->AddDecl(D);
1385 
1386   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387     // Implicitly-generated labels may end up getting generated in an order that
1388     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389     // the label at the appropriate place in the identifier chain.
1390     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392       if (IDC == CurContext) {
1393         if (!S->isDeclScope(*I))
1394           continue;
1395       } else if (IDC->Encloses(CurContext))
1396         break;
1397     }
1398 
1399     IdResolver.InsertDeclAfter(I, D);
1400   } else {
1401     IdResolver.AddDecl(D);
1402   }
1403 }
1404 
1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407     TUScope->AddDecl(D);
1408 }
1409 
1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411                          bool AllowInlineNamespace) {
1412   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413 }
1414 
1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416   DeclContext *TargetDC = DC->getPrimaryContext();
1417   do {
1418     if (DeclContext *ScopeDC = S->getEntity())
1419       if (ScopeDC->getPrimaryContext() == TargetDC)
1420         return S;
1421   } while ((S = S->getParent()));
1422 
1423   return nullptr;
1424 }
1425 
1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427                                             DeclContext*,
1428                                             ASTContext&);
1429 
1430 /// Filters out lookup results that don't fall within the given scope
1431 /// as determined by isDeclInScope.
1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433                                 bool ConsiderLinkage,
1434                                 bool AllowInlineNamespace) {
1435   LookupResult::Filter F = R.makeFilter();
1436   while (F.hasNext()) {
1437     NamedDecl *D = F.next();
1438 
1439     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440       continue;
1441 
1442     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443       continue;
1444 
1445     F.erase();
1446   }
1447 
1448   F.done();
1449 }
1450 
1451 static bool isUsingDecl(NamedDecl *D) {
1452   return isa<UsingShadowDecl>(D) ||
1453          isa<UnresolvedUsingTypenameDecl>(D) ||
1454          isa<UnresolvedUsingValueDecl>(D);
1455 }
1456 
1457 /// Removes using shadow declarations from the lookup results.
1458 static void RemoveUsingDecls(LookupResult &R) {
1459   LookupResult::Filter F = R.makeFilter();
1460   while (F.hasNext())
1461     if (isUsingDecl(F.next()))
1462       F.erase();
1463 
1464   F.done();
1465 }
1466 
1467 /// \brief Check for this common pattern:
1468 /// @code
1469 /// class S {
1470 ///   S(const S&); // DO NOT IMPLEMENT
1471 ///   void operator=(const S&); // DO NOT IMPLEMENT
1472 /// };
1473 /// @endcode
1474 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1475   // FIXME: Should check for private access too but access is set after we get
1476   // the decl here.
1477   if (D->doesThisDeclarationHaveABody())
1478     return false;
1479 
1480   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1481     return CD->isCopyConstructor();
1482   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1483     return Method->isCopyAssignmentOperator();
1484   return false;
1485 }
1486 
1487 // We need this to handle
1488 //
1489 // typedef struct {
1490 //   void *foo() { return 0; }
1491 // } A;
1492 //
1493 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1494 // for example. If 'A', foo will have external linkage. If we have '*A',
1495 // foo will have no linkage. Since we can't know until we get to the end
1496 // of the typedef, this function finds out if D might have non-external linkage.
1497 // Callers should verify at the end of the TU if it D has external linkage or
1498 // not.
1499 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1500   const DeclContext *DC = D->getDeclContext();
1501   while (!DC->isTranslationUnit()) {
1502     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1503       if (!RD->hasNameForLinkage())
1504         return true;
1505     }
1506     DC = DC->getParent();
1507   }
1508 
1509   return !D->isExternallyVisible();
1510 }
1511 
1512 // FIXME: This needs to be refactored; some other isInMainFile users want
1513 // these semantics.
1514 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1515   if (S.TUKind != TU_Complete)
1516     return false;
1517   return S.SourceMgr.isInMainFile(Loc);
1518 }
1519 
1520 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1521   assert(D);
1522 
1523   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1524     return false;
1525 
1526   // Ignore all entities declared within templates, and out-of-line definitions
1527   // of members of class templates.
1528   if (D->getDeclContext()->isDependentContext() ||
1529       D->getLexicalDeclContext()->isDependentContext())
1530     return false;
1531 
1532   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1533     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1534       return false;
1535     // A non-out-of-line declaration of a member specialization was implicitly
1536     // instantiated; it's the out-of-line declaration that we're interested in.
1537     if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1538         FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1539       return false;
1540 
1541     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1542       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1543         return false;
1544     } else {
1545       // 'static inline' functions are defined in headers; don't warn.
1546       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1547         return false;
1548     }
1549 
1550     if (FD->doesThisDeclarationHaveABody() &&
1551         Context.DeclMustBeEmitted(FD))
1552       return false;
1553   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1554     // Constants and utility variables are defined in headers with internal
1555     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1556     // like "inline".)
1557     if (!isMainFileLoc(*this, VD->getLocation()))
1558       return false;
1559 
1560     if (Context.DeclMustBeEmitted(VD))
1561       return false;
1562 
1563     if (VD->isStaticDataMember() &&
1564         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1565       return false;
1566     if (VD->isStaticDataMember() &&
1567         VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1568         VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1569       return false;
1570 
1571     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1572       return false;
1573   } else {
1574     return false;
1575   }
1576 
1577   // Only warn for unused decls internal to the translation unit.
1578   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1579   // for inline functions defined in the main source file, for instance.
1580   return mightHaveNonExternalLinkage(D);
1581 }
1582 
1583 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1584   if (!D)
1585     return;
1586 
1587   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1588     const FunctionDecl *First = FD->getFirstDecl();
1589     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1590       return; // First should already be in the vector.
1591   }
1592 
1593   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594     const VarDecl *First = VD->getFirstDecl();
1595     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1596       return; // First should already be in the vector.
1597   }
1598 
1599   if (ShouldWarnIfUnusedFileScopedDecl(D))
1600     UnusedFileScopedDecls.push_back(D);
1601 }
1602 
1603 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1604   if (D->isInvalidDecl())
1605     return false;
1606 
1607   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1608       D->hasAttr<ObjCPreciseLifetimeAttr>())
1609     return false;
1610 
1611   if (isa<LabelDecl>(D))
1612     return true;
1613 
1614   // Except for labels, we only care about unused decls that are local to
1615   // functions.
1616   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1617   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1618     // For dependent types, the diagnostic is deferred.
1619     WithinFunction =
1620         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1621   if (!WithinFunction)
1622     return false;
1623 
1624   if (isa<TypedefNameDecl>(D))
1625     return true;
1626 
1627   // White-list anything that isn't a local variable.
1628   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1629     return false;
1630 
1631   // Types of valid local variables should be complete, so this should succeed.
1632   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1633 
1634     // White-list anything with an __attribute__((unused)) type.
1635     const auto *Ty = VD->getType().getTypePtr();
1636 
1637     // Only look at the outermost level of typedef.
1638     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1639       if (TT->getDecl()->hasAttr<UnusedAttr>())
1640         return false;
1641     }
1642 
1643     // If we failed to complete the type for some reason, or if the type is
1644     // dependent, don't diagnose the variable.
1645     if (Ty->isIncompleteType() || Ty->isDependentType())
1646       return false;
1647 
1648     // Look at the element type to ensure that the warning behaviour is
1649     // consistent for both scalars and arrays.
1650     Ty = Ty->getBaseElementTypeUnsafe();
1651 
1652     if (const TagType *TT = Ty->getAs<TagType>()) {
1653       const TagDecl *Tag = TT->getDecl();
1654       if (Tag->hasAttr<UnusedAttr>())
1655         return false;
1656 
1657       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1658         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1659           return false;
1660 
1661         if (const Expr *Init = VD->getInit()) {
1662           if (const ExprWithCleanups *Cleanups =
1663                   dyn_cast<ExprWithCleanups>(Init))
1664             Init = Cleanups->getSubExpr();
1665           const CXXConstructExpr *Construct =
1666             dyn_cast<CXXConstructExpr>(Init);
1667           if (Construct && !Construct->isElidable()) {
1668             CXXConstructorDecl *CD = Construct->getConstructor();
1669             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1670               return false;
1671           }
1672         }
1673       }
1674     }
1675 
1676     // TODO: __attribute__((unused)) templates?
1677   }
1678 
1679   return true;
1680 }
1681 
1682 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1683                                      FixItHint &Hint) {
1684   if (isa<LabelDecl>(D)) {
1685     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1686                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1687     if (AfterColon.isInvalid())
1688       return;
1689     Hint = FixItHint::CreateRemoval(CharSourceRange::
1690                                     getCharRange(D->getLocStart(), AfterColon));
1691   }
1692 }
1693 
1694 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1695   if (D->getTypeForDecl()->isDependentType())
1696     return;
1697 
1698   for (auto *TmpD : D->decls()) {
1699     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1700       DiagnoseUnusedDecl(T);
1701     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1702       DiagnoseUnusedNestedTypedefs(R);
1703   }
1704 }
1705 
1706 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1707 /// unless they are marked attr(unused).
1708 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1709   if (!ShouldDiagnoseUnusedDecl(D))
1710     return;
1711 
1712   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1713     // typedefs can be referenced later on, so the diagnostics are emitted
1714     // at end-of-translation-unit.
1715     UnusedLocalTypedefNameCandidates.insert(TD);
1716     return;
1717   }
1718 
1719   FixItHint Hint;
1720   GenerateFixForUnusedDecl(D, Context, Hint);
1721 
1722   unsigned DiagID;
1723   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1724     DiagID = diag::warn_unused_exception_param;
1725   else if (isa<LabelDecl>(D))
1726     DiagID = diag::warn_unused_label;
1727   else
1728     DiagID = diag::warn_unused_variable;
1729 
1730   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1731 }
1732 
1733 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1734   // Verify that we have no forward references left.  If so, there was a goto
1735   // or address of a label taken, but no definition of it.  Label fwd
1736   // definitions are indicated with a null substmt which is also not a resolved
1737   // MS inline assembly label name.
1738   bool Diagnose = false;
1739   if (L->isMSAsmLabel())
1740     Diagnose = !L->isResolvedMSAsmLabel();
1741   else
1742     Diagnose = L->getStmt() == nullptr;
1743   if (Diagnose)
1744     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1745 }
1746 
1747 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1748   S->mergeNRVOIntoParent();
1749 
1750   if (S->decl_empty()) return;
1751   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1752          "Scope shouldn't contain decls!");
1753 
1754   for (auto *TmpD : S->decls()) {
1755     assert(TmpD && "This decl didn't get pushed??");
1756 
1757     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1758     NamedDecl *D = cast<NamedDecl>(TmpD);
1759 
1760     if (!D->getDeclName()) continue;
1761 
1762     // Diagnose unused variables in this scope.
1763     if (!S->hasUnrecoverableErrorOccurred()) {
1764       DiagnoseUnusedDecl(D);
1765       if (const auto *RD = dyn_cast<RecordDecl>(D))
1766         DiagnoseUnusedNestedTypedefs(RD);
1767     }
1768 
1769     // If this was a forward reference to a label, verify it was defined.
1770     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1771       CheckPoppedLabel(LD, *this);
1772 
1773     // Remove this name from our lexical scope, and warn on it if we haven't
1774     // already.
1775     IdResolver.RemoveDecl(D);
1776     auto ShadowI = ShadowingDecls.find(D);
1777     if (ShadowI != ShadowingDecls.end()) {
1778       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1779         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1780             << D << FD << FD->getParent();
1781         Diag(FD->getLocation(), diag::note_previous_declaration);
1782       }
1783       ShadowingDecls.erase(ShadowI);
1784     }
1785   }
1786 }
1787 
1788 /// \brief Look for an Objective-C class in the translation unit.
1789 ///
1790 /// \param Id The name of the Objective-C class we're looking for. If
1791 /// typo-correction fixes this name, the Id will be updated
1792 /// to the fixed name.
1793 ///
1794 /// \param IdLoc The location of the name in the translation unit.
1795 ///
1796 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1797 /// if there is no class with the given name.
1798 ///
1799 /// \returns The declaration of the named Objective-C class, or NULL if the
1800 /// class could not be found.
1801 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1802                                               SourceLocation IdLoc,
1803                                               bool DoTypoCorrection) {
1804   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1805   // creation from this context.
1806   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1807 
1808   if (!IDecl && DoTypoCorrection) {
1809     // Perform typo correction at the given location, but only if we
1810     // find an Objective-C class name.
1811     if (TypoCorrection C = CorrectTypo(
1812             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1813             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1814             CTK_ErrorRecovery)) {
1815       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1816       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1817       Id = IDecl->getIdentifier();
1818     }
1819   }
1820   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1821   // This routine must always return a class definition, if any.
1822   if (Def && Def->getDefinition())
1823       Def = Def->getDefinition();
1824   return Def;
1825 }
1826 
1827 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1828 /// from S, where a non-field would be declared. This routine copes
1829 /// with the difference between C and C++ scoping rules in structs and
1830 /// unions. For example, the following code is well-formed in C but
1831 /// ill-formed in C++:
1832 /// @code
1833 /// struct S6 {
1834 ///   enum { BAR } e;
1835 /// };
1836 ///
1837 /// void test_S6() {
1838 ///   struct S6 a;
1839 ///   a.e = BAR;
1840 /// }
1841 /// @endcode
1842 /// For the declaration of BAR, this routine will return a different
1843 /// scope. The scope S will be the scope of the unnamed enumeration
1844 /// within S6. In C++, this routine will return the scope associated
1845 /// with S6, because the enumeration's scope is a transparent
1846 /// context but structures can contain non-field names. In C, this
1847 /// routine will return the translation unit scope, since the
1848 /// enumeration's scope is a transparent context and structures cannot
1849 /// contain non-field names.
1850 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1851   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1852          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1853          (S->isClassScope() && !getLangOpts().CPlusPlus))
1854     S = S->getParent();
1855   return S;
1856 }
1857 
1858 /// \brief Looks up the declaration of "struct objc_super" and
1859 /// saves it for later use in building builtin declaration of
1860 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1861 /// pre-existing declaration exists no action takes place.
1862 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1863                                         IdentifierInfo *II) {
1864   if (!II->isStr("objc_msgSendSuper"))
1865     return;
1866   ASTContext &Context = ThisSema.Context;
1867 
1868   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1869                       SourceLocation(), Sema::LookupTagName);
1870   ThisSema.LookupName(Result, S);
1871   if (Result.getResultKind() == LookupResult::Found)
1872     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1873       Context.setObjCSuperType(Context.getTagDeclType(TD));
1874 }
1875 
1876 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1877   switch (Error) {
1878   case ASTContext::GE_None:
1879     return "";
1880   case ASTContext::GE_Missing_stdio:
1881     return "stdio.h";
1882   case ASTContext::GE_Missing_setjmp:
1883     return "setjmp.h";
1884   case ASTContext::GE_Missing_ucontext:
1885     return "ucontext.h";
1886   }
1887   llvm_unreachable("unhandled error kind");
1888 }
1889 
1890 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1891 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1892 /// if we're creating this built-in in anticipation of redeclaring the
1893 /// built-in.
1894 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1895                                      Scope *S, bool ForRedeclaration,
1896                                      SourceLocation Loc) {
1897   LookupPredefedObjCSuperType(*this, S, II);
1898 
1899   ASTContext::GetBuiltinTypeError Error;
1900   QualType R = Context.GetBuiltinType(ID, Error);
1901   if (Error) {
1902     if (ForRedeclaration)
1903       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1904           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1905     return nullptr;
1906   }
1907 
1908   if (!ForRedeclaration &&
1909       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1910        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1911     Diag(Loc, diag::ext_implicit_lib_function_decl)
1912         << Context.BuiltinInfo.getName(ID) << R;
1913     if (Context.BuiltinInfo.getHeaderName(ID) &&
1914         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1915       Diag(Loc, diag::note_include_header_or_declare)
1916           << Context.BuiltinInfo.getHeaderName(ID)
1917           << Context.BuiltinInfo.getName(ID);
1918   }
1919 
1920   if (R.isNull())
1921     return nullptr;
1922 
1923   DeclContext *Parent = Context.getTranslationUnitDecl();
1924   if (getLangOpts().CPlusPlus) {
1925     LinkageSpecDecl *CLinkageDecl =
1926         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1927                                 LinkageSpecDecl::lang_c, false);
1928     CLinkageDecl->setImplicit();
1929     Parent->addDecl(CLinkageDecl);
1930     Parent = CLinkageDecl;
1931   }
1932 
1933   FunctionDecl *New = FunctionDecl::Create(Context,
1934                                            Parent,
1935                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1936                                            SC_Extern,
1937                                            false,
1938                                            R->isFunctionProtoType());
1939   New->setImplicit();
1940 
1941   // Create Decl objects for each parameter, adding them to the
1942   // FunctionDecl.
1943   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1944     SmallVector<ParmVarDecl*, 16> Params;
1945     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1946       ParmVarDecl *parm =
1947           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1948                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1949                               SC_None, nullptr);
1950       parm->setScopeInfo(0, i);
1951       Params.push_back(parm);
1952     }
1953     New->setParams(Params);
1954   }
1955 
1956   AddKnownFunctionAttributes(New);
1957   RegisterLocallyScopedExternCDecl(New, S);
1958 
1959   // TUScope is the translation-unit scope to insert this function into.
1960   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1961   // relate Scopes to DeclContexts, and probably eliminate CurContext
1962   // entirely, but we're not there yet.
1963   DeclContext *SavedContext = CurContext;
1964   CurContext = Parent;
1965   PushOnScopeChains(New, TUScope);
1966   CurContext = SavedContext;
1967   return New;
1968 }
1969 
1970 /// Typedef declarations don't have linkage, but they still denote the same
1971 /// entity if their types are the same.
1972 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1973 /// isSameEntity.
1974 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1975                                                      TypedefNameDecl *Decl,
1976                                                      LookupResult &Previous) {
1977   // This is only interesting when modules are enabled.
1978   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1979     return;
1980 
1981   // Empty sets are uninteresting.
1982   if (Previous.empty())
1983     return;
1984 
1985   LookupResult::Filter Filter = Previous.makeFilter();
1986   while (Filter.hasNext()) {
1987     NamedDecl *Old = Filter.next();
1988 
1989     // Non-hidden declarations are never ignored.
1990     if (S.isVisible(Old))
1991       continue;
1992 
1993     // Declarations of the same entity are not ignored, even if they have
1994     // different linkages.
1995     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1996       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1997                                 Decl->getUnderlyingType()))
1998         continue;
1999 
2000       // If both declarations give a tag declaration a typedef name for linkage
2001       // purposes, then they declare the same entity.
2002       if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2003           Decl->getAnonDeclWithTypedefName())
2004         continue;
2005     }
2006 
2007     Filter.erase();
2008   }
2009 
2010   Filter.done();
2011 }
2012 
2013 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2014   QualType OldType;
2015   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2016     OldType = OldTypedef->getUnderlyingType();
2017   else
2018     OldType = Context.getTypeDeclType(Old);
2019   QualType NewType = New->getUnderlyingType();
2020 
2021   if (NewType->isVariablyModifiedType()) {
2022     // Must not redefine a typedef with a variably-modified type.
2023     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2024     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2025       << Kind << NewType;
2026     if (Old->getLocation().isValid())
2027       notePreviousDefinition(Old, New->getLocation());
2028     New->setInvalidDecl();
2029     return true;
2030   }
2031 
2032   if (OldType != NewType &&
2033       !OldType->isDependentType() &&
2034       !NewType->isDependentType() &&
2035       !Context.hasSameType(OldType, NewType)) {
2036     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2037     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2038       << Kind << NewType << OldType;
2039     if (Old->getLocation().isValid())
2040       notePreviousDefinition(Old, New->getLocation());
2041     New->setInvalidDecl();
2042     return true;
2043   }
2044   return false;
2045 }
2046 
2047 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2048 /// same name and scope as a previous declaration 'Old'.  Figure out
2049 /// how to resolve this situation, merging decls or emitting
2050 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2051 ///
2052 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2053                                 LookupResult &OldDecls) {
2054   // If the new decl is known invalid already, don't bother doing any
2055   // merging checks.
2056   if (New->isInvalidDecl()) return;
2057 
2058   // Allow multiple definitions for ObjC built-in typedefs.
2059   // FIXME: Verify the underlying types are equivalent!
2060   if (getLangOpts().ObjC1) {
2061     const IdentifierInfo *TypeID = New->getIdentifier();
2062     switch (TypeID->getLength()) {
2063     default: break;
2064     case 2:
2065       {
2066         if (!TypeID->isStr("id"))
2067           break;
2068         QualType T = New->getUnderlyingType();
2069         if (!T->isPointerType())
2070           break;
2071         if (!T->isVoidPointerType()) {
2072           QualType PT = T->getAs<PointerType>()->getPointeeType();
2073           if (!PT->isStructureType())
2074             break;
2075         }
2076         Context.setObjCIdRedefinitionType(T);
2077         // Install the built-in type for 'id', ignoring the current definition.
2078         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2079         return;
2080       }
2081     case 5:
2082       if (!TypeID->isStr("Class"))
2083         break;
2084       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2085       // Install the built-in type for 'Class', ignoring the current definition.
2086       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2087       return;
2088     case 3:
2089       if (!TypeID->isStr("SEL"))
2090         break;
2091       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2092       // Install the built-in type for 'SEL', ignoring the current definition.
2093       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2094       return;
2095     }
2096     // Fall through - the typedef name was not a builtin type.
2097   }
2098 
2099   // Verify the old decl was also a type.
2100   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2101   if (!Old) {
2102     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2103       << New->getDeclName();
2104 
2105     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2106     if (OldD->getLocation().isValid())
2107       notePreviousDefinition(OldD, New->getLocation());
2108 
2109     return New->setInvalidDecl();
2110   }
2111 
2112   // If the old declaration is invalid, just give up here.
2113   if (Old->isInvalidDecl())
2114     return New->setInvalidDecl();
2115 
2116   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2117     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2118     auto *NewTag = New->getAnonDeclWithTypedefName();
2119     NamedDecl *Hidden = nullptr;
2120     if (OldTag && NewTag &&
2121         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2122         !hasVisibleDefinition(OldTag, &Hidden)) {
2123       // There is a definition of this tag, but it is not visible. Use it
2124       // instead of our tag.
2125       New->setTypeForDecl(OldTD->getTypeForDecl());
2126       if (OldTD->isModed())
2127         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2128                                     OldTD->getUnderlyingType());
2129       else
2130         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2131 
2132       // Make the old tag definition visible.
2133       makeMergedDefinitionVisible(Hidden);
2134 
2135       // If this was an unscoped enumeration, yank all of its enumerators
2136       // out of the scope.
2137       if (isa<EnumDecl>(NewTag)) {
2138         Scope *EnumScope = getNonFieldDeclScope(S);
2139         for (auto *D : NewTag->decls()) {
2140           auto *ED = cast<EnumConstantDecl>(D);
2141           assert(EnumScope->isDeclScope(ED));
2142           EnumScope->RemoveDecl(ED);
2143           IdResolver.RemoveDecl(ED);
2144           ED->getLexicalDeclContext()->removeDecl(ED);
2145         }
2146       }
2147     }
2148   }
2149 
2150   // If the typedef types are not identical, reject them in all languages and
2151   // with any extensions enabled.
2152   if (isIncompatibleTypedef(Old, New))
2153     return;
2154 
2155   // The types match.  Link up the redeclaration chain and merge attributes if
2156   // the old declaration was a typedef.
2157   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2158     New->setPreviousDecl(Typedef);
2159     mergeDeclAttributes(New, Old);
2160   }
2161 
2162   if (getLangOpts().MicrosoftExt)
2163     return;
2164 
2165   if (getLangOpts().CPlusPlus) {
2166     // C++ [dcl.typedef]p2:
2167     //   In a given non-class scope, a typedef specifier can be used to
2168     //   redefine the name of any type declared in that scope to refer
2169     //   to the type to which it already refers.
2170     if (!isa<CXXRecordDecl>(CurContext))
2171       return;
2172 
2173     // C++0x [dcl.typedef]p4:
2174     //   In a given class scope, a typedef specifier can be used to redefine
2175     //   any class-name declared in that scope that is not also a typedef-name
2176     //   to refer to the type to which it already refers.
2177     //
2178     // This wording came in via DR424, which was a correction to the
2179     // wording in DR56, which accidentally banned code like:
2180     //
2181     //   struct S {
2182     //     typedef struct A { } A;
2183     //   };
2184     //
2185     // in the C++03 standard. We implement the C++0x semantics, which
2186     // allow the above but disallow
2187     //
2188     //   struct S {
2189     //     typedef int I;
2190     //     typedef int I;
2191     //   };
2192     //
2193     // since that was the intent of DR56.
2194     if (!isa<TypedefNameDecl>(Old))
2195       return;
2196 
2197     Diag(New->getLocation(), diag::err_redefinition)
2198       << New->getDeclName();
2199     notePreviousDefinition(Old, New->getLocation());
2200     return New->setInvalidDecl();
2201   }
2202 
2203   // Modules always permit redefinition of typedefs, as does C11.
2204   if (getLangOpts().Modules || getLangOpts().C11)
2205     return;
2206 
2207   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2208   // is normally mapped to an error, but can be controlled with
2209   // -Wtypedef-redefinition.  If either the original or the redefinition is
2210   // in a system header, don't emit this for compatibility with GCC.
2211   if (getDiagnostics().getSuppressSystemWarnings() &&
2212       // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2213       (Old->isImplicit() ||
2214        Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2215        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2216     return;
2217 
2218   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2219     << New->getDeclName();
2220   notePreviousDefinition(Old, New->getLocation());
2221 }
2222 
2223 /// DeclhasAttr - returns true if decl Declaration already has the target
2224 /// attribute.
2225 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2226   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2227   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2228   for (const auto *i : D->attrs())
2229     if (i->getKind() == A->getKind()) {
2230       if (Ann) {
2231         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2232           return true;
2233         continue;
2234       }
2235       // FIXME: Don't hardcode this check
2236       if (OA && isa<OwnershipAttr>(i))
2237         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2238       return true;
2239     }
2240 
2241   return false;
2242 }
2243 
2244 static bool isAttributeTargetADefinition(Decl *D) {
2245   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2246     return VD->isThisDeclarationADefinition();
2247   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2248     return TD->isCompleteDefinition() || TD->isBeingDefined();
2249   return true;
2250 }
2251 
2252 /// Merge alignment attributes from \p Old to \p New, taking into account the
2253 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2254 ///
2255 /// \return \c true if any attributes were added to \p New.
2256 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2257   // Look for alignas attributes on Old, and pick out whichever attribute
2258   // specifies the strictest alignment requirement.
2259   AlignedAttr *OldAlignasAttr = nullptr;
2260   AlignedAttr *OldStrictestAlignAttr = nullptr;
2261   unsigned OldAlign = 0;
2262   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2263     // FIXME: We have no way of representing inherited dependent alignments
2264     // in a case like:
2265     //   template<int A, int B> struct alignas(A) X;
2266     //   template<int A, int B> struct alignas(B) X {};
2267     // For now, we just ignore any alignas attributes which are not on the
2268     // definition in such a case.
2269     if (I->isAlignmentDependent())
2270       return false;
2271 
2272     if (I->isAlignas())
2273       OldAlignasAttr = I;
2274 
2275     unsigned Align = I->getAlignment(S.Context);
2276     if (Align > OldAlign) {
2277       OldAlign = Align;
2278       OldStrictestAlignAttr = I;
2279     }
2280   }
2281 
2282   // Look for alignas attributes on New.
2283   AlignedAttr *NewAlignasAttr = nullptr;
2284   unsigned NewAlign = 0;
2285   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2286     if (I->isAlignmentDependent())
2287       return false;
2288 
2289     if (I->isAlignas())
2290       NewAlignasAttr = I;
2291 
2292     unsigned Align = I->getAlignment(S.Context);
2293     if (Align > NewAlign)
2294       NewAlign = Align;
2295   }
2296 
2297   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2298     // Both declarations have 'alignas' attributes. We require them to match.
2299     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2300     // fall short. (If two declarations both have alignas, they must both match
2301     // every definition, and so must match each other if there is a definition.)
2302 
2303     // If either declaration only contains 'alignas(0)' specifiers, then it
2304     // specifies the natural alignment for the type.
2305     if (OldAlign == 0 || NewAlign == 0) {
2306       QualType Ty;
2307       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2308         Ty = VD->getType();
2309       else
2310         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2311 
2312       if (OldAlign == 0)
2313         OldAlign = S.Context.getTypeAlign(Ty);
2314       if (NewAlign == 0)
2315         NewAlign = S.Context.getTypeAlign(Ty);
2316     }
2317 
2318     if (OldAlign != NewAlign) {
2319       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2320         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2321         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2322       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2323     }
2324   }
2325 
2326   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2327     // C++11 [dcl.align]p6:
2328     //   if any declaration of an entity has an alignment-specifier,
2329     //   every defining declaration of that entity shall specify an
2330     //   equivalent alignment.
2331     // C11 6.7.5/7:
2332     //   If the definition of an object does not have an alignment
2333     //   specifier, any other declaration of that object shall also
2334     //   have no alignment specifier.
2335     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2336       << OldAlignasAttr;
2337     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2338       << OldAlignasAttr;
2339   }
2340 
2341   bool AnyAdded = false;
2342 
2343   // Ensure we have an attribute representing the strictest alignment.
2344   if (OldAlign > NewAlign) {
2345     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2346     Clone->setInherited(true);
2347     New->addAttr(Clone);
2348     AnyAdded = true;
2349   }
2350 
2351   // Ensure we have an alignas attribute if the old declaration had one.
2352   if (OldAlignasAttr && !NewAlignasAttr &&
2353       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2354     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2355     Clone->setInherited(true);
2356     New->addAttr(Clone);
2357     AnyAdded = true;
2358   }
2359 
2360   return AnyAdded;
2361 }
2362 
2363 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2364                                const InheritableAttr *Attr,
2365                                Sema::AvailabilityMergeKind AMK) {
2366   // This function copies an attribute Attr from a previous declaration to the
2367   // new declaration D if the new declaration doesn't itself have that attribute
2368   // yet or if that attribute allows duplicates.
2369   // If you're adding a new attribute that requires logic different from
2370   // "use explicit attribute on decl if present, else use attribute from
2371   // previous decl", for example if the attribute needs to be consistent
2372   // between redeclarations, you need to call a custom merge function here.
2373   InheritableAttr *NewAttr = nullptr;
2374   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2375   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2376     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2377                                       AA->isImplicit(), AA->getIntroduced(),
2378                                       AA->getDeprecated(),
2379                                       AA->getObsoleted(), AA->getUnavailable(),
2380                                       AA->getMessage(), AA->getStrict(),
2381                                       AA->getReplacement(), AMK,
2382                                       AttrSpellingListIndex);
2383   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2384     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2385                                     AttrSpellingListIndex);
2386   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2387     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2388                                         AttrSpellingListIndex);
2389   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2390     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2391                                    AttrSpellingListIndex);
2392   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2393     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2394                                    AttrSpellingListIndex);
2395   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2396     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2397                                 FA->getFormatIdx(), FA->getFirstArg(),
2398                                 AttrSpellingListIndex);
2399   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2400     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2401                                  AttrSpellingListIndex);
2402   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2403     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2404                                        AttrSpellingListIndex,
2405                                        IA->getSemanticSpelling());
2406   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2407     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2408                                       &S.Context.Idents.get(AA->getSpelling()),
2409                                       AttrSpellingListIndex);
2410   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2411            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2412             isa<CUDAGlobalAttr>(Attr))) {
2413     // CUDA target attributes are part of function signature for
2414     // overloading purposes and must not be merged.
2415     return false;
2416   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2417     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2418   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2419     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2420   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2421     NewAttr = S.mergeInternalLinkageAttr(
2422         D, InternalLinkageA->getRange(),
2423         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2424         AttrSpellingListIndex);
2425   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2426     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2427                                 &S.Context.Idents.get(CommonA->getSpelling()),
2428                                 AttrSpellingListIndex);
2429   else if (isa<AlignedAttr>(Attr))
2430     // AlignedAttrs are handled separately, because we need to handle all
2431     // such attributes on a declaration at the same time.
2432     NewAttr = nullptr;
2433   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2434            (AMK == Sema::AMK_Override ||
2435             AMK == Sema::AMK_ProtocolImplementation))
2436     NewAttr = nullptr;
2437   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2438     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2439                               UA->getGuid());
2440   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2441     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2442 
2443   if (NewAttr) {
2444     NewAttr->setInherited(true);
2445     D->addAttr(NewAttr);
2446     if (isa<MSInheritanceAttr>(NewAttr))
2447       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2448     return true;
2449   }
2450 
2451   return false;
2452 }
2453 
2454 static const NamedDecl *getDefinition(const Decl *D) {
2455   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2456     return TD->getDefinition();
2457   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2458     const VarDecl *Def = VD->getDefinition();
2459     if (Def)
2460       return Def;
2461     return VD->getActingDefinition();
2462   }
2463   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2464     return FD->getDefinition();
2465   return nullptr;
2466 }
2467 
2468 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2469   for (const auto *Attribute : D->attrs())
2470     if (Attribute->getKind() == Kind)
2471       return true;
2472   return false;
2473 }
2474 
2475 /// checkNewAttributesAfterDef - If we already have a definition, check that
2476 /// there are no new attributes in this declaration.
2477 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2478   if (!New->hasAttrs())
2479     return;
2480 
2481   const NamedDecl *Def = getDefinition(Old);
2482   if (!Def || Def == New)
2483     return;
2484 
2485   AttrVec &NewAttributes = New->getAttrs();
2486   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2487     const Attr *NewAttribute = NewAttributes[I];
2488 
2489     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2490       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2491         Sema::SkipBodyInfo SkipBody;
2492         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2493 
2494         // If we're skipping this definition, drop the "alias" attribute.
2495         if (SkipBody.ShouldSkip) {
2496           NewAttributes.erase(NewAttributes.begin() + I);
2497           --E;
2498           continue;
2499         }
2500       } else {
2501         VarDecl *VD = cast<VarDecl>(New);
2502         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2503                                 VarDecl::TentativeDefinition
2504                             ? diag::err_alias_after_tentative
2505                             : diag::err_redefinition;
2506         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2507         if (Diag == diag::err_redefinition)
2508           S.notePreviousDefinition(Def, VD->getLocation());
2509         else
2510           S.Diag(Def->getLocation(), diag::note_previous_definition);
2511         VD->setInvalidDecl();
2512       }
2513       ++I;
2514       continue;
2515     }
2516 
2517     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2518       // Tentative definitions are only interesting for the alias check above.
2519       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2520         ++I;
2521         continue;
2522       }
2523     }
2524 
2525     if (hasAttribute(Def, NewAttribute->getKind())) {
2526       ++I;
2527       continue; // regular attr merging will take care of validating this.
2528     }
2529 
2530     if (isa<C11NoReturnAttr>(NewAttribute)) {
2531       // C's _Noreturn is allowed to be added to a function after it is defined.
2532       ++I;
2533       continue;
2534     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2535       if (AA->isAlignas()) {
2536         // C++11 [dcl.align]p6:
2537         //   if any declaration of an entity has an alignment-specifier,
2538         //   every defining declaration of that entity shall specify an
2539         //   equivalent alignment.
2540         // C11 6.7.5/7:
2541         //   If the definition of an object does not have an alignment
2542         //   specifier, any other declaration of that object shall also
2543         //   have no alignment specifier.
2544         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2545           << AA;
2546         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2547           << AA;
2548         NewAttributes.erase(NewAttributes.begin() + I);
2549         --E;
2550         continue;
2551       }
2552     }
2553 
2554     S.Diag(NewAttribute->getLocation(),
2555            diag::warn_attribute_precede_definition);
2556     S.Diag(Def->getLocation(), diag::note_previous_definition);
2557     NewAttributes.erase(NewAttributes.begin() + I);
2558     --E;
2559   }
2560 }
2561 
2562 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2563 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2564                                AvailabilityMergeKind AMK) {
2565   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2566     UsedAttr *NewAttr = OldAttr->clone(Context);
2567     NewAttr->setInherited(true);
2568     New->addAttr(NewAttr);
2569   }
2570 
2571   if (!Old->hasAttrs() && !New->hasAttrs())
2572     return;
2573 
2574   // Attributes declared post-definition are currently ignored.
2575   checkNewAttributesAfterDef(*this, New, Old);
2576 
2577   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2578     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2579       if (OldA->getLabel() != NewA->getLabel()) {
2580         // This redeclaration changes __asm__ label.
2581         Diag(New->getLocation(), diag::err_different_asm_label);
2582         Diag(OldA->getLocation(), diag::note_previous_declaration);
2583       }
2584     } else if (Old->isUsed()) {
2585       // This redeclaration adds an __asm__ label to a declaration that has
2586       // already been ODR-used.
2587       Diag(New->getLocation(), diag::err_late_asm_label_name)
2588         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2589     }
2590   }
2591 
2592   // Re-declaration cannot add abi_tag's.
2593   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2594     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2595       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2596         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2597                       NewTag) == OldAbiTagAttr->tags_end()) {
2598           Diag(NewAbiTagAttr->getLocation(),
2599                diag::err_new_abi_tag_on_redeclaration)
2600               << NewTag;
2601           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2602         }
2603       }
2604     } else {
2605       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2606       Diag(Old->getLocation(), diag::note_previous_declaration);
2607     }
2608   }
2609 
2610   // This redeclaration adds a section attribute.
2611   if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2612     if (auto *VD = dyn_cast<VarDecl>(New)) {
2613       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2614         Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2615         Diag(Old->getLocation(), diag::note_previous_declaration);
2616       }
2617     }
2618   }
2619 
2620   if (!Old->hasAttrs())
2621     return;
2622 
2623   bool foundAny = New->hasAttrs();
2624 
2625   // Ensure that any moving of objects within the allocated map is done before
2626   // we process them.
2627   if (!foundAny) New->setAttrs(AttrVec());
2628 
2629   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2630     // Ignore deprecated/unavailable/availability attributes if requested.
2631     AvailabilityMergeKind LocalAMK = AMK_None;
2632     if (isa<DeprecatedAttr>(I) ||
2633         isa<UnavailableAttr>(I) ||
2634         isa<AvailabilityAttr>(I)) {
2635       switch (AMK) {
2636       case AMK_None:
2637         continue;
2638 
2639       case AMK_Redeclaration:
2640       case AMK_Override:
2641       case AMK_ProtocolImplementation:
2642         LocalAMK = AMK;
2643         break;
2644       }
2645     }
2646 
2647     // Already handled.
2648     if (isa<UsedAttr>(I))
2649       continue;
2650 
2651     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2652       foundAny = true;
2653   }
2654 
2655   if (mergeAlignedAttrs(*this, New, Old))
2656     foundAny = true;
2657 
2658   if (!foundAny) New->dropAttrs();
2659 }
2660 
2661 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2662 /// to the new one.
2663 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2664                                      const ParmVarDecl *oldDecl,
2665                                      Sema &S) {
2666   // C++11 [dcl.attr.depend]p2:
2667   //   The first declaration of a function shall specify the
2668   //   carries_dependency attribute for its declarator-id if any declaration
2669   //   of the function specifies the carries_dependency attribute.
2670   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2671   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2672     S.Diag(CDA->getLocation(),
2673            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2674     // Find the first declaration of the parameter.
2675     // FIXME: Should we build redeclaration chains for function parameters?
2676     const FunctionDecl *FirstFD =
2677       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2678     const ParmVarDecl *FirstVD =
2679       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2680     S.Diag(FirstVD->getLocation(),
2681            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2682   }
2683 
2684   if (!oldDecl->hasAttrs())
2685     return;
2686 
2687   bool foundAny = newDecl->hasAttrs();
2688 
2689   // Ensure that any moving of objects within the allocated map is
2690   // done before we process them.
2691   if (!foundAny) newDecl->setAttrs(AttrVec());
2692 
2693   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2694     if (!DeclHasAttr(newDecl, I)) {
2695       InheritableAttr *newAttr =
2696         cast<InheritableParamAttr>(I->clone(S.Context));
2697       newAttr->setInherited(true);
2698       newDecl->addAttr(newAttr);
2699       foundAny = true;
2700     }
2701   }
2702 
2703   if (!foundAny) newDecl->dropAttrs();
2704 }
2705 
2706 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2707                                 const ParmVarDecl *OldParam,
2708                                 Sema &S) {
2709   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2710     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2711       if (*Oldnullability != *Newnullability) {
2712         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2713           << DiagNullabilityKind(
2714                *Newnullability,
2715                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2716                 != 0))
2717           << DiagNullabilityKind(
2718                *Oldnullability,
2719                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2720                 != 0));
2721         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2722       }
2723     } else {
2724       QualType NewT = NewParam->getType();
2725       NewT = S.Context.getAttributedType(
2726                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2727                          NewT, NewT);
2728       NewParam->setType(NewT);
2729     }
2730   }
2731 }
2732 
2733 namespace {
2734 
2735 /// Used in MergeFunctionDecl to keep track of function parameters in
2736 /// C.
2737 struct GNUCompatibleParamWarning {
2738   ParmVarDecl *OldParm;
2739   ParmVarDecl *NewParm;
2740   QualType PromotedType;
2741 };
2742 
2743 } // end anonymous namespace
2744 
2745 /// getSpecialMember - get the special member enum for a method.
2746 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2747   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2748     if (Ctor->isDefaultConstructor())
2749       return Sema::CXXDefaultConstructor;
2750 
2751     if (Ctor->isCopyConstructor())
2752       return Sema::CXXCopyConstructor;
2753 
2754     if (Ctor->isMoveConstructor())
2755       return Sema::CXXMoveConstructor;
2756   } else if (isa<CXXDestructorDecl>(MD)) {
2757     return Sema::CXXDestructor;
2758   } else if (MD->isCopyAssignmentOperator()) {
2759     return Sema::CXXCopyAssignment;
2760   } else if (MD->isMoveAssignmentOperator()) {
2761     return Sema::CXXMoveAssignment;
2762   }
2763 
2764   return Sema::CXXInvalid;
2765 }
2766 
2767 // Determine whether the previous declaration was a definition, implicit
2768 // declaration, or a declaration.
2769 template <typename T>
2770 static std::pair<diag::kind, SourceLocation>
2771 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2772   diag::kind PrevDiag;
2773   SourceLocation OldLocation = Old->getLocation();
2774   if (Old->isThisDeclarationADefinition())
2775     PrevDiag = diag::note_previous_definition;
2776   else if (Old->isImplicit()) {
2777     PrevDiag = diag::note_previous_implicit_declaration;
2778     if (OldLocation.isInvalid())
2779       OldLocation = New->getLocation();
2780   } else
2781     PrevDiag = diag::note_previous_declaration;
2782   return std::make_pair(PrevDiag, OldLocation);
2783 }
2784 
2785 /// canRedefineFunction - checks if a function can be redefined. Currently,
2786 /// only extern inline functions can be redefined, and even then only in
2787 /// GNU89 mode.
2788 static bool canRedefineFunction(const FunctionDecl *FD,
2789                                 const LangOptions& LangOpts) {
2790   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2791           !LangOpts.CPlusPlus &&
2792           FD->isInlineSpecified() &&
2793           FD->getStorageClass() == SC_Extern);
2794 }
2795 
2796 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2797   const AttributedType *AT = T->getAs<AttributedType>();
2798   while (AT && !AT->isCallingConv())
2799     AT = AT->getModifiedType()->getAs<AttributedType>();
2800   return AT;
2801 }
2802 
2803 template <typename T>
2804 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2805   const DeclContext *DC = Old->getDeclContext();
2806   if (DC->isRecord())
2807     return false;
2808 
2809   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2810   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2811     return true;
2812   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2813     return true;
2814   return false;
2815 }
2816 
2817 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2818 static bool isExternC(VarTemplateDecl *) { return false; }
2819 
2820 /// \brief Check whether a redeclaration of an entity introduced by a
2821 /// using-declaration is valid, given that we know it's not an overload
2822 /// (nor a hidden tag declaration).
2823 template<typename ExpectedDecl>
2824 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2825                                    ExpectedDecl *New) {
2826   // C++11 [basic.scope.declarative]p4:
2827   //   Given a set of declarations in a single declarative region, each of
2828   //   which specifies the same unqualified name,
2829   //   -- they shall all refer to the same entity, or all refer to functions
2830   //      and function templates; or
2831   //   -- exactly one declaration shall declare a class name or enumeration
2832   //      name that is not a typedef name and the other declarations shall all
2833   //      refer to the same variable or enumerator, or all refer to functions
2834   //      and function templates; in this case the class name or enumeration
2835   //      name is hidden (3.3.10).
2836 
2837   // C++11 [namespace.udecl]p14:
2838   //   If a function declaration in namespace scope or block scope has the
2839   //   same name and the same parameter-type-list as a function introduced
2840   //   by a using-declaration, and the declarations do not declare the same
2841   //   function, the program is ill-formed.
2842 
2843   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2844   if (Old &&
2845       !Old->getDeclContext()->getRedeclContext()->Equals(
2846           New->getDeclContext()->getRedeclContext()) &&
2847       !(isExternC(Old) && isExternC(New)))
2848     Old = nullptr;
2849 
2850   if (!Old) {
2851     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2852     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2853     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2854     return true;
2855   }
2856   return false;
2857 }
2858 
2859 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2860                                             const FunctionDecl *B) {
2861   assert(A->getNumParams() == B->getNumParams());
2862 
2863   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2864     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2865     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2866     if (AttrA == AttrB)
2867       return true;
2868     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2869   };
2870 
2871   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2872 }
2873 
2874 /// MergeFunctionDecl - We just parsed a function 'New' from
2875 /// declarator D which has the same name and scope as a previous
2876 /// declaration 'Old'.  Figure out how to resolve this situation,
2877 /// merging decls or emitting diagnostics as appropriate.
2878 ///
2879 /// In C++, New and Old must be declarations that are not
2880 /// overloaded. Use IsOverload to determine whether New and Old are
2881 /// overloaded, and to select the Old declaration that New should be
2882 /// merged with.
2883 ///
2884 /// Returns true if there was an error, false otherwise.
2885 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2886                              Scope *S, bool MergeTypeWithOld) {
2887   // Verify the old decl was also a function.
2888   FunctionDecl *Old = OldD->getAsFunction();
2889   if (!Old) {
2890     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2891       if (New->getFriendObjectKind()) {
2892         Diag(New->getLocation(), diag::err_using_decl_friend);
2893         Diag(Shadow->getTargetDecl()->getLocation(),
2894              diag::note_using_decl_target);
2895         Diag(Shadow->getUsingDecl()->getLocation(),
2896              diag::note_using_decl) << 0;
2897         return true;
2898       }
2899 
2900       // Check whether the two declarations might declare the same function.
2901       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2902         return true;
2903       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2904     } else {
2905       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2906         << New->getDeclName();
2907       notePreviousDefinition(OldD, New->getLocation());
2908       return true;
2909     }
2910   }
2911 
2912   // If the old declaration is invalid, just give up here.
2913   if (Old->isInvalidDecl())
2914     return true;
2915 
2916   diag::kind PrevDiag;
2917   SourceLocation OldLocation;
2918   std::tie(PrevDiag, OldLocation) =
2919       getNoteDiagForInvalidRedeclaration(Old, New);
2920 
2921   // Don't complain about this if we're in GNU89 mode and the old function
2922   // is an extern inline function.
2923   // Don't complain about specializations. They are not supposed to have
2924   // storage classes.
2925   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2926       New->getStorageClass() == SC_Static &&
2927       Old->hasExternalFormalLinkage() &&
2928       !New->getTemplateSpecializationInfo() &&
2929       !canRedefineFunction(Old, getLangOpts())) {
2930     if (getLangOpts().MicrosoftExt) {
2931       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2932       Diag(OldLocation, PrevDiag);
2933     } else {
2934       Diag(New->getLocation(), diag::err_static_non_static) << New;
2935       Diag(OldLocation, PrevDiag);
2936       return true;
2937     }
2938   }
2939 
2940   if (New->hasAttr<InternalLinkageAttr>() &&
2941       !Old->hasAttr<InternalLinkageAttr>()) {
2942     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2943         << New->getDeclName();
2944     notePreviousDefinition(Old, New->getLocation());
2945     New->dropAttr<InternalLinkageAttr>();
2946   }
2947 
2948   if (!getLangOpts().CPlusPlus) {
2949     bool OldOvl = Old->hasAttr<OverloadableAttr>();
2950     if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
2951       Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
2952         << New << OldOvl;
2953 
2954       // Try our best to find a decl that actually has the overloadable
2955       // attribute for the note. In most cases (e.g. programs with only one
2956       // broken declaration/definition), this won't matter.
2957       //
2958       // FIXME: We could do this if we juggled some extra state in
2959       // OverloadableAttr, rather than just removing it.
2960       const Decl *DiagOld = Old;
2961       if (OldOvl) {
2962         auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
2963           const auto *A = D->getAttr<OverloadableAttr>();
2964           return A && !A->isImplicit();
2965         });
2966         // If we've implicitly added *all* of the overloadable attrs to this
2967         // chain, emitting a "previous redecl" note is pointless.
2968         DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
2969       }
2970 
2971       if (DiagOld)
2972         Diag(DiagOld->getLocation(),
2973              diag::note_attribute_overloadable_prev_overload)
2974           << OldOvl;
2975 
2976       if (OldOvl)
2977         New->addAttr(OverloadableAttr::CreateImplicit(Context));
2978       else
2979         New->dropAttr<OverloadableAttr>();
2980     }
2981   }
2982 
2983   // If a function is first declared with a calling convention, but is later
2984   // declared or defined without one, all following decls assume the calling
2985   // convention of the first.
2986   //
2987   // It's OK if a function is first declared without a calling convention,
2988   // but is later declared or defined with the default calling convention.
2989   //
2990   // To test if either decl has an explicit calling convention, we look for
2991   // AttributedType sugar nodes on the type as written.  If they are missing or
2992   // were canonicalized away, we assume the calling convention was implicit.
2993   //
2994   // Note also that we DO NOT return at this point, because we still have
2995   // other tests to run.
2996   QualType OldQType = Context.getCanonicalType(Old->getType());
2997   QualType NewQType = Context.getCanonicalType(New->getType());
2998   const FunctionType *OldType = cast<FunctionType>(OldQType);
2999   const FunctionType *NewType = cast<FunctionType>(NewQType);
3000   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3001   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3002   bool RequiresAdjustment = false;
3003 
3004   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3005     FunctionDecl *First = Old->getFirstDecl();
3006     const FunctionType *FT =
3007         First->getType().getCanonicalType()->castAs<FunctionType>();
3008     FunctionType::ExtInfo FI = FT->getExtInfo();
3009     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3010     if (!NewCCExplicit) {
3011       // Inherit the CC from the previous declaration if it was specified
3012       // there but not here.
3013       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3014       RequiresAdjustment = true;
3015     } else {
3016       // Calling conventions aren't compatible, so complain.
3017       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3018       Diag(New->getLocation(), diag::err_cconv_change)
3019         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3020         << !FirstCCExplicit
3021         << (!FirstCCExplicit ? "" :
3022             FunctionType::getNameForCallConv(FI.getCC()));
3023 
3024       // Put the note on the first decl, since it is the one that matters.
3025       Diag(First->getLocation(), diag::note_previous_declaration);
3026       return true;
3027     }
3028   }
3029 
3030   // FIXME: diagnose the other way around?
3031   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3032     NewTypeInfo = NewTypeInfo.withNoReturn(true);
3033     RequiresAdjustment = true;
3034   }
3035 
3036   // Merge regparm attribute.
3037   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3038       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3039     if (NewTypeInfo.getHasRegParm()) {
3040       Diag(New->getLocation(), diag::err_regparm_mismatch)
3041         << NewType->getRegParmType()
3042         << OldType->getRegParmType();
3043       Diag(OldLocation, diag::note_previous_declaration);
3044       return true;
3045     }
3046 
3047     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3048     RequiresAdjustment = true;
3049   }
3050 
3051   // Merge ns_returns_retained attribute.
3052   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3053     if (NewTypeInfo.getProducesResult()) {
3054       Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3055           << "'ns_returns_retained'";
3056       Diag(OldLocation, diag::note_previous_declaration);
3057       return true;
3058     }
3059 
3060     NewTypeInfo = NewTypeInfo.withProducesResult(true);
3061     RequiresAdjustment = true;
3062   }
3063 
3064   if (OldTypeInfo.getNoCallerSavedRegs() !=
3065       NewTypeInfo.getNoCallerSavedRegs()) {
3066     if (NewTypeInfo.getNoCallerSavedRegs()) {
3067       AnyX86NoCallerSavedRegistersAttr *Attr =
3068         New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3069       Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3070       Diag(OldLocation, diag::note_previous_declaration);
3071       return true;
3072     }
3073 
3074     NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3075     RequiresAdjustment = true;
3076   }
3077 
3078   if (RequiresAdjustment) {
3079     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3080     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3081     New->setType(QualType(AdjustedType, 0));
3082     NewQType = Context.getCanonicalType(New->getType());
3083     NewType = cast<FunctionType>(NewQType);
3084   }
3085 
3086   // If this redeclaration makes the function inline, we may need to add it to
3087   // UndefinedButUsed.
3088   if (!Old->isInlined() && New->isInlined() &&
3089       !New->hasAttr<GNUInlineAttr>() &&
3090       !getLangOpts().GNUInline &&
3091       Old->isUsed(false) &&
3092       !Old->isDefined() && !New->isThisDeclarationADefinition())
3093     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3094                                            SourceLocation()));
3095 
3096   // If this redeclaration makes it newly gnu_inline, we don't want to warn
3097   // about it.
3098   if (New->hasAttr<GNUInlineAttr>() &&
3099       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3100     UndefinedButUsed.erase(Old->getCanonicalDecl());
3101   }
3102 
3103   // If pass_object_size params don't match up perfectly, this isn't a valid
3104   // redeclaration.
3105   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3106       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3107     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3108         << New->getDeclName();
3109     Diag(OldLocation, PrevDiag) << Old << Old->getType();
3110     return true;
3111   }
3112 
3113   if (getLangOpts().CPlusPlus) {
3114     // C++1z [over.load]p2
3115     //   Certain function declarations cannot be overloaded:
3116     //     -- Function declarations that differ only in the return type,
3117     //        the exception specification, or both cannot be overloaded.
3118 
3119     // Check the exception specifications match. This may recompute the type of
3120     // both Old and New if it resolved exception specifications, so grab the
3121     // types again after this. Because this updates the type, we do this before
3122     // any of the other checks below, which may update the "de facto" NewQType
3123     // but do not necessarily update the type of New.
3124     if (CheckEquivalentExceptionSpec(Old, New))
3125       return true;
3126     OldQType = Context.getCanonicalType(Old->getType());
3127     NewQType = Context.getCanonicalType(New->getType());
3128 
3129     // Go back to the type source info to compare the declared return types,
3130     // per C++1y [dcl.type.auto]p13:
3131     //   Redeclarations or specializations of a function or function template
3132     //   with a declared return type that uses a placeholder type shall also
3133     //   use that placeholder, not a deduced type.
3134     QualType OldDeclaredReturnType =
3135         (Old->getTypeSourceInfo()
3136              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3137              : OldType)->getReturnType();
3138     QualType NewDeclaredReturnType =
3139         (New->getTypeSourceInfo()
3140              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3141              : NewType)->getReturnType();
3142     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3143         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3144           New->isLocalExternDecl())) {
3145       QualType ResQT;
3146       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3147           OldDeclaredReturnType->isObjCObjectPointerType())
3148         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3149       if (ResQT.isNull()) {
3150         if (New->isCXXClassMember() && New->isOutOfLine())
3151           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3152               << New << New->getReturnTypeSourceRange();
3153         else
3154           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3155               << New->getReturnTypeSourceRange();
3156         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3157                                     << Old->getReturnTypeSourceRange();
3158         return true;
3159       }
3160       else
3161         NewQType = ResQT;
3162     }
3163 
3164     QualType OldReturnType = OldType->getReturnType();
3165     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3166     if (OldReturnType != NewReturnType) {
3167       // If this function has a deduced return type and has already been
3168       // defined, copy the deduced value from the old declaration.
3169       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3170       if (OldAT && OldAT->isDeduced()) {
3171         New->setType(
3172             SubstAutoType(New->getType(),
3173                           OldAT->isDependentType() ? Context.DependentTy
3174                                                    : OldAT->getDeducedType()));
3175         NewQType = Context.getCanonicalType(
3176             SubstAutoType(NewQType,
3177                           OldAT->isDependentType() ? Context.DependentTy
3178                                                    : OldAT->getDeducedType()));
3179       }
3180     }
3181 
3182     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3183     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3184     if (OldMethod && NewMethod) {
3185       // Preserve triviality.
3186       NewMethod->setTrivial(OldMethod->isTrivial());
3187 
3188       // MSVC allows explicit template specialization at class scope:
3189       // 2 CXXMethodDecls referring to the same function will be injected.
3190       // We don't want a redeclaration error.
3191       bool IsClassScopeExplicitSpecialization =
3192                               OldMethod->isFunctionTemplateSpecialization() &&
3193                               NewMethod->isFunctionTemplateSpecialization();
3194       bool isFriend = NewMethod->getFriendObjectKind();
3195 
3196       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3197           !IsClassScopeExplicitSpecialization) {
3198         //    -- Member function declarations with the same name and the
3199         //       same parameter types cannot be overloaded if any of them
3200         //       is a static member function declaration.
3201         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3202           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3203           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3204           return true;
3205         }
3206 
3207         // C++ [class.mem]p1:
3208         //   [...] A member shall not be declared twice in the
3209         //   member-specification, except that a nested class or member
3210         //   class template can be declared and then later defined.
3211         if (!inTemplateInstantiation()) {
3212           unsigned NewDiag;
3213           if (isa<CXXConstructorDecl>(OldMethod))
3214             NewDiag = diag::err_constructor_redeclared;
3215           else if (isa<CXXDestructorDecl>(NewMethod))
3216             NewDiag = diag::err_destructor_redeclared;
3217           else if (isa<CXXConversionDecl>(NewMethod))
3218             NewDiag = diag::err_conv_function_redeclared;
3219           else
3220             NewDiag = diag::err_member_redeclared;
3221 
3222           Diag(New->getLocation(), NewDiag);
3223         } else {
3224           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3225             << New << New->getType();
3226         }
3227         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3228         return true;
3229 
3230       // Complain if this is an explicit declaration of a special
3231       // member that was initially declared implicitly.
3232       //
3233       // As an exception, it's okay to befriend such methods in order
3234       // to permit the implicit constructor/destructor/operator calls.
3235       } else if (OldMethod->isImplicit()) {
3236         if (isFriend) {
3237           NewMethod->setImplicit();
3238         } else {
3239           Diag(NewMethod->getLocation(),
3240                diag::err_definition_of_implicitly_declared_member)
3241             << New << getSpecialMember(OldMethod);
3242           return true;
3243         }
3244       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3245         Diag(NewMethod->getLocation(),
3246              diag::err_definition_of_explicitly_defaulted_member)
3247           << getSpecialMember(OldMethod);
3248         return true;
3249       }
3250     }
3251 
3252     // C++11 [dcl.attr.noreturn]p1:
3253     //   The first declaration of a function shall specify the noreturn
3254     //   attribute if any declaration of that function specifies the noreturn
3255     //   attribute.
3256     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3257     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3258       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3259       Diag(Old->getFirstDecl()->getLocation(),
3260            diag::note_noreturn_missing_first_decl);
3261     }
3262 
3263     // C++11 [dcl.attr.depend]p2:
3264     //   The first declaration of a function shall specify the
3265     //   carries_dependency attribute for its declarator-id if any declaration
3266     //   of the function specifies the carries_dependency attribute.
3267     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3268     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3269       Diag(CDA->getLocation(),
3270            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3271       Diag(Old->getFirstDecl()->getLocation(),
3272            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3273     }
3274 
3275     // (C++98 8.3.5p3):
3276     //   All declarations for a function shall agree exactly in both the
3277     //   return type and the parameter-type-list.
3278     // We also want to respect all the extended bits except noreturn.
3279 
3280     // noreturn should now match unless the old type info didn't have it.
3281     QualType OldQTypeForComparison = OldQType;
3282     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3283       auto *OldType = OldQType->castAs<FunctionProtoType>();
3284       const FunctionType *OldTypeForComparison
3285         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3286       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3287       assert(OldQTypeForComparison.isCanonical());
3288     }
3289 
3290     if (haveIncompatibleLanguageLinkages(Old, New)) {
3291       // As a special case, retain the language linkage from previous
3292       // declarations of a friend function as an extension.
3293       //
3294       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3295       // and is useful because there's otherwise no way to specify language
3296       // linkage within class scope.
3297       //
3298       // Check cautiously as the friend object kind isn't yet complete.
3299       if (New->getFriendObjectKind() != Decl::FOK_None) {
3300         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3301         Diag(OldLocation, PrevDiag);
3302       } else {
3303         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3304         Diag(OldLocation, PrevDiag);
3305         return true;
3306       }
3307     }
3308 
3309     if (OldQTypeForComparison == NewQType)
3310       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3311 
3312     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3313         New->isLocalExternDecl()) {
3314       // It's OK if we couldn't merge types for a local function declaraton
3315       // if either the old or new type is dependent. We'll merge the types
3316       // when we instantiate the function.
3317       return false;
3318     }
3319 
3320     // Fall through for conflicting redeclarations and redefinitions.
3321   }
3322 
3323   // C: Function types need to be compatible, not identical. This handles
3324   // duplicate function decls like "void f(int); void f(enum X);" properly.
3325   if (!getLangOpts().CPlusPlus &&
3326       Context.typesAreCompatible(OldQType, NewQType)) {
3327     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3328     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3329     const FunctionProtoType *OldProto = nullptr;
3330     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3331         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3332       // The old declaration provided a function prototype, but the
3333       // new declaration does not. Merge in the prototype.
3334       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3335       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3336       NewQType =
3337           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3338                                   OldProto->getExtProtoInfo());
3339       New->setType(NewQType);
3340       New->setHasInheritedPrototype();
3341 
3342       // Synthesize parameters with the same types.
3343       SmallVector<ParmVarDecl*, 16> Params;
3344       for (const auto &ParamType : OldProto->param_types()) {
3345         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3346                                                  SourceLocation(), nullptr,
3347                                                  ParamType, /*TInfo=*/nullptr,
3348                                                  SC_None, nullptr);
3349         Param->setScopeInfo(0, Params.size());
3350         Param->setImplicit();
3351         Params.push_back(Param);
3352       }
3353 
3354       New->setParams(Params);
3355     }
3356 
3357     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3358   }
3359 
3360   // GNU C permits a K&R definition to follow a prototype declaration
3361   // if the declared types of the parameters in the K&R definition
3362   // match the types in the prototype declaration, even when the
3363   // promoted types of the parameters from the K&R definition differ
3364   // from the types in the prototype. GCC then keeps the types from
3365   // the prototype.
3366   //
3367   // If a variadic prototype is followed by a non-variadic K&R definition,
3368   // the K&R definition becomes variadic.  This is sort of an edge case, but
3369   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3370   // C99 6.9.1p8.
3371   if (!getLangOpts().CPlusPlus &&
3372       Old->hasPrototype() && !New->hasPrototype() &&
3373       New->getType()->getAs<FunctionProtoType>() &&
3374       Old->getNumParams() == New->getNumParams()) {
3375     SmallVector<QualType, 16> ArgTypes;
3376     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3377     const FunctionProtoType *OldProto
3378       = Old->getType()->getAs<FunctionProtoType>();
3379     const FunctionProtoType *NewProto
3380       = New->getType()->getAs<FunctionProtoType>();
3381 
3382     // Determine whether this is the GNU C extension.
3383     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3384                                                NewProto->getReturnType());
3385     bool LooseCompatible = !MergedReturn.isNull();
3386     for (unsigned Idx = 0, End = Old->getNumParams();
3387          LooseCompatible && Idx != End; ++Idx) {
3388       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3389       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3390       if (Context.typesAreCompatible(OldParm->getType(),
3391                                      NewProto->getParamType(Idx))) {
3392         ArgTypes.push_back(NewParm->getType());
3393       } else if (Context.typesAreCompatible(OldParm->getType(),
3394                                             NewParm->getType(),
3395                                             /*CompareUnqualified=*/true)) {
3396         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3397                                            NewProto->getParamType(Idx) };
3398         Warnings.push_back(Warn);
3399         ArgTypes.push_back(NewParm->getType());
3400       } else
3401         LooseCompatible = false;
3402     }
3403 
3404     if (LooseCompatible) {
3405       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3406         Diag(Warnings[Warn].NewParm->getLocation(),
3407              diag::ext_param_promoted_not_compatible_with_prototype)
3408           << Warnings[Warn].PromotedType
3409           << Warnings[Warn].OldParm->getType();
3410         if (Warnings[Warn].OldParm->getLocation().isValid())
3411           Diag(Warnings[Warn].OldParm->getLocation(),
3412                diag::note_previous_declaration);
3413       }
3414 
3415       if (MergeTypeWithOld)
3416         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3417                                              OldProto->getExtProtoInfo()));
3418       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3419     }
3420 
3421     // Fall through to diagnose conflicting types.
3422   }
3423 
3424   // A function that has already been declared has been redeclared or
3425   // defined with a different type; show an appropriate diagnostic.
3426 
3427   // If the previous declaration was an implicitly-generated builtin
3428   // declaration, then at the very least we should use a specialized note.
3429   unsigned BuiltinID;
3430   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3431     // If it's actually a library-defined builtin function like 'malloc'
3432     // or 'printf', just warn about the incompatible redeclaration.
3433     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3434       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3435       Diag(OldLocation, diag::note_previous_builtin_declaration)
3436         << Old << Old->getType();
3437 
3438       // If this is a global redeclaration, just forget hereafter
3439       // about the "builtin-ness" of the function.
3440       //
3441       // Doing this for local extern declarations is problematic.  If
3442       // the builtin declaration remains visible, a second invalid
3443       // local declaration will produce a hard error; if it doesn't
3444       // remain visible, a single bogus local redeclaration (which is
3445       // actually only a warning) could break all the downstream code.
3446       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3447         New->getIdentifier()->revertBuiltin();
3448 
3449       return false;
3450     }
3451 
3452     PrevDiag = diag::note_previous_builtin_declaration;
3453   }
3454 
3455   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3456   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3457   return true;
3458 }
3459 
3460 /// \brief Completes the merge of two function declarations that are
3461 /// known to be compatible.
3462 ///
3463 /// This routine handles the merging of attributes and other
3464 /// properties of function declarations from the old declaration to
3465 /// the new declaration, once we know that New is in fact a
3466 /// redeclaration of Old.
3467 ///
3468 /// \returns false
3469 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3470                                         Scope *S, bool MergeTypeWithOld) {
3471   // Merge the attributes
3472   mergeDeclAttributes(New, Old);
3473 
3474   // Merge "pure" flag.
3475   if (Old->isPure())
3476     New->setPure();
3477 
3478   // Merge "used" flag.
3479   if (Old->getMostRecentDecl()->isUsed(false))
3480     New->setIsUsed();
3481 
3482   // Merge attributes from the parameters.  These can mismatch with K&R
3483   // declarations.
3484   if (New->getNumParams() == Old->getNumParams())
3485       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3486         ParmVarDecl *NewParam = New->getParamDecl(i);
3487         ParmVarDecl *OldParam = Old->getParamDecl(i);
3488         mergeParamDeclAttributes(NewParam, OldParam, *this);
3489         mergeParamDeclTypes(NewParam, OldParam, *this);
3490       }
3491 
3492   if (getLangOpts().CPlusPlus)
3493     return MergeCXXFunctionDecl(New, Old, S);
3494 
3495   // Merge the function types so the we get the composite types for the return
3496   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3497   // was visible.
3498   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3499   if (!Merged.isNull() && MergeTypeWithOld)
3500     New->setType(Merged);
3501 
3502   return false;
3503 }
3504 
3505 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3506                                 ObjCMethodDecl *oldMethod) {
3507   // Merge the attributes, including deprecated/unavailable
3508   AvailabilityMergeKind MergeKind =
3509     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3510       ? AMK_ProtocolImplementation
3511       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3512                                                        : AMK_Override;
3513 
3514   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3515 
3516   // Merge attributes from the parameters.
3517   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3518                                        oe = oldMethod->param_end();
3519   for (ObjCMethodDecl::param_iterator
3520          ni = newMethod->param_begin(), ne = newMethod->param_end();
3521        ni != ne && oi != oe; ++ni, ++oi)
3522     mergeParamDeclAttributes(*ni, *oi, *this);
3523 
3524   CheckObjCMethodOverride(newMethod, oldMethod);
3525 }
3526 
3527 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3528   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3529 
3530   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3531          ? diag::err_redefinition_different_type
3532          : diag::err_redeclaration_different_type)
3533     << New->getDeclName() << New->getType() << Old->getType();
3534 
3535   diag::kind PrevDiag;
3536   SourceLocation OldLocation;
3537   std::tie(PrevDiag, OldLocation)
3538     = getNoteDiagForInvalidRedeclaration(Old, New);
3539   S.Diag(OldLocation, PrevDiag);
3540   New->setInvalidDecl();
3541 }
3542 
3543 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3544 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3545 /// emitting diagnostics as appropriate.
3546 ///
3547 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3548 /// to here in AddInitializerToDecl. We can't check them before the initializer
3549 /// is attached.
3550 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3551                              bool MergeTypeWithOld) {
3552   if (New->isInvalidDecl() || Old->isInvalidDecl())
3553     return;
3554 
3555   QualType MergedT;
3556   if (getLangOpts().CPlusPlus) {
3557     if (New->getType()->isUndeducedType()) {
3558       // We don't know what the new type is until the initializer is attached.
3559       return;
3560     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3561       // These could still be something that needs exception specs checked.
3562       return MergeVarDeclExceptionSpecs(New, Old);
3563     }
3564     // C++ [basic.link]p10:
3565     //   [...] the types specified by all declarations referring to a given
3566     //   object or function shall be identical, except that declarations for an
3567     //   array object can specify array types that differ by the presence or
3568     //   absence of a major array bound (8.3.4).
3569     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3570       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3571       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3572 
3573       // We are merging a variable declaration New into Old. If it has an array
3574       // bound, and that bound differs from Old's bound, we should diagnose the
3575       // mismatch.
3576       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3577         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3578              PrevVD = PrevVD->getPreviousDecl()) {
3579           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3580           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3581             continue;
3582 
3583           if (!Context.hasSameType(NewArray, PrevVDTy))
3584             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3585         }
3586       }
3587 
3588       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3589         if (Context.hasSameType(OldArray->getElementType(),
3590                                 NewArray->getElementType()))
3591           MergedT = New->getType();
3592       }
3593       // FIXME: Check visibility. New is hidden but has a complete type. If New
3594       // has no array bound, it should not inherit one from Old, if Old is not
3595       // visible.
3596       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3597         if (Context.hasSameType(OldArray->getElementType(),
3598                                 NewArray->getElementType()))
3599           MergedT = Old->getType();
3600       }
3601     }
3602     else if (New->getType()->isObjCObjectPointerType() &&
3603                Old->getType()->isObjCObjectPointerType()) {
3604       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3605                                               Old->getType());
3606     }
3607   } else {
3608     // C 6.2.7p2:
3609     //   All declarations that refer to the same object or function shall have
3610     //   compatible type.
3611     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3612   }
3613   if (MergedT.isNull()) {
3614     // It's OK if we couldn't merge types if either type is dependent, for a
3615     // block-scope variable. In other cases (static data members of class
3616     // templates, variable templates, ...), we require the types to be
3617     // equivalent.
3618     // FIXME: The C++ standard doesn't say anything about this.
3619     if ((New->getType()->isDependentType() ||
3620          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3621       // If the old type was dependent, we can't merge with it, so the new type
3622       // becomes dependent for now. We'll reproduce the original type when we
3623       // instantiate the TypeSourceInfo for the variable.
3624       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3625         New->setType(Context.DependentTy);
3626       return;
3627     }
3628     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3629   }
3630 
3631   // Don't actually update the type on the new declaration if the old
3632   // declaration was an extern declaration in a different scope.
3633   if (MergeTypeWithOld)
3634     New->setType(MergedT);
3635 }
3636 
3637 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3638                                   LookupResult &Previous) {
3639   // C11 6.2.7p4:
3640   //   For an identifier with internal or external linkage declared
3641   //   in a scope in which a prior declaration of that identifier is
3642   //   visible, if the prior declaration specifies internal or
3643   //   external linkage, the type of the identifier at the later
3644   //   declaration becomes the composite type.
3645   //
3646   // If the variable isn't visible, we do not merge with its type.
3647   if (Previous.isShadowed())
3648     return false;
3649 
3650   if (S.getLangOpts().CPlusPlus) {
3651     // C++11 [dcl.array]p3:
3652     //   If there is a preceding declaration of the entity in the same
3653     //   scope in which the bound was specified, an omitted array bound
3654     //   is taken to be the same as in that earlier declaration.
3655     return NewVD->isPreviousDeclInSameBlockScope() ||
3656            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3657             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3658   } else {
3659     // If the old declaration was function-local, don't merge with its
3660     // type unless we're in the same function.
3661     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3662            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3663   }
3664 }
3665 
3666 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3667 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3668 /// situation, merging decls or emitting diagnostics as appropriate.
3669 ///
3670 /// Tentative definition rules (C99 6.9.2p2) are checked by
3671 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3672 /// definitions here, since the initializer hasn't been attached.
3673 ///
3674 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3675   // If the new decl is already invalid, don't do any other checking.
3676   if (New->isInvalidDecl())
3677     return;
3678 
3679   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3680     return;
3681 
3682   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3683 
3684   // Verify the old decl was also a variable or variable template.
3685   VarDecl *Old = nullptr;
3686   VarTemplateDecl *OldTemplate = nullptr;
3687   if (Previous.isSingleResult()) {
3688     if (NewTemplate) {
3689       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3690       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3691 
3692       if (auto *Shadow =
3693               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3694         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3695           return New->setInvalidDecl();
3696     } else {
3697       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3698 
3699       if (auto *Shadow =
3700               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3701         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3702           return New->setInvalidDecl();
3703     }
3704   }
3705   if (!Old) {
3706     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3707         << New->getDeclName();
3708     notePreviousDefinition(Previous.getRepresentativeDecl(),
3709                            New->getLocation());
3710     return New->setInvalidDecl();
3711   }
3712 
3713   // Ensure the template parameters are compatible.
3714   if (NewTemplate &&
3715       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3716                                       OldTemplate->getTemplateParameters(),
3717                                       /*Complain=*/true, TPL_TemplateMatch))
3718     return New->setInvalidDecl();
3719 
3720   // C++ [class.mem]p1:
3721   //   A member shall not be declared twice in the member-specification [...]
3722   //
3723   // Here, we need only consider static data members.
3724   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3725     Diag(New->getLocation(), diag::err_duplicate_member)
3726       << New->getIdentifier();
3727     Diag(Old->getLocation(), diag::note_previous_declaration);
3728     New->setInvalidDecl();
3729   }
3730 
3731   mergeDeclAttributes(New, Old);
3732   // Warn if an already-declared variable is made a weak_import in a subsequent
3733   // declaration
3734   if (New->hasAttr<WeakImportAttr>() &&
3735       Old->getStorageClass() == SC_None &&
3736       !Old->hasAttr<WeakImportAttr>()) {
3737     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3738     notePreviousDefinition(Old, New->getLocation());
3739     // Remove weak_import attribute on new declaration.
3740     New->dropAttr<WeakImportAttr>();
3741   }
3742 
3743   if (New->hasAttr<InternalLinkageAttr>() &&
3744       !Old->hasAttr<InternalLinkageAttr>()) {
3745     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3746         << New->getDeclName();
3747     notePreviousDefinition(Old, New->getLocation());
3748     New->dropAttr<InternalLinkageAttr>();
3749   }
3750 
3751   // Merge the types.
3752   VarDecl *MostRecent = Old->getMostRecentDecl();
3753   if (MostRecent != Old) {
3754     MergeVarDeclTypes(New, MostRecent,
3755                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3756     if (New->isInvalidDecl())
3757       return;
3758   }
3759 
3760   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3761   if (New->isInvalidDecl())
3762     return;
3763 
3764   diag::kind PrevDiag;
3765   SourceLocation OldLocation;
3766   std::tie(PrevDiag, OldLocation) =
3767       getNoteDiagForInvalidRedeclaration(Old, New);
3768 
3769   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3770   if (New->getStorageClass() == SC_Static &&
3771       !New->isStaticDataMember() &&
3772       Old->hasExternalFormalLinkage()) {
3773     if (getLangOpts().MicrosoftExt) {
3774       Diag(New->getLocation(), diag::ext_static_non_static)
3775           << New->getDeclName();
3776       Diag(OldLocation, PrevDiag);
3777     } else {
3778       Diag(New->getLocation(), diag::err_static_non_static)
3779           << New->getDeclName();
3780       Diag(OldLocation, PrevDiag);
3781       return New->setInvalidDecl();
3782     }
3783   }
3784   // C99 6.2.2p4:
3785   //   For an identifier declared with the storage-class specifier
3786   //   extern in a scope in which a prior declaration of that
3787   //   identifier is visible,23) if the prior declaration specifies
3788   //   internal or external linkage, the linkage of the identifier at
3789   //   the later declaration is the same as the linkage specified at
3790   //   the prior declaration. If no prior declaration is visible, or
3791   //   if the prior declaration specifies no linkage, then the
3792   //   identifier has external linkage.
3793   if (New->hasExternalStorage() && Old->hasLinkage())
3794     /* Okay */;
3795   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3796            !New->isStaticDataMember() &&
3797            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3798     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3799     Diag(OldLocation, PrevDiag);
3800     return New->setInvalidDecl();
3801   }
3802 
3803   // Check if extern is followed by non-extern and vice-versa.
3804   if (New->hasExternalStorage() &&
3805       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3806     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3807     Diag(OldLocation, PrevDiag);
3808     return New->setInvalidDecl();
3809   }
3810   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3811       !New->hasExternalStorage()) {
3812     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3813     Diag(OldLocation, PrevDiag);
3814     return New->setInvalidDecl();
3815   }
3816 
3817   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3818 
3819   // FIXME: The test for external storage here seems wrong? We still
3820   // need to check for mismatches.
3821   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3822       // Don't complain about out-of-line definitions of static members.
3823       !(Old->getLexicalDeclContext()->isRecord() &&
3824         !New->getLexicalDeclContext()->isRecord())) {
3825     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3826     Diag(OldLocation, PrevDiag);
3827     return New->setInvalidDecl();
3828   }
3829 
3830   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3831     if (VarDecl *Def = Old->getDefinition()) {
3832       // C++1z [dcl.fcn.spec]p4:
3833       //   If the definition of a variable appears in a translation unit before
3834       //   its first declaration as inline, the program is ill-formed.
3835       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3836       Diag(Def->getLocation(), diag::note_previous_definition);
3837     }
3838   }
3839 
3840   // If this redeclaration makes the variable inline, we may need to add it to
3841   // UndefinedButUsed.
3842   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3843       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3844     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3845                                            SourceLocation()));
3846 
3847   if (New->getTLSKind() != Old->getTLSKind()) {
3848     if (!Old->getTLSKind()) {
3849       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3850       Diag(OldLocation, PrevDiag);
3851     } else if (!New->getTLSKind()) {
3852       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3853       Diag(OldLocation, PrevDiag);
3854     } else {
3855       // Do not allow redeclaration to change the variable between requiring
3856       // static and dynamic initialization.
3857       // FIXME: GCC allows this, but uses the TLS keyword on the first
3858       // declaration to determine the kind. Do we need to be compatible here?
3859       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3860         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3861       Diag(OldLocation, PrevDiag);
3862     }
3863   }
3864 
3865   // C++ doesn't have tentative definitions, so go right ahead and check here.
3866   if (getLangOpts().CPlusPlus &&
3867       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3868     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3869         Old->getCanonicalDecl()->isConstexpr()) {
3870       // This definition won't be a definition any more once it's been merged.
3871       Diag(New->getLocation(),
3872            diag::warn_deprecated_redundant_constexpr_static_def);
3873     } else if (VarDecl *Def = Old->getDefinition()) {
3874       if (checkVarDeclRedefinition(Def, New))
3875         return;
3876     }
3877   }
3878 
3879   if (haveIncompatibleLanguageLinkages(Old, New)) {
3880     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3881     Diag(OldLocation, PrevDiag);
3882     New->setInvalidDecl();
3883     return;
3884   }
3885 
3886   // Merge "used" flag.
3887   if (Old->getMostRecentDecl()->isUsed(false))
3888     New->setIsUsed();
3889 
3890   // Keep a chain of previous declarations.
3891   New->setPreviousDecl(Old);
3892   if (NewTemplate)
3893     NewTemplate->setPreviousDecl(OldTemplate);
3894 
3895   // Inherit access appropriately.
3896   New->setAccess(Old->getAccess());
3897   if (NewTemplate)
3898     NewTemplate->setAccess(New->getAccess());
3899 
3900   if (Old->isInline())
3901     New->setImplicitlyInline();
3902 }
3903 
3904 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3905   SourceManager &SrcMgr = getSourceManager();
3906   auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3907   auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3908   auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3909   auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3910   auto &HSI = PP.getHeaderSearchInfo();
3911   StringRef HdrFilename =
3912       SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3913 
3914   auto noteFromModuleOrInclude = [&](Module *Mod,
3915                                      SourceLocation IncLoc) -> bool {
3916     // Redefinition errors with modules are common with non modular mapped
3917     // headers, example: a non-modular header H in module A that also gets
3918     // included directly in a TU. Pointing twice to the same header/definition
3919     // is confusing, try to get better diagnostics when modules is on.
3920     if (IncLoc.isValid()) {
3921       if (Mod) {
3922         Diag(IncLoc, diag::note_redefinition_modules_same_file)
3923             << HdrFilename.str() << Mod->getFullModuleName();
3924         if (!Mod->DefinitionLoc.isInvalid())
3925           Diag(Mod->DefinitionLoc, diag::note_defined_here)
3926               << Mod->getFullModuleName();
3927       } else {
3928         Diag(IncLoc, diag::note_redefinition_include_same_file)
3929             << HdrFilename.str();
3930       }
3931       return true;
3932     }
3933 
3934     return false;
3935   };
3936 
3937   // Is it the same file and same offset? Provide more information on why
3938   // this leads to a redefinition error.
3939   bool EmittedDiag = false;
3940   if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3941     SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3942     SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3943     EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3944     EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3945 
3946     // If the header has no guards, emit a note suggesting one.
3947     if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3948       Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3949 
3950     if (EmittedDiag)
3951       return;
3952   }
3953 
3954   // Redefinition coming from different files or couldn't do better above.
3955   Diag(Old->getLocation(), diag::note_previous_definition);
3956 }
3957 
3958 /// We've just determined that \p Old and \p New both appear to be definitions
3959 /// of the same variable. Either diagnose or fix the problem.
3960 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3961   if (!hasVisibleDefinition(Old) &&
3962       (New->getFormalLinkage() == InternalLinkage ||
3963        New->isInline() ||
3964        New->getDescribedVarTemplate() ||
3965        New->getNumTemplateParameterLists() ||
3966        New->getDeclContext()->isDependentContext())) {
3967     // The previous definition is hidden, and multiple definitions are
3968     // permitted (in separate TUs). Demote this to a declaration.
3969     New->demoteThisDefinitionToDeclaration();
3970 
3971     // Make the canonical definition visible.
3972     if (auto *OldTD = Old->getDescribedVarTemplate())
3973       makeMergedDefinitionVisible(OldTD);
3974     makeMergedDefinitionVisible(Old);
3975     return false;
3976   } else {
3977     Diag(New->getLocation(), diag::err_redefinition) << New;
3978     notePreviousDefinition(Old, New->getLocation());
3979     New->setInvalidDecl();
3980     return true;
3981   }
3982 }
3983 
3984 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3985 /// no declarator (e.g. "struct foo;") is parsed.
3986 Decl *
3987 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3988                                  RecordDecl *&AnonRecord) {
3989   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3990                                     AnonRecord);
3991 }
3992 
3993 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3994 // disambiguate entities defined in different scopes.
3995 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3996 // compatibility.
3997 // We will pick our mangling number depending on which version of MSVC is being
3998 // targeted.
3999 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4000   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4001              ? S->getMSCurManglingNumber()
4002              : S->getMSLastManglingNumber();
4003 }
4004 
4005 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4006   if (!Context.getLangOpts().CPlusPlus)
4007     return;
4008 
4009   if (isa<CXXRecordDecl>(Tag->getParent())) {
4010     // If this tag is the direct child of a class, number it if
4011     // it is anonymous.
4012     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4013       return;
4014     MangleNumberingContext &MCtx =
4015         Context.getManglingNumberContext(Tag->getParent());
4016     Context.setManglingNumber(
4017         Tag, MCtx.getManglingNumber(
4018                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4019     return;
4020   }
4021 
4022   // If this tag isn't a direct child of a class, number it if it is local.
4023   Decl *ManglingContextDecl;
4024   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4025           Tag->getDeclContext(), ManglingContextDecl)) {
4026     Context.setManglingNumber(
4027         Tag, MCtx->getManglingNumber(
4028                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4029   }
4030 }
4031 
4032 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4033                                         TypedefNameDecl *NewTD) {
4034   if (TagFromDeclSpec->isInvalidDecl())
4035     return;
4036 
4037   // Do nothing if the tag already has a name for linkage purposes.
4038   if (TagFromDeclSpec->hasNameForLinkage())
4039     return;
4040 
4041   // A well-formed anonymous tag must always be a TUK_Definition.
4042   assert(TagFromDeclSpec->isThisDeclarationADefinition());
4043 
4044   // The type must match the tag exactly;  no qualifiers allowed.
4045   if (!Context.hasSameType(NewTD->getUnderlyingType(),
4046                            Context.getTagDeclType(TagFromDeclSpec))) {
4047     if (getLangOpts().CPlusPlus)
4048       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4049     return;
4050   }
4051 
4052   // If we've already computed linkage for the anonymous tag, then
4053   // adding a typedef name for the anonymous decl can change that
4054   // linkage, which might be a serious problem.  Diagnose this as
4055   // unsupported and ignore the typedef name.  TODO: we should
4056   // pursue this as a language defect and establish a formal rule
4057   // for how to handle it.
4058   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4059     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4060 
4061     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4062     tagLoc = getLocForEndOfToken(tagLoc);
4063 
4064     llvm::SmallString<40> textToInsert;
4065     textToInsert += ' ';
4066     textToInsert += NewTD->getIdentifier()->getName();
4067     Diag(tagLoc, diag::note_typedef_changes_linkage)
4068         << FixItHint::CreateInsertion(tagLoc, textToInsert);
4069     return;
4070   }
4071 
4072   // Otherwise, set this is the anon-decl typedef for the tag.
4073   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4074 }
4075 
4076 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4077   switch (T) {
4078   case DeclSpec::TST_class:
4079     return 0;
4080   case DeclSpec::TST_struct:
4081     return 1;
4082   case DeclSpec::TST_interface:
4083     return 2;
4084   case DeclSpec::TST_union:
4085     return 3;
4086   case DeclSpec::TST_enum:
4087     return 4;
4088   default:
4089     llvm_unreachable("unexpected type specifier");
4090   }
4091 }
4092 
4093 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4094 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4095 /// parameters to cope with template friend declarations.
4096 Decl *
4097 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4098                                  MultiTemplateParamsArg TemplateParams,
4099                                  bool IsExplicitInstantiation,
4100                                  RecordDecl *&AnonRecord) {
4101   Decl *TagD = nullptr;
4102   TagDecl *Tag = nullptr;
4103   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4104       DS.getTypeSpecType() == DeclSpec::TST_struct ||
4105       DS.getTypeSpecType() == DeclSpec::TST_interface ||
4106       DS.getTypeSpecType() == DeclSpec::TST_union ||
4107       DS.getTypeSpecType() == DeclSpec::TST_enum) {
4108     TagD = DS.getRepAsDecl();
4109 
4110     if (!TagD) // We probably had an error
4111       return nullptr;
4112 
4113     // Note that the above type specs guarantee that the
4114     // type rep is a Decl, whereas in many of the others
4115     // it's a Type.
4116     if (isa<TagDecl>(TagD))
4117       Tag = cast<TagDecl>(TagD);
4118     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4119       Tag = CTD->getTemplatedDecl();
4120   }
4121 
4122   if (Tag) {
4123     handleTagNumbering(Tag, S);
4124     Tag->setFreeStanding();
4125     if (Tag->isInvalidDecl())
4126       return Tag;
4127   }
4128 
4129   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4130     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4131     // or incomplete types shall not be restrict-qualified."
4132     if (TypeQuals & DeclSpec::TQ_restrict)
4133       Diag(DS.getRestrictSpecLoc(),
4134            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4135            << DS.getSourceRange();
4136   }
4137 
4138   if (DS.isInlineSpecified())
4139     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4140         << getLangOpts().CPlusPlus1z;
4141 
4142   if (DS.isConstexprSpecified()) {
4143     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4144     // and definitions of functions and variables.
4145     if (Tag)
4146       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4147           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4148     else
4149       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4150     // Don't emit warnings after this error.
4151     return TagD;
4152   }
4153 
4154   if (DS.isConceptSpecified()) {
4155     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4156     // either a function concept and its definition or a variable concept and
4157     // its initializer.
4158     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4159     return TagD;
4160   }
4161 
4162   DiagnoseFunctionSpecifiers(DS);
4163 
4164   if (DS.isFriendSpecified()) {
4165     // If we're dealing with a decl but not a TagDecl, assume that
4166     // whatever routines created it handled the friendship aspect.
4167     if (TagD && !Tag)
4168       return nullptr;
4169     return ActOnFriendTypeDecl(S, DS, TemplateParams);
4170   }
4171 
4172   const CXXScopeSpec &SS = DS.getTypeSpecScope();
4173   bool IsExplicitSpecialization =
4174     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4175   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4176       !IsExplicitInstantiation && !IsExplicitSpecialization &&
4177       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4178     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4179     // nested-name-specifier unless it is an explicit instantiation
4180     // or an explicit specialization.
4181     //
4182     // FIXME: We allow class template partial specializations here too, per the
4183     // obvious intent of DR1819.
4184     //
4185     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4186     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4187         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4188     return nullptr;
4189   }
4190 
4191   // Track whether this decl-specifier declares anything.
4192   bool DeclaresAnything = true;
4193 
4194   // Handle anonymous struct definitions.
4195   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4196     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4197         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4198       if (getLangOpts().CPlusPlus ||
4199           Record->getDeclContext()->isRecord()) {
4200         // If CurContext is a DeclContext that can contain statements,
4201         // RecursiveASTVisitor won't visit the decls that
4202         // BuildAnonymousStructOrUnion() will put into CurContext.
4203         // Also store them here so that they can be part of the
4204         // DeclStmt that gets created in this case.
4205         // FIXME: Also return the IndirectFieldDecls created by
4206         // BuildAnonymousStructOr union, for the same reason?
4207         if (CurContext->isFunctionOrMethod())
4208           AnonRecord = Record;
4209         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4210                                            Context.getPrintingPolicy());
4211       }
4212 
4213       DeclaresAnything = false;
4214     }
4215   }
4216 
4217   // C11 6.7.2.1p2:
4218   //   A struct-declaration that does not declare an anonymous structure or
4219   //   anonymous union shall contain a struct-declarator-list.
4220   //
4221   // This rule also existed in C89 and C99; the grammar for struct-declaration
4222   // did not permit a struct-declaration without a struct-declarator-list.
4223   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4224       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4225     // Check for Microsoft C extension: anonymous struct/union member.
4226     // Handle 2 kinds of anonymous struct/union:
4227     //   struct STRUCT;
4228     //   union UNION;
4229     // and
4230     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4231     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4232     if ((Tag && Tag->getDeclName()) ||
4233         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4234       RecordDecl *Record = nullptr;
4235       if (Tag)
4236         Record = dyn_cast<RecordDecl>(Tag);
4237       else if (const RecordType *RT =
4238                    DS.getRepAsType().get()->getAsStructureType())
4239         Record = RT->getDecl();
4240       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4241         Record = UT->getDecl();
4242 
4243       if (Record && getLangOpts().MicrosoftExt) {
4244         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4245           << Record->isUnion() << DS.getSourceRange();
4246         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4247       }
4248 
4249       DeclaresAnything = false;
4250     }
4251   }
4252 
4253   // Skip all the checks below if we have a type error.
4254   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4255       (TagD && TagD->isInvalidDecl()))
4256     return TagD;
4257 
4258   if (getLangOpts().CPlusPlus &&
4259       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4260     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4261       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4262           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4263         DeclaresAnything = false;
4264 
4265   if (!DS.isMissingDeclaratorOk()) {
4266     // Customize diagnostic for a typedef missing a name.
4267     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4268       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4269         << DS.getSourceRange();
4270     else
4271       DeclaresAnything = false;
4272   }
4273 
4274   if (DS.isModulePrivateSpecified() &&
4275       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4276     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4277       << Tag->getTagKind()
4278       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4279 
4280   ActOnDocumentableDecl(TagD);
4281 
4282   // C 6.7/2:
4283   //   A declaration [...] shall declare at least a declarator [...], a tag,
4284   //   or the members of an enumeration.
4285   // C++ [dcl.dcl]p3:
4286   //   [If there are no declarators], and except for the declaration of an
4287   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4288   //   names into the program, or shall redeclare a name introduced by a
4289   //   previous declaration.
4290   if (!DeclaresAnything) {
4291     // In C, we allow this as a (popular) extension / bug. Don't bother
4292     // producing further diagnostics for redundant qualifiers after this.
4293     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4294     return TagD;
4295   }
4296 
4297   // C++ [dcl.stc]p1:
4298   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4299   //   init-declarator-list of the declaration shall not be empty.
4300   // C++ [dcl.fct.spec]p1:
4301   //   If a cv-qualifier appears in a decl-specifier-seq, the
4302   //   init-declarator-list of the declaration shall not be empty.
4303   //
4304   // Spurious qualifiers here appear to be valid in C.
4305   unsigned DiagID = diag::warn_standalone_specifier;
4306   if (getLangOpts().CPlusPlus)
4307     DiagID = diag::ext_standalone_specifier;
4308 
4309   // Note that a linkage-specification sets a storage class, but
4310   // 'extern "C" struct foo;' is actually valid and not theoretically
4311   // useless.
4312   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4313     if (SCS == DeclSpec::SCS_mutable)
4314       // Since mutable is not a viable storage class specifier in C, there is
4315       // no reason to treat it as an extension. Instead, diagnose as an error.
4316       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4317     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4318       Diag(DS.getStorageClassSpecLoc(), DiagID)
4319         << DeclSpec::getSpecifierName(SCS);
4320   }
4321 
4322   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4323     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4324       << DeclSpec::getSpecifierName(TSCS);
4325   if (DS.getTypeQualifiers()) {
4326     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4327       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4328     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4329       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4330     // Restrict is covered above.
4331     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4332       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4333     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4334       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4335   }
4336 
4337   // Warn about ignored type attributes, for example:
4338   // __attribute__((aligned)) struct A;
4339   // Attributes should be placed after tag to apply to type declaration.
4340   if (!DS.getAttributes().empty()) {
4341     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4342     if (TypeSpecType == DeclSpec::TST_class ||
4343         TypeSpecType == DeclSpec::TST_struct ||
4344         TypeSpecType == DeclSpec::TST_interface ||
4345         TypeSpecType == DeclSpec::TST_union ||
4346         TypeSpecType == DeclSpec::TST_enum) {
4347       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4348            attrs = attrs->getNext())
4349         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4350             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4351     }
4352   }
4353 
4354   return TagD;
4355 }
4356 
4357 /// We are trying to inject an anonymous member into the given scope;
4358 /// check if there's an existing declaration that can't be overloaded.
4359 ///
4360 /// \return true if this is a forbidden redeclaration
4361 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4362                                          Scope *S,
4363                                          DeclContext *Owner,
4364                                          DeclarationName Name,
4365                                          SourceLocation NameLoc,
4366                                          bool IsUnion) {
4367   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4368                  Sema::ForRedeclaration);
4369   if (!SemaRef.LookupName(R, S)) return false;
4370 
4371   // Pick a representative declaration.
4372   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4373   assert(PrevDecl && "Expected a non-null Decl");
4374 
4375   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4376     return false;
4377 
4378   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4379     << IsUnion << Name;
4380   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4381 
4382   return true;
4383 }
4384 
4385 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4386 /// anonymous struct or union AnonRecord into the owning context Owner
4387 /// and scope S. This routine will be invoked just after we realize
4388 /// that an unnamed union or struct is actually an anonymous union or
4389 /// struct, e.g.,
4390 ///
4391 /// @code
4392 /// union {
4393 ///   int i;
4394 ///   float f;
4395 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4396 ///    // f into the surrounding scope.x
4397 /// @endcode
4398 ///
4399 /// This routine is recursive, injecting the names of nested anonymous
4400 /// structs/unions into the owning context and scope as well.
4401 static bool
4402 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4403                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4404                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4405   bool Invalid = false;
4406 
4407   // Look every FieldDecl and IndirectFieldDecl with a name.
4408   for (auto *D : AnonRecord->decls()) {
4409     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4410         cast<NamedDecl>(D)->getDeclName()) {
4411       ValueDecl *VD = cast<ValueDecl>(D);
4412       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4413                                        VD->getLocation(),
4414                                        AnonRecord->isUnion())) {
4415         // C++ [class.union]p2:
4416         //   The names of the members of an anonymous union shall be
4417         //   distinct from the names of any other entity in the
4418         //   scope in which the anonymous union is declared.
4419         Invalid = true;
4420       } else {
4421         // C++ [class.union]p2:
4422         //   For the purpose of name lookup, after the anonymous union
4423         //   definition, the members of the anonymous union are
4424         //   considered to have been defined in the scope in which the
4425         //   anonymous union is declared.
4426         unsigned OldChainingSize = Chaining.size();
4427         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4428           Chaining.append(IF->chain_begin(), IF->chain_end());
4429         else
4430           Chaining.push_back(VD);
4431 
4432         assert(Chaining.size() >= 2);
4433         NamedDecl **NamedChain =
4434           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4435         for (unsigned i = 0; i < Chaining.size(); i++)
4436           NamedChain[i] = Chaining[i];
4437 
4438         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4439             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4440             VD->getType(), {NamedChain, Chaining.size()});
4441 
4442         for (const auto *Attr : VD->attrs())
4443           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4444 
4445         IndirectField->setAccess(AS);
4446         IndirectField->setImplicit();
4447         SemaRef.PushOnScopeChains(IndirectField, S);
4448 
4449         // That includes picking up the appropriate access specifier.
4450         if (AS != AS_none) IndirectField->setAccess(AS);
4451 
4452         Chaining.resize(OldChainingSize);
4453       }
4454     }
4455   }
4456 
4457   return Invalid;
4458 }
4459 
4460 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4461 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4462 /// illegal input values are mapped to SC_None.
4463 static StorageClass
4464 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4465   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4466   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4467          "Parser allowed 'typedef' as storage class VarDecl.");
4468   switch (StorageClassSpec) {
4469   case DeclSpec::SCS_unspecified:    return SC_None;
4470   case DeclSpec::SCS_extern:
4471     if (DS.isExternInLinkageSpec())
4472       return SC_None;
4473     return SC_Extern;
4474   case DeclSpec::SCS_static:         return SC_Static;
4475   case DeclSpec::SCS_auto:           return SC_Auto;
4476   case DeclSpec::SCS_register:       return SC_Register;
4477   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4478     // Illegal SCSs map to None: error reporting is up to the caller.
4479   case DeclSpec::SCS_mutable:        // Fall through.
4480   case DeclSpec::SCS_typedef:        return SC_None;
4481   }
4482   llvm_unreachable("unknown storage class specifier");
4483 }
4484 
4485 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4486   assert(Record->hasInClassInitializer());
4487 
4488   for (const auto *I : Record->decls()) {
4489     const auto *FD = dyn_cast<FieldDecl>(I);
4490     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4491       FD = IFD->getAnonField();
4492     if (FD && FD->hasInClassInitializer())
4493       return FD->getLocation();
4494   }
4495 
4496   llvm_unreachable("couldn't find in-class initializer");
4497 }
4498 
4499 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4500                                       SourceLocation DefaultInitLoc) {
4501   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4502     return;
4503 
4504   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4505   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4506 }
4507 
4508 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4509                                       CXXRecordDecl *AnonUnion) {
4510   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4511     return;
4512 
4513   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4514 }
4515 
4516 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4517 /// anonymous structure or union. Anonymous unions are a C++ feature
4518 /// (C++ [class.union]) and a C11 feature; anonymous structures
4519 /// are a C11 feature and GNU C++ extension.
4520 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4521                                         AccessSpecifier AS,
4522                                         RecordDecl *Record,
4523                                         const PrintingPolicy &Policy) {
4524   DeclContext *Owner = Record->getDeclContext();
4525 
4526   // Diagnose whether this anonymous struct/union is an extension.
4527   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4528     Diag(Record->getLocation(), diag::ext_anonymous_union);
4529   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4530     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4531   else if (!Record->isUnion() && !getLangOpts().C11)
4532     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4533 
4534   // C and C++ require different kinds of checks for anonymous
4535   // structs/unions.
4536   bool Invalid = false;
4537   if (getLangOpts().CPlusPlus) {
4538     const char *PrevSpec = nullptr;
4539     unsigned DiagID;
4540     if (Record->isUnion()) {
4541       // C++ [class.union]p6:
4542       //   Anonymous unions declared in a named namespace or in the
4543       //   global namespace shall be declared static.
4544       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4545           (isa<TranslationUnitDecl>(Owner) ||
4546            (isa<NamespaceDecl>(Owner) &&
4547             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4548         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4549           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4550 
4551         // Recover by adding 'static'.
4552         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4553                                PrevSpec, DiagID, Policy);
4554       }
4555       // C++ [class.union]p6:
4556       //   A storage class is not allowed in a declaration of an
4557       //   anonymous union in a class scope.
4558       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4559                isa<RecordDecl>(Owner)) {
4560         Diag(DS.getStorageClassSpecLoc(),
4561              diag::err_anonymous_union_with_storage_spec)
4562           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4563 
4564         // Recover by removing the storage specifier.
4565         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4566                                SourceLocation(),
4567                                PrevSpec, DiagID, Context.getPrintingPolicy());
4568       }
4569     }
4570 
4571     // Ignore const/volatile/restrict qualifiers.
4572     if (DS.getTypeQualifiers()) {
4573       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4574         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4575           << Record->isUnion() << "const"
4576           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4577       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4578         Diag(DS.getVolatileSpecLoc(),
4579              diag::ext_anonymous_struct_union_qualified)
4580           << Record->isUnion() << "volatile"
4581           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4582       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4583         Diag(DS.getRestrictSpecLoc(),
4584              diag::ext_anonymous_struct_union_qualified)
4585           << Record->isUnion() << "restrict"
4586           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4587       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4588         Diag(DS.getAtomicSpecLoc(),
4589              diag::ext_anonymous_struct_union_qualified)
4590           << Record->isUnion() << "_Atomic"
4591           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4592       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4593         Diag(DS.getUnalignedSpecLoc(),
4594              diag::ext_anonymous_struct_union_qualified)
4595           << Record->isUnion() << "__unaligned"
4596           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4597 
4598       DS.ClearTypeQualifiers();
4599     }
4600 
4601     // C++ [class.union]p2:
4602     //   The member-specification of an anonymous union shall only
4603     //   define non-static data members. [Note: nested types and
4604     //   functions cannot be declared within an anonymous union. ]
4605     for (auto *Mem : Record->decls()) {
4606       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4607         // C++ [class.union]p3:
4608         //   An anonymous union shall not have private or protected
4609         //   members (clause 11).
4610         assert(FD->getAccess() != AS_none);
4611         if (FD->getAccess() != AS_public) {
4612           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4613             << Record->isUnion() << (FD->getAccess() == AS_protected);
4614           Invalid = true;
4615         }
4616 
4617         // C++ [class.union]p1
4618         //   An object of a class with a non-trivial constructor, a non-trivial
4619         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4620         //   assignment operator cannot be a member of a union, nor can an
4621         //   array of such objects.
4622         if (CheckNontrivialField(FD))
4623           Invalid = true;
4624       } else if (Mem->isImplicit()) {
4625         // Any implicit members are fine.
4626       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4627         // This is a type that showed up in an
4628         // elaborated-type-specifier inside the anonymous struct or
4629         // union, but which actually declares a type outside of the
4630         // anonymous struct or union. It's okay.
4631       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4632         if (!MemRecord->isAnonymousStructOrUnion() &&
4633             MemRecord->getDeclName()) {
4634           // Visual C++ allows type definition in anonymous struct or union.
4635           if (getLangOpts().MicrosoftExt)
4636             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4637               << Record->isUnion();
4638           else {
4639             // This is a nested type declaration.
4640             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4641               << Record->isUnion();
4642             Invalid = true;
4643           }
4644         } else {
4645           // This is an anonymous type definition within another anonymous type.
4646           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4647           // not part of standard C++.
4648           Diag(MemRecord->getLocation(),
4649                diag::ext_anonymous_record_with_anonymous_type)
4650             << Record->isUnion();
4651         }
4652       } else if (isa<AccessSpecDecl>(Mem)) {
4653         // Any access specifier is fine.
4654       } else if (isa<StaticAssertDecl>(Mem)) {
4655         // In C++1z, static_assert declarations are also fine.
4656       } else {
4657         // We have something that isn't a non-static data
4658         // member. Complain about it.
4659         unsigned DK = diag::err_anonymous_record_bad_member;
4660         if (isa<TypeDecl>(Mem))
4661           DK = diag::err_anonymous_record_with_type;
4662         else if (isa<FunctionDecl>(Mem))
4663           DK = diag::err_anonymous_record_with_function;
4664         else if (isa<VarDecl>(Mem))
4665           DK = diag::err_anonymous_record_with_static;
4666 
4667         // Visual C++ allows type definition in anonymous struct or union.
4668         if (getLangOpts().MicrosoftExt &&
4669             DK == diag::err_anonymous_record_with_type)
4670           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4671             << Record->isUnion();
4672         else {
4673           Diag(Mem->getLocation(), DK) << Record->isUnion();
4674           Invalid = true;
4675         }
4676       }
4677     }
4678 
4679     // C++11 [class.union]p8 (DR1460):
4680     //   At most one variant member of a union may have a
4681     //   brace-or-equal-initializer.
4682     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4683         Owner->isRecord())
4684       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4685                                 cast<CXXRecordDecl>(Record));
4686   }
4687 
4688   if (!Record->isUnion() && !Owner->isRecord()) {
4689     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4690       << getLangOpts().CPlusPlus;
4691     Invalid = true;
4692   }
4693 
4694   // Mock up a declarator.
4695   Declarator Dc(DS, Declarator::MemberContext);
4696   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4697   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4698 
4699   // Create a declaration for this anonymous struct/union.
4700   NamedDecl *Anon = nullptr;
4701   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4702     Anon = FieldDecl::Create(Context, OwningClass,
4703                              DS.getLocStart(),
4704                              Record->getLocation(),
4705                              /*IdentifierInfo=*/nullptr,
4706                              Context.getTypeDeclType(Record),
4707                              TInfo,
4708                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4709                              /*InitStyle=*/ICIS_NoInit);
4710     Anon->setAccess(AS);
4711     if (getLangOpts().CPlusPlus)
4712       FieldCollector->Add(cast<FieldDecl>(Anon));
4713   } else {
4714     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4715     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4716     if (SCSpec == DeclSpec::SCS_mutable) {
4717       // mutable can only appear on non-static class members, so it's always
4718       // an error here
4719       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4720       Invalid = true;
4721       SC = SC_None;
4722     }
4723 
4724     Anon = VarDecl::Create(Context, Owner,
4725                            DS.getLocStart(),
4726                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4727                            Context.getTypeDeclType(Record),
4728                            TInfo, SC);
4729 
4730     // Default-initialize the implicit variable. This initialization will be
4731     // trivial in almost all cases, except if a union member has an in-class
4732     // initializer:
4733     //   union { int n = 0; };
4734     ActOnUninitializedDecl(Anon);
4735   }
4736   Anon->setImplicit();
4737 
4738   // Mark this as an anonymous struct/union type.
4739   Record->setAnonymousStructOrUnion(true);
4740 
4741   // Add the anonymous struct/union object to the current
4742   // context. We'll be referencing this object when we refer to one of
4743   // its members.
4744   Owner->addDecl(Anon);
4745 
4746   // Inject the members of the anonymous struct/union into the owning
4747   // context and into the identifier resolver chain for name lookup
4748   // purposes.
4749   SmallVector<NamedDecl*, 2> Chain;
4750   Chain.push_back(Anon);
4751 
4752   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4753     Invalid = true;
4754 
4755   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4756     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4757       Decl *ManglingContextDecl;
4758       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4759               NewVD->getDeclContext(), ManglingContextDecl)) {
4760         Context.setManglingNumber(
4761             NewVD, MCtx->getManglingNumber(
4762                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4763         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4764       }
4765     }
4766   }
4767 
4768   if (Invalid)
4769     Anon->setInvalidDecl();
4770 
4771   return Anon;
4772 }
4773 
4774 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4775 /// Microsoft C anonymous structure.
4776 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4777 /// Example:
4778 ///
4779 /// struct A { int a; };
4780 /// struct B { struct A; int b; };
4781 ///
4782 /// void foo() {
4783 ///   B var;
4784 ///   var.a = 3;
4785 /// }
4786 ///
4787 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4788                                            RecordDecl *Record) {
4789   assert(Record && "expected a record!");
4790 
4791   // Mock up a declarator.
4792   Declarator Dc(DS, Declarator::TypeNameContext);
4793   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4794   assert(TInfo && "couldn't build declarator info for anonymous struct");
4795 
4796   auto *ParentDecl = cast<RecordDecl>(CurContext);
4797   QualType RecTy = Context.getTypeDeclType(Record);
4798 
4799   // Create a declaration for this anonymous struct.
4800   NamedDecl *Anon = FieldDecl::Create(Context,
4801                              ParentDecl,
4802                              DS.getLocStart(),
4803                              DS.getLocStart(),
4804                              /*IdentifierInfo=*/nullptr,
4805                              RecTy,
4806                              TInfo,
4807                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4808                              /*InitStyle=*/ICIS_NoInit);
4809   Anon->setImplicit();
4810 
4811   // Add the anonymous struct object to the current context.
4812   CurContext->addDecl(Anon);
4813 
4814   // Inject the members of the anonymous struct into the current
4815   // context and into the identifier resolver chain for name lookup
4816   // purposes.
4817   SmallVector<NamedDecl*, 2> Chain;
4818   Chain.push_back(Anon);
4819 
4820   RecordDecl *RecordDef = Record->getDefinition();
4821   if (RequireCompleteType(Anon->getLocation(), RecTy,
4822                           diag::err_field_incomplete) ||
4823       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4824                                           AS_none, Chain)) {
4825     Anon->setInvalidDecl();
4826     ParentDecl->setInvalidDecl();
4827   }
4828 
4829   return Anon;
4830 }
4831 
4832 /// GetNameForDeclarator - Determine the full declaration name for the
4833 /// given Declarator.
4834 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4835   return GetNameFromUnqualifiedId(D.getName());
4836 }
4837 
4838 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4839 DeclarationNameInfo
4840 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4841   DeclarationNameInfo NameInfo;
4842   NameInfo.setLoc(Name.StartLocation);
4843 
4844   switch (Name.getKind()) {
4845 
4846   case UnqualifiedId::IK_ImplicitSelfParam:
4847   case UnqualifiedId::IK_Identifier:
4848     NameInfo.setName(Name.Identifier);
4849     NameInfo.setLoc(Name.StartLocation);
4850     return NameInfo;
4851 
4852   case UnqualifiedId::IK_DeductionGuideName: {
4853     // C++ [temp.deduct.guide]p3:
4854     //   The simple-template-id shall name a class template specialization.
4855     //   The template-name shall be the same identifier as the template-name
4856     //   of the simple-template-id.
4857     // These together intend to imply that the template-name shall name a
4858     // class template.
4859     // FIXME: template<typename T> struct X {};
4860     //        template<typename T> using Y = X<T>;
4861     //        Y(int) -> Y<int>;
4862     //   satisfies these rules but does not name a class template.
4863     TemplateName TN = Name.TemplateName.get().get();
4864     auto *Template = TN.getAsTemplateDecl();
4865     if (!Template || !isa<ClassTemplateDecl>(Template)) {
4866       Diag(Name.StartLocation,
4867            diag::err_deduction_guide_name_not_class_template)
4868         << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4869       if (Template)
4870         Diag(Template->getLocation(), diag::note_template_decl_here);
4871       return DeclarationNameInfo();
4872     }
4873 
4874     NameInfo.setName(
4875         Context.DeclarationNames.getCXXDeductionGuideName(Template));
4876     NameInfo.setLoc(Name.StartLocation);
4877     return NameInfo;
4878   }
4879 
4880   case UnqualifiedId::IK_OperatorFunctionId:
4881     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4882                                            Name.OperatorFunctionId.Operator));
4883     NameInfo.setLoc(Name.StartLocation);
4884     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4885       = Name.OperatorFunctionId.SymbolLocations[0];
4886     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4887       = Name.EndLocation.getRawEncoding();
4888     return NameInfo;
4889 
4890   case UnqualifiedId::IK_LiteralOperatorId:
4891     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4892                                                            Name.Identifier));
4893     NameInfo.setLoc(Name.StartLocation);
4894     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4895     return NameInfo;
4896 
4897   case UnqualifiedId::IK_ConversionFunctionId: {
4898     TypeSourceInfo *TInfo;
4899     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4900     if (Ty.isNull())
4901       return DeclarationNameInfo();
4902     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4903                                                Context.getCanonicalType(Ty)));
4904     NameInfo.setLoc(Name.StartLocation);
4905     NameInfo.setNamedTypeInfo(TInfo);
4906     return NameInfo;
4907   }
4908 
4909   case UnqualifiedId::IK_ConstructorName: {
4910     TypeSourceInfo *TInfo;
4911     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4912     if (Ty.isNull())
4913       return DeclarationNameInfo();
4914     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4915                                               Context.getCanonicalType(Ty)));
4916     NameInfo.setLoc(Name.StartLocation);
4917     NameInfo.setNamedTypeInfo(TInfo);
4918     return NameInfo;
4919   }
4920 
4921   case UnqualifiedId::IK_ConstructorTemplateId: {
4922     // In well-formed code, we can only have a constructor
4923     // template-id that refers to the current context, so go there
4924     // to find the actual type being constructed.
4925     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4926     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4927       return DeclarationNameInfo();
4928 
4929     // Determine the type of the class being constructed.
4930     QualType CurClassType = Context.getTypeDeclType(CurClass);
4931 
4932     // FIXME: Check two things: that the template-id names the same type as
4933     // CurClassType, and that the template-id does not occur when the name
4934     // was qualified.
4935 
4936     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4937                                     Context.getCanonicalType(CurClassType)));
4938     NameInfo.setLoc(Name.StartLocation);
4939     // FIXME: should we retrieve TypeSourceInfo?
4940     NameInfo.setNamedTypeInfo(nullptr);
4941     return NameInfo;
4942   }
4943 
4944   case UnqualifiedId::IK_DestructorName: {
4945     TypeSourceInfo *TInfo;
4946     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4947     if (Ty.isNull())
4948       return DeclarationNameInfo();
4949     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4950                                               Context.getCanonicalType(Ty)));
4951     NameInfo.setLoc(Name.StartLocation);
4952     NameInfo.setNamedTypeInfo(TInfo);
4953     return NameInfo;
4954   }
4955 
4956   case UnqualifiedId::IK_TemplateId: {
4957     TemplateName TName = Name.TemplateId->Template.get();
4958     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4959     return Context.getNameForTemplate(TName, TNameLoc);
4960   }
4961 
4962   } // switch (Name.getKind())
4963 
4964   llvm_unreachable("Unknown name kind");
4965 }
4966 
4967 static QualType getCoreType(QualType Ty) {
4968   do {
4969     if (Ty->isPointerType() || Ty->isReferenceType())
4970       Ty = Ty->getPointeeType();
4971     else if (Ty->isArrayType())
4972       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4973     else
4974       return Ty.withoutLocalFastQualifiers();
4975   } while (true);
4976 }
4977 
4978 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4979 /// and Definition have "nearly" matching parameters. This heuristic is
4980 /// used to improve diagnostics in the case where an out-of-line function
4981 /// definition doesn't match any declaration within the class or namespace.
4982 /// Also sets Params to the list of indices to the parameters that differ
4983 /// between the declaration and the definition. If hasSimilarParameters
4984 /// returns true and Params is empty, then all of the parameters match.
4985 static bool hasSimilarParameters(ASTContext &Context,
4986                                      FunctionDecl *Declaration,
4987                                      FunctionDecl *Definition,
4988                                      SmallVectorImpl<unsigned> &Params) {
4989   Params.clear();
4990   if (Declaration->param_size() != Definition->param_size())
4991     return false;
4992   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4993     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4994     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4995 
4996     // The parameter types are identical
4997     if (Context.hasSameType(DefParamTy, DeclParamTy))
4998       continue;
4999 
5000     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5001     QualType DefParamBaseTy = getCoreType(DefParamTy);
5002     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5003     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5004 
5005     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5006         (DeclTyName && DeclTyName == DefTyName))
5007       Params.push_back(Idx);
5008     else  // The two parameters aren't even close
5009       return false;
5010   }
5011 
5012   return true;
5013 }
5014 
5015 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5016 /// declarator needs to be rebuilt in the current instantiation.
5017 /// Any bits of declarator which appear before the name are valid for
5018 /// consideration here.  That's specifically the type in the decl spec
5019 /// and the base type in any member-pointer chunks.
5020 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5021                                                     DeclarationName Name) {
5022   // The types we specifically need to rebuild are:
5023   //   - typenames, typeofs, and decltypes
5024   //   - types which will become injected class names
5025   // Of course, we also need to rebuild any type referencing such a
5026   // type.  It's safest to just say "dependent", but we call out a
5027   // few cases here.
5028 
5029   DeclSpec &DS = D.getMutableDeclSpec();
5030   switch (DS.getTypeSpecType()) {
5031   case DeclSpec::TST_typename:
5032   case DeclSpec::TST_typeofType:
5033   case DeclSpec::TST_underlyingType:
5034   case DeclSpec::TST_atomic: {
5035     // Grab the type from the parser.
5036     TypeSourceInfo *TSI = nullptr;
5037     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5038     if (T.isNull() || !T->isDependentType()) break;
5039 
5040     // Make sure there's a type source info.  This isn't really much
5041     // of a waste; most dependent types should have type source info
5042     // attached already.
5043     if (!TSI)
5044       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5045 
5046     // Rebuild the type in the current instantiation.
5047     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5048     if (!TSI) return true;
5049 
5050     // Store the new type back in the decl spec.
5051     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5052     DS.UpdateTypeRep(LocType);
5053     break;
5054   }
5055 
5056   case DeclSpec::TST_decltype:
5057   case DeclSpec::TST_typeofExpr: {
5058     Expr *E = DS.getRepAsExpr();
5059     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5060     if (Result.isInvalid()) return true;
5061     DS.UpdateExprRep(Result.get());
5062     break;
5063   }
5064 
5065   default:
5066     // Nothing to do for these decl specs.
5067     break;
5068   }
5069 
5070   // It doesn't matter what order we do this in.
5071   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5072     DeclaratorChunk &Chunk = D.getTypeObject(I);
5073 
5074     // The only type information in the declarator which can come
5075     // before the declaration name is the base type of a member
5076     // pointer.
5077     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5078       continue;
5079 
5080     // Rebuild the scope specifier in-place.
5081     CXXScopeSpec &SS = Chunk.Mem.Scope();
5082     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5083       return true;
5084   }
5085 
5086   return false;
5087 }
5088 
5089 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5090   D.setFunctionDefinitionKind(FDK_Declaration);
5091   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5092 
5093   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5094       Dcl && Dcl->getDeclContext()->isFileContext())
5095     Dcl->setTopLevelDeclInObjCContainer();
5096 
5097   if (getLangOpts().OpenCL)
5098     setCurrentOpenCLExtensionForDecl(Dcl);
5099 
5100   return Dcl;
5101 }
5102 
5103 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5104 ///   If T is the name of a class, then each of the following shall have a
5105 ///   name different from T:
5106 ///     - every static data member of class T;
5107 ///     - every member function of class T
5108 ///     - every member of class T that is itself a type;
5109 /// \returns true if the declaration name violates these rules.
5110 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5111                                    DeclarationNameInfo NameInfo) {
5112   DeclarationName Name = NameInfo.getName();
5113 
5114   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5115   while (Record && Record->isAnonymousStructOrUnion())
5116     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5117   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5118     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5119     return true;
5120   }
5121 
5122   return false;
5123 }
5124 
5125 /// \brief Diagnose a declaration whose declarator-id has the given
5126 /// nested-name-specifier.
5127 ///
5128 /// \param SS The nested-name-specifier of the declarator-id.
5129 ///
5130 /// \param DC The declaration context to which the nested-name-specifier
5131 /// resolves.
5132 ///
5133 /// \param Name The name of the entity being declared.
5134 ///
5135 /// \param Loc The location of the name of the entity being declared.
5136 ///
5137 /// \returns true if we cannot safely recover from this error, false otherwise.
5138 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5139                                         DeclarationName Name,
5140                                         SourceLocation Loc) {
5141   DeclContext *Cur = CurContext;
5142   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5143     Cur = Cur->getParent();
5144 
5145   // If the user provided a superfluous scope specifier that refers back to the
5146   // class in which the entity is already declared, diagnose and ignore it.
5147   //
5148   // class X {
5149   //   void X::f();
5150   // };
5151   //
5152   // Note, it was once ill-formed to give redundant qualification in all
5153   // contexts, but that rule was removed by DR482.
5154   if (Cur->Equals(DC)) {
5155     if (Cur->isRecord()) {
5156       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5157                                       : diag::err_member_extra_qualification)
5158         << Name << FixItHint::CreateRemoval(SS.getRange());
5159       SS.clear();
5160     } else {
5161       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5162     }
5163     return false;
5164   }
5165 
5166   // Check whether the qualifying scope encloses the scope of the original
5167   // declaration.
5168   if (!Cur->Encloses(DC)) {
5169     if (Cur->isRecord())
5170       Diag(Loc, diag::err_member_qualification)
5171         << Name << SS.getRange();
5172     else if (isa<TranslationUnitDecl>(DC))
5173       Diag(Loc, diag::err_invalid_declarator_global_scope)
5174         << Name << SS.getRange();
5175     else if (isa<FunctionDecl>(Cur))
5176       Diag(Loc, diag::err_invalid_declarator_in_function)
5177         << Name << SS.getRange();
5178     else if (isa<BlockDecl>(Cur))
5179       Diag(Loc, diag::err_invalid_declarator_in_block)
5180         << Name << SS.getRange();
5181     else
5182       Diag(Loc, diag::err_invalid_declarator_scope)
5183       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5184 
5185     return true;
5186   }
5187 
5188   if (Cur->isRecord()) {
5189     // Cannot qualify members within a class.
5190     Diag(Loc, diag::err_member_qualification)
5191       << Name << SS.getRange();
5192     SS.clear();
5193 
5194     // C++ constructors and destructors with incorrect scopes can break
5195     // our AST invariants by having the wrong underlying types. If
5196     // that's the case, then drop this declaration entirely.
5197     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5198          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5199         !Context.hasSameType(Name.getCXXNameType(),
5200                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5201       return true;
5202 
5203     return false;
5204   }
5205 
5206   // C++11 [dcl.meaning]p1:
5207   //   [...] "The nested-name-specifier of the qualified declarator-id shall
5208   //   not begin with a decltype-specifer"
5209   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5210   while (SpecLoc.getPrefix())
5211     SpecLoc = SpecLoc.getPrefix();
5212   if (dyn_cast_or_null<DecltypeType>(
5213         SpecLoc.getNestedNameSpecifier()->getAsType()))
5214     Diag(Loc, diag::err_decltype_in_declarator)
5215       << SpecLoc.getTypeLoc().getSourceRange();
5216 
5217   return false;
5218 }
5219 
5220 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5221                                   MultiTemplateParamsArg TemplateParamLists) {
5222   // TODO: consider using NameInfo for diagnostic.
5223   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5224   DeclarationName Name = NameInfo.getName();
5225 
5226   // All of these full declarators require an identifier.  If it doesn't have
5227   // one, the ParsedFreeStandingDeclSpec action should be used.
5228   if (D.isDecompositionDeclarator()) {
5229     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5230   } else if (!Name) {
5231     if (!D.isInvalidType())  // Reject this if we think it is valid.
5232       Diag(D.getDeclSpec().getLocStart(),
5233            diag::err_declarator_need_ident)
5234         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5235     return nullptr;
5236   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5237     return nullptr;
5238 
5239   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5240   // we find one that is.
5241   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5242          (S->getFlags() & Scope::TemplateParamScope) != 0)
5243     S = S->getParent();
5244 
5245   DeclContext *DC = CurContext;
5246   if (D.getCXXScopeSpec().isInvalid())
5247     D.setInvalidType();
5248   else if (D.getCXXScopeSpec().isSet()) {
5249     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5250                                         UPPC_DeclarationQualifier))
5251       return nullptr;
5252 
5253     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5254     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5255     if (!DC || isa<EnumDecl>(DC)) {
5256       // If we could not compute the declaration context, it's because the
5257       // declaration context is dependent but does not refer to a class,
5258       // class template, or class template partial specialization. Complain
5259       // and return early, to avoid the coming semantic disaster.
5260       Diag(D.getIdentifierLoc(),
5261            diag::err_template_qualified_declarator_no_match)
5262         << D.getCXXScopeSpec().getScopeRep()
5263         << D.getCXXScopeSpec().getRange();
5264       return nullptr;
5265     }
5266     bool IsDependentContext = DC->isDependentContext();
5267 
5268     if (!IsDependentContext &&
5269         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5270       return nullptr;
5271 
5272     // If a class is incomplete, do not parse entities inside it.
5273     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5274       Diag(D.getIdentifierLoc(),
5275            diag::err_member_def_undefined_record)
5276         << Name << DC << D.getCXXScopeSpec().getRange();
5277       return nullptr;
5278     }
5279     if (!D.getDeclSpec().isFriendSpecified()) {
5280       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5281                                       Name, D.getIdentifierLoc())) {
5282         if (DC->isRecord())
5283           return nullptr;
5284 
5285         D.setInvalidType();
5286       }
5287     }
5288 
5289     // Check whether we need to rebuild the type of the given
5290     // declaration in the current instantiation.
5291     if (EnteringContext && IsDependentContext &&
5292         TemplateParamLists.size() != 0) {
5293       ContextRAII SavedContext(*this, DC);
5294       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5295         D.setInvalidType();
5296     }
5297   }
5298 
5299   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5300   QualType R = TInfo->getType();
5301 
5302   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5303                                       UPPC_DeclarationType))
5304     D.setInvalidType();
5305 
5306   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5307                         ForRedeclaration);
5308 
5309   // See if this is a redefinition of a variable in the same scope.
5310   if (!D.getCXXScopeSpec().isSet()) {
5311     bool IsLinkageLookup = false;
5312     bool CreateBuiltins = false;
5313 
5314     // If the declaration we're planning to build will be a function
5315     // or object with linkage, then look for another declaration with
5316     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5317     //
5318     // If the declaration we're planning to build will be declared with
5319     // external linkage in the translation unit, create any builtin with
5320     // the same name.
5321     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5322       /* Do nothing*/;
5323     else if (CurContext->isFunctionOrMethod() &&
5324              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5325               R->isFunctionType())) {
5326       IsLinkageLookup = true;
5327       CreateBuiltins =
5328           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5329     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5330                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5331       CreateBuiltins = true;
5332 
5333     if (IsLinkageLookup)
5334       Previous.clear(LookupRedeclarationWithLinkage);
5335 
5336     LookupName(Previous, S, CreateBuiltins);
5337   } else { // Something like "int foo::x;"
5338     LookupQualifiedName(Previous, DC);
5339 
5340     // C++ [dcl.meaning]p1:
5341     //   When the declarator-id is qualified, the declaration shall refer to a
5342     //  previously declared member of the class or namespace to which the
5343     //  qualifier refers (or, in the case of a namespace, of an element of the
5344     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5345     //  thereof; [...]
5346     //
5347     // Note that we already checked the context above, and that we do not have
5348     // enough information to make sure that Previous contains the declaration
5349     // we want to match. For example, given:
5350     //
5351     //   class X {
5352     //     void f();
5353     //     void f(float);
5354     //   };
5355     //
5356     //   void X::f(int) { } // ill-formed
5357     //
5358     // In this case, Previous will point to the overload set
5359     // containing the two f's declared in X, but neither of them
5360     // matches.
5361 
5362     // C++ [dcl.meaning]p1:
5363     //   [...] the member shall not merely have been introduced by a
5364     //   using-declaration in the scope of the class or namespace nominated by
5365     //   the nested-name-specifier of the declarator-id.
5366     RemoveUsingDecls(Previous);
5367   }
5368 
5369   if (Previous.isSingleResult() &&
5370       Previous.getFoundDecl()->isTemplateParameter()) {
5371     // Maybe we will complain about the shadowed template parameter.
5372     if (!D.isInvalidType())
5373       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5374                                       Previous.getFoundDecl());
5375 
5376     // Just pretend that we didn't see the previous declaration.
5377     Previous.clear();
5378   }
5379 
5380   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5381     // Forget that the previous declaration is the injected-class-name.
5382     Previous.clear();
5383 
5384   // In C++, the previous declaration we find might be a tag type
5385   // (class or enum). In this case, the new declaration will hide the
5386   // tag type. Note that this applies to functions, function templates, and
5387   // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5388   if (Previous.isSingleTagDecl() &&
5389       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5390       (TemplateParamLists.size() == 0 || R->isFunctionType()))
5391     Previous.clear();
5392 
5393   // Check that there are no default arguments other than in the parameters
5394   // of a function declaration (C++ only).
5395   if (getLangOpts().CPlusPlus)
5396     CheckExtraCXXDefaultArguments(D);
5397 
5398   if (D.getDeclSpec().isConceptSpecified()) {
5399     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5400     // applied only to the definition of a function template or variable
5401     // template, declared in namespace scope
5402     if (!TemplateParamLists.size()) {
5403       Diag(D.getDeclSpec().getConceptSpecLoc(),
5404            diag:: err_concept_wrong_decl_kind);
5405       return nullptr;
5406     }
5407 
5408     if (!DC->getRedeclContext()->isFileContext()) {
5409       Diag(D.getIdentifierLoc(),
5410            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5411       return nullptr;
5412     }
5413   }
5414 
5415   NamedDecl *New;
5416 
5417   bool AddToScope = true;
5418   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5419     if (TemplateParamLists.size()) {
5420       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5421       return nullptr;
5422     }
5423 
5424     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5425   } else if (R->isFunctionType()) {
5426     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5427                                   TemplateParamLists,
5428                                   AddToScope);
5429   } else {
5430     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5431                                   AddToScope);
5432   }
5433 
5434   if (!New)
5435     return nullptr;
5436 
5437   // If this has an identifier and is not a function template specialization,
5438   // add it to the scope stack.
5439   if (New->getDeclName() && AddToScope) {
5440     // Only make a locally-scoped extern declaration visible if it is the first
5441     // declaration of this entity. Qualified lookup for such an entity should
5442     // only find this declaration if there is no visible declaration of it.
5443     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5444     PushOnScopeChains(New, S, AddToContext);
5445     if (!AddToContext)
5446       CurContext->addHiddenDecl(New);
5447   }
5448 
5449   if (isInOpenMPDeclareTargetContext())
5450     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5451 
5452   return New;
5453 }
5454 
5455 /// Helper method to turn variable array types into constant array
5456 /// types in certain situations which would otherwise be errors (for
5457 /// GCC compatibility).
5458 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5459                                                     ASTContext &Context,
5460                                                     bool &SizeIsNegative,
5461                                                     llvm::APSInt &Oversized) {
5462   // This method tries to turn a variable array into a constant
5463   // array even when the size isn't an ICE.  This is necessary
5464   // for compatibility with code that depends on gcc's buggy
5465   // constant expression folding, like struct {char x[(int)(char*)2];}
5466   SizeIsNegative = false;
5467   Oversized = 0;
5468 
5469   if (T->isDependentType())
5470     return QualType();
5471 
5472   QualifierCollector Qs;
5473   const Type *Ty = Qs.strip(T);
5474 
5475   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5476     QualType Pointee = PTy->getPointeeType();
5477     QualType FixedType =
5478         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5479                                             Oversized);
5480     if (FixedType.isNull()) return FixedType;
5481     FixedType = Context.getPointerType(FixedType);
5482     return Qs.apply(Context, FixedType);
5483   }
5484   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5485     QualType Inner = PTy->getInnerType();
5486     QualType FixedType =
5487         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5488                                             Oversized);
5489     if (FixedType.isNull()) return FixedType;
5490     FixedType = Context.getParenType(FixedType);
5491     return Qs.apply(Context, FixedType);
5492   }
5493 
5494   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5495   if (!VLATy)
5496     return QualType();
5497   // FIXME: We should probably handle this case
5498   if (VLATy->getElementType()->isVariablyModifiedType())
5499     return QualType();
5500 
5501   llvm::APSInt Res;
5502   if (!VLATy->getSizeExpr() ||
5503       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5504     return QualType();
5505 
5506   // Check whether the array size is negative.
5507   if (Res.isSigned() && Res.isNegative()) {
5508     SizeIsNegative = true;
5509     return QualType();
5510   }
5511 
5512   // Check whether the array is too large to be addressed.
5513   unsigned ActiveSizeBits
5514     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5515                                               Res);
5516   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5517     Oversized = Res;
5518     return QualType();
5519   }
5520 
5521   return Context.getConstantArrayType(VLATy->getElementType(),
5522                                       Res, ArrayType::Normal, 0);
5523 }
5524 
5525 static void
5526 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5527   SrcTL = SrcTL.getUnqualifiedLoc();
5528   DstTL = DstTL.getUnqualifiedLoc();
5529   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5530     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5531     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5532                                       DstPTL.getPointeeLoc());
5533     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5534     return;
5535   }
5536   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5537     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5538     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5539                                       DstPTL.getInnerLoc());
5540     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5541     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5542     return;
5543   }
5544   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5545   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5546   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5547   TypeLoc DstElemTL = DstATL.getElementLoc();
5548   DstElemTL.initializeFullCopy(SrcElemTL);
5549   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5550   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5551   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5552 }
5553 
5554 /// Helper method to turn variable array types into constant array
5555 /// types in certain situations which would otherwise be errors (for
5556 /// GCC compatibility).
5557 static TypeSourceInfo*
5558 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5559                                               ASTContext &Context,
5560                                               bool &SizeIsNegative,
5561                                               llvm::APSInt &Oversized) {
5562   QualType FixedTy
5563     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5564                                           SizeIsNegative, Oversized);
5565   if (FixedTy.isNull())
5566     return nullptr;
5567   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5568   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5569                                     FixedTInfo->getTypeLoc());
5570   return FixedTInfo;
5571 }
5572 
5573 /// \brief Register the given locally-scoped extern "C" declaration so
5574 /// that it can be found later for redeclarations. We include any extern "C"
5575 /// declaration that is not visible in the translation unit here, not just
5576 /// function-scope declarations.
5577 void
5578 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5579   if (!getLangOpts().CPlusPlus &&
5580       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5581     // Don't need to track declarations in the TU in C.
5582     return;
5583 
5584   // Note that we have a locally-scoped external with this name.
5585   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5586 }
5587 
5588 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5589   // FIXME: We can have multiple results via __attribute__((overloadable)).
5590   auto Result = Context.getExternCContextDecl()->lookup(Name);
5591   return Result.empty() ? nullptr : *Result.begin();
5592 }
5593 
5594 /// \brief Diagnose function specifiers on a declaration of an identifier that
5595 /// does not identify a function.
5596 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5597   // FIXME: We should probably indicate the identifier in question to avoid
5598   // confusion for constructs like "virtual int a(), b;"
5599   if (DS.isVirtualSpecified())
5600     Diag(DS.getVirtualSpecLoc(),
5601          diag::err_virtual_non_function);
5602 
5603   if (DS.isExplicitSpecified())
5604     Diag(DS.getExplicitSpecLoc(),
5605          diag::err_explicit_non_function);
5606 
5607   if (DS.isNoreturnSpecified())
5608     Diag(DS.getNoreturnSpecLoc(),
5609          diag::err_noreturn_non_function);
5610 }
5611 
5612 NamedDecl*
5613 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5614                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5615   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5616   if (D.getCXXScopeSpec().isSet()) {
5617     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5618       << D.getCXXScopeSpec().getRange();
5619     D.setInvalidType();
5620     // Pretend we didn't see the scope specifier.
5621     DC = CurContext;
5622     Previous.clear();
5623   }
5624 
5625   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5626 
5627   if (D.getDeclSpec().isInlineSpecified())
5628     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5629         << getLangOpts().CPlusPlus1z;
5630   if (D.getDeclSpec().isConstexprSpecified())
5631     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5632       << 1;
5633   if (D.getDeclSpec().isConceptSpecified())
5634     Diag(D.getDeclSpec().getConceptSpecLoc(),
5635          diag::err_concept_wrong_decl_kind);
5636 
5637   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5638     if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5639       Diag(D.getName().StartLocation,
5640            diag::err_deduction_guide_invalid_specifier)
5641           << "typedef";
5642     else
5643       Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5644           << D.getName().getSourceRange();
5645     return nullptr;
5646   }
5647 
5648   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5649   if (!NewTD) return nullptr;
5650 
5651   // Handle attributes prior to checking for duplicates in MergeVarDecl
5652   ProcessDeclAttributes(S, NewTD, D);
5653 
5654   CheckTypedefForVariablyModifiedType(S, NewTD);
5655 
5656   bool Redeclaration = D.isRedeclaration();
5657   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5658   D.setRedeclaration(Redeclaration);
5659   return ND;
5660 }
5661 
5662 void
5663 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5664   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5665   // then it shall have block scope.
5666   // Note that variably modified types must be fixed before merging the decl so
5667   // that redeclarations will match.
5668   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5669   QualType T = TInfo->getType();
5670   if (T->isVariablyModifiedType()) {
5671     getCurFunction()->setHasBranchProtectedScope();
5672 
5673     if (S->getFnParent() == nullptr) {
5674       bool SizeIsNegative;
5675       llvm::APSInt Oversized;
5676       TypeSourceInfo *FixedTInfo =
5677         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5678                                                       SizeIsNegative,
5679                                                       Oversized);
5680       if (FixedTInfo) {
5681         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5682         NewTD->setTypeSourceInfo(FixedTInfo);
5683       } else {
5684         if (SizeIsNegative)
5685           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5686         else if (T->isVariableArrayType())
5687           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5688         else if (Oversized.getBoolValue())
5689           Diag(NewTD->getLocation(), diag::err_array_too_large)
5690             << Oversized.toString(10);
5691         else
5692           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5693         NewTD->setInvalidDecl();
5694       }
5695     }
5696   }
5697 }
5698 
5699 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5700 /// declares a typedef-name, either using the 'typedef' type specifier or via
5701 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5702 NamedDecl*
5703 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5704                            LookupResult &Previous, bool &Redeclaration) {
5705 
5706   // Find the shadowed declaration before filtering for scope.
5707   NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5708 
5709   // Merge the decl with the existing one if appropriate. If the decl is
5710   // in an outer scope, it isn't the same thing.
5711   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5712                        /*AllowInlineNamespace*/false);
5713   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5714   if (!Previous.empty()) {
5715     Redeclaration = true;
5716     MergeTypedefNameDecl(S, NewTD, Previous);
5717   }
5718 
5719   if (ShadowedDecl && !Redeclaration)
5720     CheckShadow(NewTD, ShadowedDecl, Previous);
5721 
5722   // If this is the C FILE type, notify the AST context.
5723   if (IdentifierInfo *II = NewTD->getIdentifier())
5724     if (!NewTD->isInvalidDecl() &&
5725         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5726       if (II->isStr("FILE"))
5727         Context.setFILEDecl(NewTD);
5728       else if (II->isStr("jmp_buf"))
5729         Context.setjmp_bufDecl(NewTD);
5730       else if (II->isStr("sigjmp_buf"))
5731         Context.setsigjmp_bufDecl(NewTD);
5732       else if (II->isStr("ucontext_t"))
5733         Context.setucontext_tDecl(NewTD);
5734     }
5735 
5736   return NewTD;
5737 }
5738 
5739 /// \brief Determines whether the given declaration is an out-of-scope
5740 /// previous declaration.
5741 ///
5742 /// This routine should be invoked when name lookup has found a
5743 /// previous declaration (PrevDecl) that is not in the scope where a
5744 /// new declaration by the same name is being introduced. If the new
5745 /// declaration occurs in a local scope, previous declarations with
5746 /// linkage may still be considered previous declarations (C99
5747 /// 6.2.2p4-5, C++ [basic.link]p6).
5748 ///
5749 /// \param PrevDecl the previous declaration found by name
5750 /// lookup
5751 ///
5752 /// \param DC the context in which the new declaration is being
5753 /// declared.
5754 ///
5755 /// \returns true if PrevDecl is an out-of-scope previous declaration
5756 /// for a new delcaration with the same name.
5757 static bool
5758 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5759                                 ASTContext &Context) {
5760   if (!PrevDecl)
5761     return false;
5762 
5763   if (!PrevDecl->hasLinkage())
5764     return false;
5765 
5766   if (Context.getLangOpts().CPlusPlus) {
5767     // C++ [basic.link]p6:
5768     //   If there is a visible declaration of an entity with linkage
5769     //   having the same name and type, ignoring entities declared
5770     //   outside the innermost enclosing namespace scope, the block
5771     //   scope declaration declares that same entity and receives the
5772     //   linkage of the previous declaration.
5773     DeclContext *OuterContext = DC->getRedeclContext();
5774     if (!OuterContext->isFunctionOrMethod())
5775       // This rule only applies to block-scope declarations.
5776       return false;
5777 
5778     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5779     if (PrevOuterContext->isRecord())
5780       // We found a member function: ignore it.
5781       return false;
5782 
5783     // Find the innermost enclosing namespace for the new and
5784     // previous declarations.
5785     OuterContext = OuterContext->getEnclosingNamespaceContext();
5786     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5787 
5788     // The previous declaration is in a different namespace, so it
5789     // isn't the same function.
5790     if (!OuterContext->Equals(PrevOuterContext))
5791       return false;
5792   }
5793 
5794   return true;
5795 }
5796 
5797 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5798   CXXScopeSpec &SS = D.getCXXScopeSpec();
5799   if (!SS.isSet()) return;
5800   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5801 }
5802 
5803 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5804   QualType type = decl->getType();
5805   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5806   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5807     // Various kinds of declaration aren't allowed to be __autoreleasing.
5808     unsigned kind = -1U;
5809     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5810       if (var->hasAttr<BlocksAttr>())
5811         kind = 0; // __block
5812       else if (!var->hasLocalStorage())
5813         kind = 1; // global
5814     } else if (isa<ObjCIvarDecl>(decl)) {
5815       kind = 3; // ivar
5816     } else if (isa<FieldDecl>(decl)) {
5817       kind = 2; // field
5818     }
5819 
5820     if (kind != -1U) {
5821       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5822         << kind;
5823     }
5824   } else if (lifetime == Qualifiers::OCL_None) {
5825     // Try to infer lifetime.
5826     if (!type->isObjCLifetimeType())
5827       return false;
5828 
5829     lifetime = type->getObjCARCImplicitLifetime();
5830     type = Context.getLifetimeQualifiedType(type, lifetime);
5831     decl->setType(type);
5832   }
5833 
5834   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5835     // Thread-local variables cannot have lifetime.
5836     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5837         var->getTLSKind()) {
5838       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5839         << var->getType();
5840       return true;
5841     }
5842   }
5843 
5844   return false;
5845 }
5846 
5847 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5848   // Ensure that an auto decl is deduced otherwise the checks below might cache
5849   // the wrong linkage.
5850   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5851 
5852   // 'weak' only applies to declarations with external linkage.
5853   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5854     if (!ND.isExternallyVisible()) {
5855       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5856       ND.dropAttr<WeakAttr>();
5857     }
5858   }
5859   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5860     if (ND.isExternallyVisible()) {
5861       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5862       ND.dropAttr<WeakRefAttr>();
5863       ND.dropAttr<AliasAttr>();
5864     }
5865   }
5866 
5867   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5868     if (VD->hasInit()) {
5869       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5870         assert(VD->isThisDeclarationADefinition() &&
5871                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5872         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5873         VD->dropAttr<AliasAttr>();
5874       }
5875     }
5876   }
5877 
5878   // 'selectany' only applies to externally visible variable declarations.
5879   // It does not apply to functions.
5880   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5881     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5882       S.Diag(Attr->getLocation(),
5883              diag::err_attribute_selectany_non_extern_data);
5884       ND.dropAttr<SelectAnyAttr>();
5885     }
5886   }
5887 
5888   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5889     // dll attributes require external linkage. Static locals may have external
5890     // linkage but still cannot be explicitly imported or exported.
5891     auto *VD = dyn_cast<VarDecl>(&ND);
5892     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5893       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5894         << &ND << Attr;
5895       ND.setInvalidDecl();
5896     }
5897   }
5898 
5899   // Virtual functions cannot be marked as 'notail'.
5900   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5901     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5902       if (MD->isVirtual()) {
5903         S.Diag(ND.getLocation(),
5904                diag::err_invalid_attribute_on_virtual_function)
5905             << Attr;
5906         ND.dropAttr<NotTailCalledAttr>();
5907       }
5908 }
5909 
5910 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5911                                            NamedDecl *NewDecl,
5912                                            bool IsSpecialization,
5913                                            bool IsDefinition) {
5914   if (OldDecl->isInvalidDecl())
5915     return;
5916 
5917   bool IsTemplate = false;
5918   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5919     OldDecl = OldTD->getTemplatedDecl();
5920     IsTemplate = true;
5921     if (!IsSpecialization)
5922       IsDefinition = false;
5923   }
5924   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5925     NewDecl = NewTD->getTemplatedDecl();
5926     IsTemplate = true;
5927   }
5928 
5929   if (!OldDecl || !NewDecl)
5930     return;
5931 
5932   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5933   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5934   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5935   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5936 
5937   // dllimport and dllexport are inheritable attributes so we have to exclude
5938   // inherited attribute instances.
5939   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5940                     (NewExportAttr && !NewExportAttr->isInherited());
5941 
5942   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5943   // the only exception being explicit specializations.
5944   // Implicitly generated declarations are also excluded for now because there
5945   // is no other way to switch these to use dllimport or dllexport.
5946   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5947 
5948   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5949     // Allow with a warning for free functions and global variables.
5950     bool JustWarn = false;
5951     if (!OldDecl->isCXXClassMember()) {
5952       auto *VD = dyn_cast<VarDecl>(OldDecl);
5953       if (VD && !VD->getDescribedVarTemplate())
5954         JustWarn = true;
5955       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5956       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5957         JustWarn = true;
5958     }
5959 
5960     // We cannot change a declaration that's been used because IR has already
5961     // been emitted. Dllimported functions will still work though (modulo
5962     // address equality) as they can use the thunk.
5963     if (OldDecl->isUsed())
5964       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5965         JustWarn = false;
5966 
5967     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5968                                : diag::err_attribute_dll_redeclaration;
5969     S.Diag(NewDecl->getLocation(), DiagID)
5970         << NewDecl
5971         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5972     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5973     if (!JustWarn) {
5974       NewDecl->setInvalidDecl();
5975       return;
5976     }
5977   }
5978 
5979   // A redeclaration is not allowed to drop a dllimport attribute, the only
5980   // exceptions being inline function definitions (except for function
5981   // templates), local extern declarations, qualified friend declarations or
5982   // special MSVC extension: in the last case, the declaration is treated as if
5983   // it were marked dllexport.
5984   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5985   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5986   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5987     // Ignore static data because out-of-line definitions are diagnosed
5988     // separately.
5989     IsStaticDataMember = VD->isStaticDataMember();
5990     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5991                    VarDecl::DeclarationOnly;
5992   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5993     IsInline = FD->isInlined();
5994     IsQualifiedFriend = FD->getQualifier() &&
5995                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5996   }
5997 
5998   if (OldImportAttr && !HasNewAttr &&
5999       (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6000       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6001     if (IsMicrosoft && IsDefinition) {
6002       S.Diag(NewDecl->getLocation(),
6003              diag::warn_redeclaration_without_import_attribute)
6004           << NewDecl;
6005       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6006       NewDecl->dropAttr<DLLImportAttr>();
6007       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6008           NewImportAttr->getRange(), S.Context,
6009           NewImportAttr->getSpellingListIndex()));
6010     } else {
6011       S.Diag(NewDecl->getLocation(),
6012              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6013           << NewDecl << OldImportAttr;
6014       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6015       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6016       OldDecl->dropAttr<DLLImportAttr>();
6017       NewDecl->dropAttr<DLLImportAttr>();
6018     }
6019   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6020     // In MinGW, seeing a function declared inline drops the dllimport attribute.
6021     OldDecl->dropAttr<DLLImportAttr>();
6022     NewDecl->dropAttr<DLLImportAttr>();
6023     S.Diag(NewDecl->getLocation(),
6024            diag::warn_dllimport_dropped_from_inline_function)
6025         << NewDecl << OldImportAttr;
6026   }
6027 }
6028 
6029 /// Given that we are within the definition of the given function,
6030 /// will that definition behave like C99's 'inline', where the
6031 /// definition is discarded except for optimization purposes?
6032 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6033   // Try to avoid calling GetGVALinkageForFunction.
6034 
6035   // All cases of this require the 'inline' keyword.
6036   if (!FD->isInlined()) return false;
6037 
6038   // This is only possible in C++ with the gnu_inline attribute.
6039   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6040     return false;
6041 
6042   // Okay, go ahead and call the relatively-more-expensive function.
6043   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6044 }
6045 
6046 /// Determine whether a variable is extern "C" prior to attaching
6047 /// an initializer. We can't just call isExternC() here, because that
6048 /// will also compute and cache whether the declaration is externally
6049 /// visible, which might change when we attach the initializer.
6050 ///
6051 /// This can only be used if the declaration is known to not be a
6052 /// redeclaration of an internal linkage declaration.
6053 ///
6054 /// For instance:
6055 ///
6056 ///   auto x = []{};
6057 ///
6058 /// Attaching the initializer here makes this declaration not externally
6059 /// visible, because its type has internal linkage.
6060 ///
6061 /// FIXME: This is a hack.
6062 template<typename T>
6063 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6064   if (S.getLangOpts().CPlusPlus) {
6065     // In C++, the overloadable attribute negates the effects of extern "C".
6066     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6067       return false;
6068 
6069     // So do CUDA's host/device attributes.
6070     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6071                                  D->template hasAttr<CUDAHostAttr>()))
6072       return false;
6073   }
6074   return D->isExternC();
6075 }
6076 
6077 static bool shouldConsiderLinkage(const VarDecl *VD) {
6078   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6079   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6080     return VD->hasExternalStorage();
6081   if (DC->isFileContext())
6082     return true;
6083   if (DC->isRecord())
6084     return false;
6085   llvm_unreachable("Unexpected context");
6086 }
6087 
6088 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6089   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6090   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6091       isa<OMPDeclareReductionDecl>(DC))
6092     return true;
6093   if (DC->isRecord())
6094     return false;
6095   llvm_unreachable("Unexpected context");
6096 }
6097 
6098 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6099                           AttributeList::Kind Kind) {
6100   for (const AttributeList *L = AttrList; L; L = L->getNext())
6101     if (L->getKind() == Kind)
6102       return true;
6103   return false;
6104 }
6105 
6106 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6107                           AttributeList::Kind Kind) {
6108   // Check decl attributes on the DeclSpec.
6109   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6110     return true;
6111 
6112   // Walk the declarator structure, checking decl attributes that were in a type
6113   // position to the decl itself.
6114   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6115     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6116       return true;
6117   }
6118 
6119   // Finally, check attributes on the decl itself.
6120   return hasParsedAttr(S, PD.getAttributes(), Kind);
6121 }
6122 
6123 /// Adjust the \c DeclContext for a function or variable that might be a
6124 /// function-local external declaration.
6125 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6126   if (!DC->isFunctionOrMethod())
6127     return false;
6128 
6129   // If this is a local extern function or variable declared within a function
6130   // template, don't add it into the enclosing namespace scope until it is
6131   // instantiated; it might have a dependent type right now.
6132   if (DC->isDependentContext())
6133     return true;
6134 
6135   // C++11 [basic.link]p7:
6136   //   When a block scope declaration of an entity with linkage is not found to
6137   //   refer to some other declaration, then that entity is a member of the
6138   //   innermost enclosing namespace.
6139   //
6140   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6141   // semantically-enclosing namespace, not a lexically-enclosing one.
6142   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6143     DC = DC->getParent();
6144   return true;
6145 }
6146 
6147 /// \brief Returns true if given declaration has external C language linkage.
6148 static bool isDeclExternC(const Decl *D) {
6149   if (const auto *FD = dyn_cast<FunctionDecl>(D))
6150     return FD->isExternC();
6151   if (const auto *VD = dyn_cast<VarDecl>(D))
6152     return VD->isExternC();
6153 
6154   llvm_unreachable("Unknown type of decl!");
6155 }
6156 
6157 NamedDecl *Sema::ActOnVariableDeclarator(
6158     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6159     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6160     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6161   QualType R = TInfo->getType();
6162   DeclarationName Name = GetNameForDeclarator(D).getName();
6163 
6164   IdentifierInfo *II = Name.getAsIdentifierInfo();
6165 
6166   if (D.isDecompositionDeclarator()) {
6167     AddToScope = false;
6168     // Take the name of the first declarator as our name for diagnostic
6169     // purposes.
6170     auto &Decomp = D.getDecompositionDeclarator();
6171     if (!Decomp.bindings().empty()) {
6172       II = Decomp.bindings()[0].Name;
6173       Name = II;
6174     }
6175   } else if (!II) {
6176     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6177     return nullptr;
6178   }
6179 
6180   if (getLangOpts().OpenCL) {
6181     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6182     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6183     // argument.
6184     if (R->isImageType() || R->isPipeType()) {
6185       Diag(D.getIdentifierLoc(),
6186            diag::err_opencl_type_can_only_be_used_as_function_parameter)
6187           << R;
6188       D.setInvalidType();
6189       return nullptr;
6190     }
6191 
6192     // OpenCL v1.2 s6.9.r:
6193     // The event type cannot be used to declare a program scope variable.
6194     // OpenCL v2.0 s6.9.q:
6195     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6196     if (NULL == S->getParent()) {
6197       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6198         Diag(D.getIdentifierLoc(),
6199              diag::err_invalid_type_for_program_scope_var) << R;
6200         D.setInvalidType();
6201         return nullptr;
6202       }
6203     }
6204 
6205     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6206     QualType NR = R;
6207     while (NR->isPointerType()) {
6208       if (NR->isFunctionPointerType()) {
6209         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6210         D.setInvalidType();
6211         break;
6212       }
6213       NR = NR->getPointeeType();
6214     }
6215 
6216     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6217       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6218       // half array type (unless the cl_khr_fp16 extension is enabled).
6219       if (Context.getBaseElementType(R)->isHalfType()) {
6220         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6221         D.setInvalidType();
6222       }
6223     }
6224 
6225     if (R->isSamplerT()) {
6226       // OpenCL v1.2 s6.9.b p4:
6227       // The sampler type cannot be used with the __local and __global address
6228       // space qualifiers.
6229       if (R.getAddressSpace() == LangAS::opencl_local ||
6230           R.getAddressSpace() == LangAS::opencl_global) {
6231         Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6232       }
6233 
6234       // OpenCL v1.2 s6.12.14.1:
6235       // A global sampler must be declared with either the constant address
6236       // space qualifier or with the const qualifier.
6237       if (DC->isTranslationUnit() &&
6238           !(R.getAddressSpace() == LangAS::opencl_constant ||
6239           R.isConstQualified())) {
6240         Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6241         D.setInvalidType();
6242       }
6243     }
6244 
6245     // OpenCL v1.2 s6.9.r:
6246     // The event type cannot be used with the __local, __constant and __global
6247     // address space qualifiers.
6248     if (R->isEventT()) {
6249       if (R.getAddressSpace()) {
6250         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6251         D.setInvalidType();
6252       }
6253     }
6254   }
6255 
6256   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6257   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6258 
6259   // dllimport globals without explicit storage class are treated as extern. We
6260   // have to change the storage class this early to get the right DeclContext.
6261   if (SC == SC_None && !DC->isRecord() &&
6262       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6263       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6264     SC = SC_Extern;
6265 
6266   DeclContext *OriginalDC = DC;
6267   bool IsLocalExternDecl = SC == SC_Extern &&
6268                            adjustContextForLocalExternDecl(DC);
6269 
6270   if (SCSpec == DeclSpec::SCS_mutable) {
6271     // mutable can only appear on non-static class members, so it's always
6272     // an error here
6273     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6274     D.setInvalidType();
6275     SC = SC_None;
6276   }
6277 
6278   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6279       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6280                               D.getDeclSpec().getStorageClassSpecLoc())) {
6281     // In C++11, the 'register' storage class specifier is deprecated.
6282     // Suppress the warning in system macros, it's used in macros in some
6283     // popular C system headers, such as in glibc's htonl() macro.
6284     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6285          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6286                                    : diag::warn_deprecated_register)
6287       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6288   }
6289 
6290   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6291 
6292   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6293     // C99 6.9p2: The storage-class specifiers auto and register shall not
6294     // appear in the declaration specifiers in an external declaration.
6295     // Global Register+Asm is a GNU extension we support.
6296     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6297       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6298       D.setInvalidType();
6299     }
6300   }
6301 
6302   bool IsMemberSpecialization = false;
6303   bool IsVariableTemplateSpecialization = false;
6304   bool IsPartialSpecialization = false;
6305   bool IsVariableTemplate = false;
6306   VarDecl *NewVD = nullptr;
6307   VarTemplateDecl *NewTemplate = nullptr;
6308   TemplateParameterList *TemplateParams = nullptr;
6309   if (!getLangOpts().CPlusPlus) {
6310     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6311                             D.getIdentifierLoc(), II,
6312                             R, TInfo, SC);
6313 
6314     if (R->getContainedDeducedType())
6315       ParsingInitForAutoVars.insert(NewVD);
6316 
6317     if (D.isInvalidType())
6318       NewVD->setInvalidDecl();
6319   } else {
6320     bool Invalid = false;
6321 
6322     if (DC->isRecord() && !CurContext->isRecord()) {
6323       // This is an out-of-line definition of a static data member.
6324       switch (SC) {
6325       case SC_None:
6326         break;
6327       case SC_Static:
6328         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6329              diag::err_static_out_of_line)
6330           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6331         break;
6332       case SC_Auto:
6333       case SC_Register:
6334       case SC_Extern:
6335         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6336         // to names of variables declared in a block or to function parameters.
6337         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6338         // of class members
6339 
6340         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6341              diag::err_storage_class_for_static_member)
6342           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6343         break;
6344       case SC_PrivateExtern:
6345         llvm_unreachable("C storage class in c++!");
6346       }
6347     }
6348 
6349     if (SC == SC_Static && CurContext->isRecord()) {
6350       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6351         if (RD->isLocalClass())
6352           Diag(D.getIdentifierLoc(),
6353                diag::err_static_data_member_not_allowed_in_local_class)
6354             << Name << RD->getDeclName();
6355 
6356         // C++98 [class.union]p1: If a union contains a static data member,
6357         // the program is ill-formed. C++11 drops this restriction.
6358         if (RD->isUnion())
6359           Diag(D.getIdentifierLoc(),
6360                getLangOpts().CPlusPlus11
6361                  ? diag::warn_cxx98_compat_static_data_member_in_union
6362                  : diag::ext_static_data_member_in_union) << Name;
6363         // We conservatively disallow static data members in anonymous structs.
6364         else if (!RD->getDeclName())
6365           Diag(D.getIdentifierLoc(),
6366                diag::err_static_data_member_not_allowed_in_anon_struct)
6367             << Name << RD->isUnion();
6368       }
6369     }
6370 
6371     // Match up the template parameter lists with the scope specifier, then
6372     // determine whether we have a template or a template specialization.
6373     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6374         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6375         D.getCXXScopeSpec(),
6376         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6377             ? D.getName().TemplateId
6378             : nullptr,
6379         TemplateParamLists,
6380         /*never a friend*/ false, IsMemberSpecialization, Invalid);
6381 
6382     if (TemplateParams) {
6383       if (!TemplateParams->size() &&
6384           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6385         // There is an extraneous 'template<>' for this variable. Complain
6386         // about it, but allow the declaration of the variable.
6387         Diag(TemplateParams->getTemplateLoc(),
6388              diag::err_template_variable_noparams)
6389           << II
6390           << SourceRange(TemplateParams->getTemplateLoc(),
6391                          TemplateParams->getRAngleLoc());
6392         TemplateParams = nullptr;
6393       } else {
6394         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6395           // This is an explicit specialization or a partial specialization.
6396           // FIXME: Check that we can declare a specialization here.
6397           IsVariableTemplateSpecialization = true;
6398           IsPartialSpecialization = TemplateParams->size() > 0;
6399         } else { // if (TemplateParams->size() > 0)
6400           // This is a template declaration.
6401           IsVariableTemplate = true;
6402 
6403           // Check that we can declare a template here.
6404           if (CheckTemplateDeclScope(S, TemplateParams))
6405             return nullptr;
6406 
6407           // Only C++1y supports variable templates (N3651).
6408           Diag(D.getIdentifierLoc(),
6409                getLangOpts().CPlusPlus14
6410                    ? diag::warn_cxx11_compat_variable_template
6411                    : diag::ext_variable_template);
6412         }
6413       }
6414     } else {
6415       assert(
6416           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6417           "should have a 'template<>' for this decl");
6418     }
6419 
6420     if (IsVariableTemplateSpecialization) {
6421       SourceLocation TemplateKWLoc =
6422           TemplateParamLists.size() > 0
6423               ? TemplateParamLists[0]->getTemplateLoc()
6424               : SourceLocation();
6425       DeclResult Res = ActOnVarTemplateSpecialization(
6426           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6427           IsPartialSpecialization);
6428       if (Res.isInvalid())
6429         return nullptr;
6430       NewVD = cast<VarDecl>(Res.get());
6431       AddToScope = false;
6432     } else if (D.isDecompositionDeclarator()) {
6433       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6434                                         D.getIdentifierLoc(), R, TInfo, SC,
6435                                         Bindings);
6436     } else
6437       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6438                               D.getIdentifierLoc(), II, R, TInfo, SC);
6439 
6440     // If this is supposed to be a variable template, create it as such.
6441     if (IsVariableTemplate) {
6442       NewTemplate =
6443           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6444                                   TemplateParams, NewVD);
6445       NewVD->setDescribedVarTemplate(NewTemplate);
6446     }
6447 
6448     // If this decl has an auto type in need of deduction, make a note of the
6449     // Decl so we can diagnose uses of it in its own initializer.
6450     if (R->getContainedDeducedType())
6451       ParsingInitForAutoVars.insert(NewVD);
6452 
6453     if (D.isInvalidType() || Invalid) {
6454       NewVD->setInvalidDecl();
6455       if (NewTemplate)
6456         NewTemplate->setInvalidDecl();
6457     }
6458 
6459     SetNestedNameSpecifier(NewVD, D);
6460 
6461     // If we have any template parameter lists that don't directly belong to
6462     // the variable (matching the scope specifier), store them.
6463     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6464     if (TemplateParamLists.size() > VDTemplateParamLists)
6465       NewVD->setTemplateParameterListsInfo(
6466           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6467 
6468     if (D.getDeclSpec().isConstexprSpecified()) {
6469       NewVD->setConstexpr(true);
6470       // C++1z [dcl.spec.constexpr]p1:
6471       //   A static data member declared with the constexpr specifier is
6472       //   implicitly an inline variable.
6473       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6474         NewVD->setImplicitlyInline();
6475     }
6476 
6477     if (D.getDeclSpec().isConceptSpecified()) {
6478       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6479         VTD->setConcept();
6480 
6481       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6482       // be declared with the thread_local, inline, friend, or constexpr
6483       // specifiers, [...]
6484       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6485         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6486              diag::err_concept_decl_invalid_specifiers)
6487             << 0 << 0;
6488         NewVD->setInvalidDecl(true);
6489       }
6490 
6491       if (D.getDeclSpec().isConstexprSpecified()) {
6492         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6493              diag::err_concept_decl_invalid_specifiers)
6494             << 0 << 3;
6495         NewVD->setInvalidDecl(true);
6496       }
6497 
6498       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6499       // applied only to the definition of a function template or variable
6500       // template, declared in namespace scope.
6501       if (IsVariableTemplateSpecialization) {
6502         Diag(D.getDeclSpec().getConceptSpecLoc(),
6503              diag::err_concept_specified_specialization)
6504             << (IsPartialSpecialization ? 2 : 1);
6505       }
6506 
6507       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6508       // following restrictions:
6509       // - The declared type shall have the type bool.
6510       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6511           !NewVD->isInvalidDecl()) {
6512         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6513         NewVD->setInvalidDecl(true);
6514       }
6515     }
6516   }
6517 
6518   if (D.getDeclSpec().isInlineSpecified()) {
6519     if (!getLangOpts().CPlusPlus) {
6520       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6521           << 0;
6522     } else if (CurContext->isFunctionOrMethod()) {
6523       // 'inline' is not allowed on block scope variable declaration.
6524       Diag(D.getDeclSpec().getInlineSpecLoc(),
6525            diag::err_inline_declaration_block_scope) << Name
6526         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6527     } else {
6528       Diag(D.getDeclSpec().getInlineSpecLoc(),
6529            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6530                                      : diag::ext_inline_variable);
6531       NewVD->setInlineSpecified();
6532     }
6533   }
6534 
6535   // Set the lexical context. If the declarator has a C++ scope specifier, the
6536   // lexical context will be different from the semantic context.
6537   NewVD->setLexicalDeclContext(CurContext);
6538   if (NewTemplate)
6539     NewTemplate->setLexicalDeclContext(CurContext);
6540 
6541   if (IsLocalExternDecl) {
6542     if (D.isDecompositionDeclarator())
6543       for (auto *B : Bindings)
6544         B->setLocalExternDecl();
6545     else
6546       NewVD->setLocalExternDecl();
6547   }
6548 
6549   bool EmitTLSUnsupportedError = false;
6550   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6551     // C++11 [dcl.stc]p4:
6552     //   When thread_local is applied to a variable of block scope the
6553     //   storage-class-specifier static is implied if it does not appear
6554     //   explicitly.
6555     // Core issue: 'static' is not implied if the variable is declared
6556     //   'extern'.
6557     if (NewVD->hasLocalStorage() &&
6558         (SCSpec != DeclSpec::SCS_unspecified ||
6559          TSCS != DeclSpec::TSCS_thread_local ||
6560          !DC->isFunctionOrMethod()))
6561       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6562            diag::err_thread_non_global)
6563         << DeclSpec::getSpecifierName(TSCS);
6564     else if (!Context.getTargetInfo().isTLSSupported()) {
6565       if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6566         // Postpone error emission until we've collected attributes required to
6567         // figure out whether it's a host or device variable and whether the
6568         // error should be ignored.
6569         EmitTLSUnsupportedError = true;
6570         // We still need to mark the variable as TLS so it shows up in AST with
6571         // proper storage class for other tools to use even if we're not going
6572         // to emit any code for it.
6573         NewVD->setTSCSpec(TSCS);
6574       } else
6575         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6576              diag::err_thread_unsupported);
6577     } else
6578       NewVD->setTSCSpec(TSCS);
6579   }
6580 
6581   // C99 6.7.4p3
6582   //   An inline definition of a function with external linkage shall
6583   //   not contain a definition of a modifiable object with static or
6584   //   thread storage duration...
6585   // We only apply this when the function is required to be defined
6586   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6587   // that a local variable with thread storage duration still has to
6588   // be marked 'static'.  Also note that it's possible to get these
6589   // semantics in C++ using __attribute__((gnu_inline)).
6590   if (SC == SC_Static && S->getFnParent() != nullptr &&
6591       !NewVD->getType().isConstQualified()) {
6592     FunctionDecl *CurFD = getCurFunctionDecl();
6593     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6594       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6595            diag::warn_static_local_in_extern_inline);
6596       MaybeSuggestAddingStaticToDecl(CurFD);
6597     }
6598   }
6599 
6600   if (D.getDeclSpec().isModulePrivateSpecified()) {
6601     if (IsVariableTemplateSpecialization)
6602       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6603           << (IsPartialSpecialization ? 1 : 0)
6604           << FixItHint::CreateRemoval(
6605                  D.getDeclSpec().getModulePrivateSpecLoc());
6606     else if (IsMemberSpecialization)
6607       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6608         << 2
6609         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6610     else if (NewVD->hasLocalStorage())
6611       Diag(NewVD->getLocation(), diag::err_module_private_local)
6612         << 0 << NewVD->getDeclName()
6613         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6614         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6615     else {
6616       NewVD->setModulePrivate();
6617       if (NewTemplate)
6618         NewTemplate->setModulePrivate();
6619       for (auto *B : Bindings)
6620         B->setModulePrivate();
6621     }
6622   }
6623 
6624   // Handle attributes prior to checking for duplicates in MergeVarDecl
6625   ProcessDeclAttributes(S, NewVD, D);
6626 
6627   if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6628     if (EmitTLSUnsupportedError &&
6629         ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6630          (getLangOpts().OpenMPIsDevice &&
6631           NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6632       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6633            diag::err_thread_unsupported);
6634     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6635     // storage [duration]."
6636     if (SC == SC_None && S->getFnParent() != nullptr &&
6637         (NewVD->hasAttr<CUDASharedAttr>() ||
6638          NewVD->hasAttr<CUDAConstantAttr>())) {
6639       NewVD->setStorageClass(SC_Static);
6640     }
6641   }
6642 
6643   // Ensure that dllimport globals without explicit storage class are treated as
6644   // extern. The storage class is set above using parsed attributes. Now we can
6645   // check the VarDecl itself.
6646   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6647          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6648          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6649 
6650   // In auto-retain/release, infer strong retension for variables of
6651   // retainable type.
6652   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6653     NewVD->setInvalidDecl();
6654 
6655   // Handle GNU asm-label extension (encoded as an attribute).
6656   if (Expr *E = (Expr*)D.getAsmLabel()) {
6657     // The parser guarantees this is a string.
6658     StringLiteral *SE = cast<StringLiteral>(E);
6659     StringRef Label = SE->getString();
6660     if (S->getFnParent() != nullptr) {
6661       switch (SC) {
6662       case SC_None:
6663       case SC_Auto:
6664         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6665         break;
6666       case SC_Register:
6667         // Local Named register
6668         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6669             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6670           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6671         break;
6672       case SC_Static:
6673       case SC_Extern:
6674       case SC_PrivateExtern:
6675         break;
6676       }
6677     } else if (SC == SC_Register) {
6678       // Global Named register
6679       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6680         const auto &TI = Context.getTargetInfo();
6681         bool HasSizeMismatch;
6682 
6683         if (!TI.isValidGCCRegisterName(Label))
6684           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6685         else if (!TI.validateGlobalRegisterVariable(Label,
6686                                                     Context.getTypeSize(R),
6687                                                     HasSizeMismatch))
6688           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6689         else if (HasSizeMismatch)
6690           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6691       }
6692 
6693       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6694         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6695         NewVD->setInvalidDecl(true);
6696       }
6697     }
6698 
6699     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6700                                                 Context, Label, 0));
6701   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6702     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6703       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6704     if (I != ExtnameUndeclaredIdentifiers.end()) {
6705       if (isDeclExternC(NewVD)) {
6706         NewVD->addAttr(I->second);
6707         ExtnameUndeclaredIdentifiers.erase(I);
6708       } else
6709         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6710             << /*Variable*/1 << NewVD;
6711     }
6712   }
6713 
6714   // Find the shadowed declaration before filtering for scope.
6715   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6716                                 ? getShadowedDeclaration(NewVD, Previous)
6717                                 : nullptr;
6718 
6719   // Don't consider existing declarations that are in a different
6720   // scope and are out-of-semantic-context declarations (if the new
6721   // declaration has linkage).
6722   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6723                        D.getCXXScopeSpec().isNotEmpty() ||
6724                        IsMemberSpecialization ||
6725                        IsVariableTemplateSpecialization);
6726 
6727   // Check whether the previous declaration is in the same block scope. This
6728   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6729   if (getLangOpts().CPlusPlus &&
6730       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6731     NewVD->setPreviousDeclInSameBlockScope(
6732         Previous.isSingleResult() && !Previous.isShadowed() &&
6733         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6734 
6735   if (!getLangOpts().CPlusPlus) {
6736     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6737   } else {
6738     // If this is an explicit specialization of a static data member, check it.
6739     if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6740         CheckMemberSpecialization(NewVD, Previous))
6741       NewVD->setInvalidDecl();
6742 
6743     // Merge the decl with the existing one if appropriate.
6744     if (!Previous.empty()) {
6745       if (Previous.isSingleResult() &&
6746           isa<FieldDecl>(Previous.getFoundDecl()) &&
6747           D.getCXXScopeSpec().isSet()) {
6748         // The user tried to define a non-static data member
6749         // out-of-line (C++ [dcl.meaning]p1).
6750         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6751           << D.getCXXScopeSpec().getRange();
6752         Previous.clear();
6753         NewVD->setInvalidDecl();
6754       }
6755     } else if (D.getCXXScopeSpec().isSet()) {
6756       // No previous declaration in the qualifying scope.
6757       Diag(D.getIdentifierLoc(), diag::err_no_member)
6758         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6759         << D.getCXXScopeSpec().getRange();
6760       NewVD->setInvalidDecl();
6761     }
6762 
6763     if (!IsVariableTemplateSpecialization)
6764       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6765 
6766     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6767     // an explicit specialization (14.8.3) or a partial specialization of a
6768     // concept definition.
6769     if (IsVariableTemplateSpecialization &&
6770         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6771         Previous.isSingleResult()) {
6772       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6773       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6774         if (VarTmpl->isConcept()) {
6775           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6776               << 1                            /*variable*/
6777               << (IsPartialSpecialization ? 2 /*partially specialized*/
6778                                           : 1 /*explicitly specialized*/);
6779           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6780           NewVD->setInvalidDecl();
6781         }
6782       }
6783     }
6784 
6785     if (NewTemplate) {
6786       VarTemplateDecl *PrevVarTemplate =
6787           NewVD->getPreviousDecl()
6788               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6789               : nullptr;
6790 
6791       // Check the template parameter list of this declaration, possibly
6792       // merging in the template parameter list from the previous variable
6793       // template declaration.
6794       if (CheckTemplateParameterList(
6795               TemplateParams,
6796               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6797                               : nullptr,
6798               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6799                DC->isDependentContext())
6800                   ? TPC_ClassTemplateMember
6801                   : TPC_VarTemplate))
6802         NewVD->setInvalidDecl();
6803 
6804       // If we are providing an explicit specialization of a static variable
6805       // template, make a note of that.
6806       if (PrevVarTemplate &&
6807           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6808         PrevVarTemplate->setMemberSpecialization();
6809     }
6810   }
6811 
6812   // Diagnose shadowed variables iff this isn't a redeclaration.
6813   if (ShadowedDecl && !D.isRedeclaration())
6814     CheckShadow(NewVD, ShadowedDecl, Previous);
6815 
6816   ProcessPragmaWeak(S, NewVD);
6817 
6818   // If this is the first declaration of an extern C variable, update
6819   // the map of such variables.
6820   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6821       isIncompleteDeclExternC(*this, NewVD))
6822     RegisterLocallyScopedExternCDecl(NewVD, S);
6823 
6824   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6825     Decl *ManglingContextDecl;
6826     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6827             NewVD->getDeclContext(), ManglingContextDecl)) {
6828       Context.setManglingNumber(
6829           NewVD, MCtx->getManglingNumber(
6830                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6831       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6832     }
6833   }
6834 
6835   // Special handling of variable named 'main'.
6836   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6837       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6838       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6839 
6840     // C++ [basic.start.main]p3
6841     // A program that declares a variable main at global scope is ill-formed.
6842     if (getLangOpts().CPlusPlus)
6843       Diag(D.getLocStart(), diag::err_main_global_variable);
6844 
6845     // In C, and external-linkage variable named main results in undefined
6846     // behavior.
6847     else if (NewVD->hasExternalFormalLinkage())
6848       Diag(D.getLocStart(), diag::warn_main_redefined);
6849   }
6850 
6851   if (D.isRedeclaration() && !Previous.empty()) {
6852     checkDLLAttributeRedeclaration(
6853         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6854         IsMemberSpecialization, D.isFunctionDefinition());
6855   }
6856 
6857   if (NewTemplate) {
6858     if (NewVD->isInvalidDecl())
6859       NewTemplate->setInvalidDecl();
6860     ActOnDocumentableDecl(NewTemplate);
6861     return NewTemplate;
6862   }
6863 
6864   if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6865     CompleteMemberSpecialization(NewVD, Previous);
6866 
6867   return NewVD;
6868 }
6869 
6870 /// Enum describing the %select options in diag::warn_decl_shadow.
6871 enum ShadowedDeclKind {
6872   SDK_Local,
6873   SDK_Global,
6874   SDK_StaticMember,
6875   SDK_Field,
6876   SDK_Typedef,
6877   SDK_Using
6878 };
6879 
6880 /// Determine what kind of declaration we're shadowing.
6881 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6882                                                 const DeclContext *OldDC) {
6883   if (isa<TypeAliasDecl>(ShadowedDecl))
6884     return SDK_Using;
6885   else if (isa<TypedefDecl>(ShadowedDecl))
6886     return SDK_Typedef;
6887   else if (isa<RecordDecl>(OldDC))
6888     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6889 
6890   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6891 }
6892 
6893 /// Return the location of the capture if the given lambda captures the given
6894 /// variable \p VD, or an invalid source location otherwise.
6895 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6896                                          const VarDecl *VD) {
6897   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6898     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6899       return Capture.getLocation();
6900   }
6901   return SourceLocation();
6902 }
6903 
6904 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6905                                      const LookupResult &R) {
6906   // Only diagnose if we're shadowing an unambiguous field or variable.
6907   if (R.getResultKind() != LookupResult::Found)
6908     return false;
6909 
6910   // Return false if warning is ignored.
6911   return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6912 }
6913 
6914 /// \brief Return the declaration shadowed by the given variable \p D, or null
6915 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6916 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6917                                         const LookupResult &R) {
6918   if (!shouldWarnIfShadowedDecl(Diags, R))
6919     return nullptr;
6920 
6921   // Don't diagnose declarations at file scope.
6922   if (D->hasGlobalStorage())
6923     return nullptr;
6924 
6925   NamedDecl *ShadowedDecl = R.getFoundDecl();
6926   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6927              ? ShadowedDecl
6928              : nullptr;
6929 }
6930 
6931 /// \brief Return the declaration shadowed by the given typedef \p D, or null
6932 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6933 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6934                                         const LookupResult &R) {
6935   // Don't warn if typedef declaration is part of a class
6936   if (D->getDeclContext()->isRecord())
6937     return nullptr;
6938 
6939   if (!shouldWarnIfShadowedDecl(Diags, R))
6940     return nullptr;
6941 
6942   NamedDecl *ShadowedDecl = R.getFoundDecl();
6943   return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6944 }
6945 
6946 /// \brief Diagnose variable or built-in function shadowing.  Implements
6947 /// -Wshadow.
6948 ///
6949 /// This method is called whenever a VarDecl is added to a "useful"
6950 /// scope.
6951 ///
6952 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6953 /// \param R the lookup of the name
6954 ///
6955 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6956                        const LookupResult &R) {
6957   DeclContext *NewDC = D->getDeclContext();
6958 
6959   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6960     // Fields are not shadowed by variables in C++ static methods.
6961     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6962       if (MD->isStatic())
6963         return;
6964 
6965     // Fields shadowed by constructor parameters are a special case. Usually
6966     // the constructor initializes the field with the parameter.
6967     if (isa<CXXConstructorDecl>(NewDC))
6968       if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6969         // Remember that this was shadowed so we can either warn about its
6970         // modification or its existence depending on warning settings.
6971         ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6972         return;
6973       }
6974   }
6975 
6976   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6977     if (shadowedVar->isExternC()) {
6978       // For shadowing external vars, make sure that we point to the global
6979       // declaration, not a locally scoped extern declaration.
6980       for (auto I : shadowedVar->redecls())
6981         if (I->isFileVarDecl()) {
6982           ShadowedDecl = I;
6983           break;
6984         }
6985     }
6986 
6987   DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6988 
6989   unsigned WarningDiag = diag::warn_decl_shadow;
6990   SourceLocation CaptureLoc;
6991   if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6992       isa<CXXMethodDecl>(NewDC)) {
6993     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6994       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6995         if (RD->getLambdaCaptureDefault() == LCD_None) {
6996           // Try to avoid warnings for lambdas with an explicit capture list.
6997           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6998           // Warn only when the lambda captures the shadowed decl explicitly.
6999           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7000           if (CaptureLoc.isInvalid())
7001             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7002         } else {
7003           // Remember that this was shadowed so we can avoid the warning if the
7004           // shadowed decl isn't captured and the warning settings allow it.
7005           cast<LambdaScopeInfo>(getCurFunction())
7006               ->ShadowingDecls.push_back(
7007                   {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7008           return;
7009         }
7010       }
7011 
7012       if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7013         // A variable can't shadow a local variable in an enclosing scope, if
7014         // they are separated by a non-capturing declaration context.
7015         for (DeclContext *ParentDC = NewDC;
7016              ParentDC && !ParentDC->Equals(OldDC);
7017              ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7018           // Only block literals, captured statements, and lambda expressions
7019           // can capture; other scopes don't.
7020           if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7021               !isLambdaCallOperator(ParentDC)) {
7022             return;
7023           }
7024         }
7025       }
7026     }
7027   }
7028 
7029   // Only warn about certain kinds of shadowing for class members.
7030   if (NewDC && NewDC->isRecord()) {
7031     // In particular, don't warn about shadowing non-class members.
7032     if (!OldDC->isRecord())
7033       return;
7034 
7035     // TODO: should we warn about static data members shadowing
7036     // static data members from base classes?
7037 
7038     // TODO: don't diagnose for inaccessible shadowed members.
7039     // This is hard to do perfectly because we might friend the
7040     // shadowing context, but that's just a false negative.
7041   }
7042 
7043 
7044   DeclarationName Name = R.getLookupName();
7045 
7046   // Emit warning and note.
7047   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7048     return;
7049   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7050   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7051   if (!CaptureLoc.isInvalid())
7052     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7053         << Name << /*explicitly*/ 1;
7054   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7055 }
7056 
7057 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7058 /// when these variables are captured by the lambda.
7059 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7060   for (const auto &Shadow : LSI->ShadowingDecls) {
7061     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7062     // Try to avoid the warning when the shadowed decl isn't captured.
7063     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7064     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7065     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7066                                        ? diag::warn_decl_shadow_uncaptured_local
7067                                        : diag::warn_decl_shadow)
7068         << Shadow.VD->getDeclName()
7069         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7070     if (!CaptureLoc.isInvalid())
7071       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7072           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7073     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7074   }
7075 }
7076 
7077 /// \brief Check -Wshadow without the advantage of a previous lookup.
7078 void Sema::CheckShadow(Scope *S, VarDecl *D) {
7079   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7080     return;
7081 
7082   LookupResult R(*this, D->getDeclName(), D->getLocation(),
7083                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7084   LookupName(R, S);
7085   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7086     CheckShadow(D, ShadowedDecl, R);
7087 }
7088 
7089 /// Check if 'E', which is an expression that is about to be modified, refers
7090 /// to a constructor parameter that shadows a field.
7091 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7092   // Quickly ignore expressions that can't be shadowing ctor parameters.
7093   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7094     return;
7095   E = E->IgnoreParenImpCasts();
7096   auto *DRE = dyn_cast<DeclRefExpr>(E);
7097   if (!DRE)
7098     return;
7099   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7100   auto I = ShadowingDecls.find(D);
7101   if (I == ShadowingDecls.end())
7102     return;
7103   const NamedDecl *ShadowedDecl = I->second;
7104   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7105   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7106   Diag(D->getLocation(), diag::note_var_declared_here) << D;
7107   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7108 
7109   // Avoid issuing multiple warnings about the same decl.
7110   ShadowingDecls.erase(I);
7111 }
7112 
7113 /// Check for conflict between this global or extern "C" declaration and
7114 /// previous global or extern "C" declarations. This is only used in C++.
7115 template<typename T>
7116 static bool checkGlobalOrExternCConflict(
7117     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7118   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7119   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7120 
7121   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7122     // The common case: this global doesn't conflict with any extern "C"
7123     // declaration.
7124     return false;
7125   }
7126 
7127   if (Prev) {
7128     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7129       // Both the old and new declarations have C language linkage. This is a
7130       // redeclaration.
7131       Previous.clear();
7132       Previous.addDecl(Prev);
7133       return true;
7134     }
7135 
7136     // This is a global, non-extern "C" declaration, and there is a previous
7137     // non-global extern "C" declaration. Diagnose if this is a variable
7138     // declaration.
7139     if (!isa<VarDecl>(ND))
7140       return false;
7141   } else {
7142     // The declaration is extern "C". Check for any declaration in the
7143     // translation unit which might conflict.
7144     if (IsGlobal) {
7145       // We have already performed the lookup into the translation unit.
7146       IsGlobal = false;
7147       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7148            I != E; ++I) {
7149         if (isa<VarDecl>(*I)) {
7150           Prev = *I;
7151           break;
7152         }
7153       }
7154     } else {
7155       DeclContext::lookup_result R =
7156           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7157       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7158            I != E; ++I) {
7159         if (isa<VarDecl>(*I)) {
7160           Prev = *I;
7161           break;
7162         }
7163         // FIXME: If we have any other entity with this name in global scope,
7164         // the declaration is ill-formed, but that is a defect: it breaks the
7165         // 'stat' hack, for instance. Only variables can have mangled name
7166         // clashes with extern "C" declarations, so only they deserve a
7167         // diagnostic.
7168       }
7169     }
7170 
7171     if (!Prev)
7172       return false;
7173   }
7174 
7175   // Use the first declaration's location to ensure we point at something which
7176   // is lexically inside an extern "C" linkage-spec.
7177   assert(Prev && "should have found a previous declaration to diagnose");
7178   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7179     Prev = FD->getFirstDecl();
7180   else
7181     Prev = cast<VarDecl>(Prev)->getFirstDecl();
7182 
7183   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7184     << IsGlobal << ND;
7185   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7186     << IsGlobal;
7187   return false;
7188 }
7189 
7190 /// Apply special rules for handling extern "C" declarations. Returns \c true
7191 /// if we have found that this is a redeclaration of some prior entity.
7192 ///
7193 /// Per C++ [dcl.link]p6:
7194 ///   Two declarations [for a function or variable] with C language linkage
7195 ///   with the same name that appear in different scopes refer to the same
7196 ///   [entity]. An entity with C language linkage shall not be declared with
7197 ///   the same name as an entity in global scope.
7198 template<typename T>
7199 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7200                                                   LookupResult &Previous) {
7201   if (!S.getLangOpts().CPlusPlus) {
7202     // In C, when declaring a global variable, look for a corresponding 'extern'
7203     // variable declared in function scope. We don't need this in C++, because
7204     // we find local extern decls in the surrounding file-scope DeclContext.
7205     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7206       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7207         Previous.clear();
7208         Previous.addDecl(Prev);
7209         return true;
7210       }
7211     }
7212     return false;
7213   }
7214 
7215   // A declaration in the translation unit can conflict with an extern "C"
7216   // declaration.
7217   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7218     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7219 
7220   // An extern "C" declaration can conflict with a declaration in the
7221   // translation unit or can be a redeclaration of an extern "C" declaration
7222   // in another scope.
7223   if (isIncompleteDeclExternC(S,ND))
7224     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7225 
7226   // Neither global nor extern "C": nothing to do.
7227   return false;
7228 }
7229 
7230 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7231   // If the decl is already known invalid, don't check it.
7232   if (NewVD->isInvalidDecl())
7233     return;
7234 
7235   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7236   QualType T = TInfo->getType();
7237 
7238   // Defer checking an 'auto' type until its initializer is attached.
7239   if (T->isUndeducedType())
7240     return;
7241 
7242   if (NewVD->hasAttrs())
7243     CheckAlignasUnderalignment(NewVD);
7244 
7245   if (T->isObjCObjectType()) {
7246     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7247       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7248     T = Context.getObjCObjectPointerType(T);
7249     NewVD->setType(T);
7250   }
7251 
7252   // Emit an error if an address space was applied to decl with local storage.
7253   // This includes arrays of objects with address space qualifiers, but not
7254   // automatic variables that point to other address spaces.
7255   // ISO/IEC TR 18037 S5.1.2
7256   if (!getLangOpts().OpenCL
7257       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7258     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7259     NewVD->setInvalidDecl();
7260     return;
7261   }
7262 
7263   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7264   // scope.
7265   if (getLangOpts().OpenCLVersion == 120 &&
7266       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7267       NewVD->isStaticLocal()) {
7268     Diag(NewVD->getLocation(), diag::err_static_function_scope);
7269     NewVD->setInvalidDecl();
7270     return;
7271   }
7272 
7273   if (getLangOpts().OpenCL) {
7274     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7275     if (NewVD->hasAttr<BlocksAttr>()) {
7276       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7277       return;
7278     }
7279 
7280     if (T->isBlockPointerType()) {
7281       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7282       // can't use 'extern' storage class.
7283       if (!T.isConstQualified()) {
7284         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7285             << 0 /*const*/;
7286         NewVD->setInvalidDecl();
7287         return;
7288       }
7289       if (NewVD->hasExternalStorage()) {
7290         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7291         NewVD->setInvalidDecl();
7292         return;
7293       }
7294     }
7295     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7296     // __constant address space.
7297     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7298     // variables inside a function can also be declared in the global
7299     // address space.
7300     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7301         NewVD->hasExternalStorage()) {
7302       if (!T->isSamplerT() &&
7303           !(T.getAddressSpace() == LangAS::opencl_constant ||
7304             (T.getAddressSpace() == LangAS::opencl_global &&
7305              getLangOpts().OpenCLVersion == 200))) {
7306         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7307         if (getLangOpts().OpenCLVersion == 200)
7308           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7309               << Scope << "global or constant";
7310         else
7311           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7312               << Scope << "constant";
7313         NewVD->setInvalidDecl();
7314         return;
7315       }
7316     } else {
7317       if (T.getAddressSpace() == LangAS::opencl_global) {
7318         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7319             << 1 /*is any function*/ << "global";
7320         NewVD->setInvalidDecl();
7321         return;
7322       }
7323       if (T.getAddressSpace() == LangAS::opencl_constant ||
7324           T.getAddressSpace() == LangAS::opencl_local) {
7325         FunctionDecl *FD = getCurFunctionDecl();
7326         // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7327         // in functions.
7328         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7329           if (T.getAddressSpace() == LangAS::opencl_constant)
7330             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7331                 << 0 /*non-kernel only*/ << "constant";
7332           else
7333             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7334                 << 0 /*non-kernel only*/ << "local";
7335           NewVD->setInvalidDecl();
7336           return;
7337         }
7338         // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7339         // in the outermost scope of a kernel function.
7340         if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7341           if (!getCurScope()->isFunctionScope()) {
7342             if (T.getAddressSpace() == LangAS::opencl_constant)
7343               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7344                   << "constant";
7345             else
7346               Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7347                   << "local";
7348             NewVD->setInvalidDecl();
7349             return;
7350           }
7351         }
7352       } else if (T.getAddressSpace() != LangAS::Default) {
7353         // Do not allow other address spaces on automatic variable.
7354         Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7355         NewVD->setInvalidDecl();
7356         return;
7357       }
7358     }
7359   }
7360 
7361   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7362       && !NewVD->hasAttr<BlocksAttr>()) {
7363     if (getLangOpts().getGC() != LangOptions::NonGC)
7364       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7365     else {
7366       assert(!getLangOpts().ObjCAutoRefCount);
7367       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7368     }
7369   }
7370 
7371   bool isVM = T->isVariablyModifiedType();
7372   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7373       NewVD->hasAttr<BlocksAttr>())
7374     getCurFunction()->setHasBranchProtectedScope();
7375 
7376   if ((isVM && NewVD->hasLinkage()) ||
7377       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7378     bool SizeIsNegative;
7379     llvm::APSInt Oversized;
7380     TypeSourceInfo *FixedTInfo =
7381       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7382                                                     SizeIsNegative, Oversized);
7383     if (!FixedTInfo && T->isVariableArrayType()) {
7384       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7385       // FIXME: This won't give the correct result for
7386       // int a[10][n];
7387       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7388 
7389       if (NewVD->isFileVarDecl())
7390         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7391         << SizeRange;
7392       else if (NewVD->isStaticLocal())
7393         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7394         << SizeRange;
7395       else
7396         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7397         << SizeRange;
7398       NewVD->setInvalidDecl();
7399       return;
7400     }
7401 
7402     if (!FixedTInfo) {
7403       if (NewVD->isFileVarDecl())
7404         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7405       else
7406         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7407       NewVD->setInvalidDecl();
7408       return;
7409     }
7410 
7411     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7412     NewVD->setType(FixedTInfo->getType());
7413     NewVD->setTypeSourceInfo(FixedTInfo);
7414   }
7415 
7416   if (T->isVoidType()) {
7417     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7418     //                    of objects and functions.
7419     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7420       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7421         << T;
7422       NewVD->setInvalidDecl();
7423       return;
7424     }
7425   }
7426 
7427   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7428     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7429     NewVD->setInvalidDecl();
7430     return;
7431   }
7432 
7433   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7434     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7435     NewVD->setInvalidDecl();
7436     return;
7437   }
7438 
7439   if (NewVD->isConstexpr() && !T->isDependentType() &&
7440       RequireLiteralType(NewVD->getLocation(), T,
7441                          diag::err_constexpr_var_non_literal)) {
7442     NewVD->setInvalidDecl();
7443     return;
7444   }
7445 }
7446 
7447 /// \brief Perform semantic checking on a newly-created variable
7448 /// declaration.
7449 ///
7450 /// This routine performs all of the type-checking required for a
7451 /// variable declaration once it has been built. It is used both to
7452 /// check variables after they have been parsed and their declarators
7453 /// have been translated into a declaration, and to check variables
7454 /// that have been instantiated from a template.
7455 ///
7456 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7457 ///
7458 /// Returns true if the variable declaration is a redeclaration.
7459 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7460   CheckVariableDeclarationType(NewVD);
7461 
7462   // If the decl is already known invalid, don't check it.
7463   if (NewVD->isInvalidDecl())
7464     return false;
7465 
7466   // If we did not find anything by this name, look for a non-visible
7467   // extern "C" declaration with the same name.
7468   if (Previous.empty() &&
7469       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7470     Previous.setShadowed();
7471 
7472   if (!Previous.empty()) {
7473     MergeVarDecl(NewVD, Previous);
7474     return true;
7475   }
7476   return false;
7477 }
7478 
7479 namespace {
7480 struct FindOverriddenMethod {
7481   Sema *S;
7482   CXXMethodDecl *Method;
7483 
7484   /// Member lookup function that determines whether a given C++
7485   /// method overrides a method in a base class, to be used with
7486   /// CXXRecordDecl::lookupInBases().
7487   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7488     RecordDecl *BaseRecord =
7489         Specifier->getType()->getAs<RecordType>()->getDecl();
7490 
7491     DeclarationName Name = Method->getDeclName();
7492 
7493     // FIXME: Do we care about other names here too?
7494     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7495       // We really want to find the base class destructor here.
7496       QualType T = S->Context.getTypeDeclType(BaseRecord);
7497       CanQualType CT = S->Context.getCanonicalType(T);
7498 
7499       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7500     }
7501 
7502     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7503          Path.Decls = Path.Decls.slice(1)) {
7504       NamedDecl *D = Path.Decls.front();
7505       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7506         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7507           return true;
7508       }
7509     }
7510 
7511     return false;
7512   }
7513 };
7514 
7515 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7516 } // end anonymous namespace
7517 
7518 /// \brief Report an error regarding overriding, along with any relevant
7519 /// overriden methods.
7520 ///
7521 /// \param DiagID the primary error to report.
7522 /// \param MD the overriding method.
7523 /// \param OEK which overrides to include as notes.
7524 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7525                             OverrideErrorKind OEK = OEK_All) {
7526   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7527   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7528                                       E = MD->end_overridden_methods();
7529        I != E; ++I) {
7530     // This check (& the OEK parameter) could be replaced by a predicate, but
7531     // without lambdas that would be overkill. This is still nicer than writing
7532     // out the diag loop 3 times.
7533     if ((OEK == OEK_All) ||
7534         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7535         (OEK == OEK_Deleted && (*I)->isDeleted()))
7536       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7537   }
7538 }
7539 
7540 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7541 /// and if so, check that it's a valid override and remember it.
7542 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7543   // Look for methods in base classes that this method might override.
7544   CXXBasePaths Paths;
7545   FindOverriddenMethod FOM;
7546   FOM.Method = MD;
7547   FOM.S = this;
7548   bool hasDeletedOverridenMethods = false;
7549   bool hasNonDeletedOverridenMethods = false;
7550   bool AddedAny = false;
7551   if (DC->lookupInBases(FOM, Paths)) {
7552     for (auto *I : Paths.found_decls()) {
7553       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7554         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7555         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7556             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7557             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7558             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7559           hasDeletedOverridenMethods |= OldMD->isDeleted();
7560           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7561           AddedAny = true;
7562         }
7563       }
7564     }
7565   }
7566 
7567   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7568     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7569   }
7570   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7571     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7572   }
7573 
7574   return AddedAny;
7575 }
7576 
7577 namespace {
7578   // Struct for holding all of the extra arguments needed by
7579   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7580   struct ActOnFDArgs {
7581     Scope *S;
7582     Declarator &D;
7583     MultiTemplateParamsArg TemplateParamLists;
7584     bool AddToScope;
7585   };
7586 } // end anonymous namespace
7587 
7588 namespace {
7589 
7590 // Callback to only accept typo corrections that have a non-zero edit distance.
7591 // Also only accept corrections that have the same parent decl.
7592 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7593  public:
7594   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7595                             CXXRecordDecl *Parent)
7596       : Context(Context), OriginalFD(TypoFD),
7597         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7598 
7599   bool ValidateCandidate(const TypoCorrection &candidate) override {
7600     if (candidate.getEditDistance() == 0)
7601       return false;
7602 
7603     SmallVector<unsigned, 1> MismatchedParams;
7604     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7605                                           CDeclEnd = candidate.end();
7606          CDecl != CDeclEnd; ++CDecl) {
7607       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7608 
7609       if (FD && !FD->hasBody() &&
7610           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7611         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7612           CXXRecordDecl *Parent = MD->getParent();
7613           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7614             return true;
7615         } else if (!ExpectedParent) {
7616           return true;
7617         }
7618       }
7619     }
7620 
7621     return false;
7622   }
7623 
7624  private:
7625   ASTContext &Context;
7626   FunctionDecl *OriginalFD;
7627   CXXRecordDecl *ExpectedParent;
7628 };
7629 
7630 } // end anonymous namespace
7631 
7632 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7633   TypoCorrectedFunctionDefinitions.insert(F);
7634 }
7635 
7636 /// \brief Generate diagnostics for an invalid function redeclaration.
7637 ///
7638 /// This routine handles generating the diagnostic messages for an invalid
7639 /// function redeclaration, including finding possible similar declarations
7640 /// or performing typo correction if there are no previous declarations with
7641 /// the same name.
7642 ///
7643 /// Returns a NamedDecl iff typo correction was performed and substituting in
7644 /// the new declaration name does not cause new errors.
7645 static NamedDecl *DiagnoseInvalidRedeclaration(
7646     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7647     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7648   DeclarationName Name = NewFD->getDeclName();
7649   DeclContext *NewDC = NewFD->getDeclContext();
7650   SmallVector<unsigned, 1> MismatchedParams;
7651   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7652   TypoCorrection Correction;
7653   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7654   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7655                                    : diag::err_member_decl_does_not_match;
7656   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7657                     IsLocalFriend ? Sema::LookupLocalFriendName
7658                                   : Sema::LookupOrdinaryName,
7659                     Sema::ForRedeclaration);
7660 
7661   NewFD->setInvalidDecl();
7662   if (IsLocalFriend)
7663     SemaRef.LookupName(Prev, S);
7664   else
7665     SemaRef.LookupQualifiedName(Prev, NewDC);
7666   assert(!Prev.isAmbiguous() &&
7667          "Cannot have an ambiguity in previous-declaration lookup");
7668   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7669   if (!Prev.empty()) {
7670     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7671          Func != FuncEnd; ++Func) {
7672       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7673       if (FD &&
7674           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7675         // Add 1 to the index so that 0 can mean the mismatch didn't
7676         // involve a parameter
7677         unsigned ParamNum =
7678             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7679         NearMatches.push_back(std::make_pair(FD, ParamNum));
7680       }
7681     }
7682   // If the qualified name lookup yielded nothing, try typo correction
7683   } else if ((Correction = SemaRef.CorrectTypo(
7684                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7685                   &ExtraArgs.D.getCXXScopeSpec(),
7686                   llvm::make_unique<DifferentNameValidatorCCC>(
7687                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7688                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7689     // Set up everything for the call to ActOnFunctionDeclarator
7690     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7691                               ExtraArgs.D.getIdentifierLoc());
7692     Previous.clear();
7693     Previous.setLookupName(Correction.getCorrection());
7694     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7695                                     CDeclEnd = Correction.end();
7696          CDecl != CDeclEnd; ++CDecl) {
7697       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7698       if (FD && !FD->hasBody() &&
7699           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7700         Previous.addDecl(FD);
7701       }
7702     }
7703     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7704 
7705     NamedDecl *Result;
7706     // Retry building the function declaration with the new previous
7707     // declarations, and with errors suppressed.
7708     {
7709       // Trap errors.
7710       Sema::SFINAETrap Trap(SemaRef);
7711 
7712       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7713       // pieces need to verify the typo-corrected C++ declaration and hopefully
7714       // eliminate the need for the parameter pack ExtraArgs.
7715       Result = SemaRef.ActOnFunctionDeclarator(
7716           ExtraArgs.S, ExtraArgs.D,
7717           Correction.getCorrectionDecl()->getDeclContext(),
7718           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7719           ExtraArgs.AddToScope);
7720 
7721       if (Trap.hasErrorOccurred())
7722         Result = nullptr;
7723     }
7724 
7725     if (Result) {
7726       // Determine which correction we picked.
7727       Decl *Canonical = Result->getCanonicalDecl();
7728       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7729            I != E; ++I)
7730         if ((*I)->getCanonicalDecl() == Canonical)
7731           Correction.setCorrectionDecl(*I);
7732 
7733       // Let Sema know about the correction.
7734       SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7735       SemaRef.diagnoseTypo(
7736           Correction,
7737           SemaRef.PDiag(IsLocalFriend
7738                           ? diag::err_no_matching_local_friend_suggest
7739                           : diag::err_member_decl_does_not_match_suggest)
7740             << Name << NewDC << IsDefinition);
7741       return Result;
7742     }
7743 
7744     // Pretend the typo correction never occurred
7745     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7746                               ExtraArgs.D.getIdentifierLoc());
7747     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7748     Previous.clear();
7749     Previous.setLookupName(Name);
7750   }
7751 
7752   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7753       << Name << NewDC << IsDefinition << NewFD->getLocation();
7754 
7755   bool NewFDisConst = false;
7756   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7757     NewFDisConst = NewMD->isConst();
7758 
7759   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7760        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7761        NearMatch != NearMatchEnd; ++NearMatch) {
7762     FunctionDecl *FD = NearMatch->first;
7763     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7764     bool FDisConst = MD && MD->isConst();
7765     bool IsMember = MD || !IsLocalFriend;
7766 
7767     // FIXME: These notes are poorly worded for the local friend case.
7768     if (unsigned Idx = NearMatch->second) {
7769       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7770       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7771       if (Loc.isInvalid()) Loc = FD->getLocation();
7772       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7773                                  : diag::note_local_decl_close_param_match)
7774         << Idx << FDParam->getType()
7775         << NewFD->getParamDecl(Idx - 1)->getType();
7776     } else if (FDisConst != NewFDisConst) {
7777       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7778           << NewFDisConst << FD->getSourceRange().getEnd();
7779     } else
7780       SemaRef.Diag(FD->getLocation(),
7781                    IsMember ? diag::note_member_def_close_match
7782                             : diag::note_local_decl_close_match);
7783   }
7784   return nullptr;
7785 }
7786 
7787 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7788   switch (D.getDeclSpec().getStorageClassSpec()) {
7789   default: llvm_unreachable("Unknown storage class!");
7790   case DeclSpec::SCS_auto:
7791   case DeclSpec::SCS_register:
7792   case DeclSpec::SCS_mutable:
7793     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7794                  diag::err_typecheck_sclass_func);
7795     D.getMutableDeclSpec().ClearStorageClassSpecs();
7796     D.setInvalidType();
7797     break;
7798   case DeclSpec::SCS_unspecified: break;
7799   case DeclSpec::SCS_extern:
7800     if (D.getDeclSpec().isExternInLinkageSpec())
7801       return SC_None;
7802     return SC_Extern;
7803   case DeclSpec::SCS_static: {
7804     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7805       // C99 6.7.1p5:
7806       //   The declaration of an identifier for a function that has
7807       //   block scope shall have no explicit storage-class specifier
7808       //   other than extern
7809       // See also (C++ [dcl.stc]p4).
7810       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7811                    diag::err_static_block_func);
7812       break;
7813     } else
7814       return SC_Static;
7815   }
7816   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7817   }
7818 
7819   // No explicit storage class has already been returned
7820   return SC_None;
7821 }
7822 
7823 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7824                                            DeclContext *DC, QualType &R,
7825                                            TypeSourceInfo *TInfo,
7826                                            StorageClass SC,
7827                                            bool &IsVirtualOkay) {
7828   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7829   DeclarationName Name = NameInfo.getName();
7830 
7831   FunctionDecl *NewFD = nullptr;
7832   bool isInline = D.getDeclSpec().isInlineSpecified();
7833 
7834   if (!SemaRef.getLangOpts().CPlusPlus) {
7835     // Determine whether the function was written with a
7836     // prototype. This true when:
7837     //   - there is a prototype in the declarator, or
7838     //   - the type R of the function is some kind of typedef or other non-
7839     //     attributed reference to a type name (which eventually refers to a
7840     //     function type).
7841     bool HasPrototype =
7842       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7843       (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7844 
7845     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7846                                  D.getLocStart(), NameInfo, R,
7847                                  TInfo, SC, isInline,
7848                                  HasPrototype, false);
7849     if (D.isInvalidType())
7850       NewFD->setInvalidDecl();
7851 
7852     return NewFD;
7853   }
7854 
7855   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7856   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7857 
7858   // Check that the return type is not an abstract class type.
7859   // For record types, this is done by the AbstractClassUsageDiagnoser once
7860   // the class has been completely parsed.
7861   if (!DC->isRecord() &&
7862       SemaRef.RequireNonAbstractType(
7863           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7864           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7865     D.setInvalidType();
7866 
7867   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7868     // This is a C++ constructor declaration.
7869     assert(DC->isRecord() &&
7870            "Constructors can only be declared in a member context");
7871 
7872     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7873     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7874                                       D.getLocStart(), NameInfo,
7875                                       R, TInfo, isExplicit, isInline,
7876                                       /*isImplicitlyDeclared=*/false,
7877                                       isConstexpr);
7878 
7879   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7880     // This is a C++ destructor declaration.
7881     if (DC->isRecord()) {
7882       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7883       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7884       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7885                                         SemaRef.Context, Record,
7886                                         D.getLocStart(),
7887                                         NameInfo, R, TInfo, isInline,
7888                                         /*isImplicitlyDeclared=*/false);
7889 
7890       // If the class is complete, then we now create the implicit exception
7891       // specification. If the class is incomplete or dependent, we can't do
7892       // it yet.
7893       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7894           Record->getDefinition() && !Record->isBeingDefined() &&
7895           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7896         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7897       }
7898 
7899       IsVirtualOkay = true;
7900       return NewDD;
7901 
7902     } else {
7903       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7904       D.setInvalidType();
7905 
7906       // Create a FunctionDecl to satisfy the function definition parsing
7907       // code path.
7908       return FunctionDecl::Create(SemaRef.Context, DC,
7909                                   D.getLocStart(),
7910                                   D.getIdentifierLoc(), Name, R, TInfo,
7911                                   SC, isInline,
7912                                   /*hasPrototype=*/true, isConstexpr);
7913     }
7914 
7915   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7916     if (!DC->isRecord()) {
7917       SemaRef.Diag(D.getIdentifierLoc(),
7918            diag::err_conv_function_not_member);
7919       return nullptr;
7920     }
7921 
7922     SemaRef.CheckConversionDeclarator(D, R, SC);
7923     IsVirtualOkay = true;
7924     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7925                                      D.getLocStart(), NameInfo,
7926                                      R, TInfo, isInline, isExplicit,
7927                                      isConstexpr, SourceLocation());
7928 
7929   } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7930     SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7931 
7932     return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7933                                          isExplicit, NameInfo, R, TInfo,
7934                                          D.getLocEnd());
7935   } else if (DC->isRecord()) {
7936     // If the name of the function is the same as the name of the record,
7937     // then this must be an invalid constructor that has a return type.
7938     // (The parser checks for a return type and makes the declarator a
7939     // constructor if it has no return type).
7940     if (Name.getAsIdentifierInfo() &&
7941         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7942       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7943         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7944         << SourceRange(D.getIdentifierLoc());
7945       return nullptr;
7946     }
7947 
7948     // This is a C++ method declaration.
7949     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7950                                                cast<CXXRecordDecl>(DC),
7951                                                D.getLocStart(), NameInfo, R,
7952                                                TInfo, SC, isInline,
7953                                                isConstexpr, SourceLocation());
7954     IsVirtualOkay = !Ret->isStatic();
7955     return Ret;
7956   } else {
7957     bool isFriend =
7958         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7959     if (!isFriend && SemaRef.CurContext->isRecord())
7960       return nullptr;
7961 
7962     // Determine whether the function was written with a
7963     // prototype. This true when:
7964     //   - we're in C++ (where every function has a prototype),
7965     return FunctionDecl::Create(SemaRef.Context, DC,
7966                                 D.getLocStart(),
7967                                 NameInfo, R, TInfo, SC, isInline,
7968                                 true/*HasPrototype*/, isConstexpr);
7969   }
7970 }
7971 
7972 enum OpenCLParamType {
7973   ValidKernelParam,
7974   PtrPtrKernelParam,
7975   PtrKernelParam,
7976   InvalidAddrSpacePtrKernelParam,
7977   InvalidKernelParam,
7978   RecordKernelParam
7979 };
7980 
7981 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7982   if (PT->isPointerType()) {
7983     QualType PointeeType = PT->getPointeeType();
7984     if (PointeeType->isPointerType())
7985       return PtrPtrKernelParam;
7986     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7987         PointeeType.getAddressSpace() == 0)
7988       return InvalidAddrSpacePtrKernelParam;
7989     return PtrKernelParam;
7990   }
7991 
7992   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7993   // be used as builtin types.
7994 
7995   if (PT->isImageType())
7996     return PtrKernelParam;
7997 
7998   if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7999     return InvalidKernelParam;
8000 
8001   // OpenCL extension spec v1.2 s9.5:
8002   // This extension adds support for half scalar and vector types as built-in
8003   // types that can be used for arithmetic operations, conversions etc.
8004   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8005     return InvalidKernelParam;
8006 
8007   if (PT->isRecordType())
8008     return RecordKernelParam;
8009 
8010   return ValidKernelParam;
8011 }
8012 
8013 static void checkIsValidOpenCLKernelParameter(
8014   Sema &S,
8015   Declarator &D,
8016   ParmVarDecl *Param,
8017   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8018   QualType PT = Param->getType();
8019 
8020   // Cache the valid types we encounter to avoid rechecking structs that are
8021   // used again
8022   if (ValidTypes.count(PT.getTypePtr()))
8023     return;
8024 
8025   switch (getOpenCLKernelParameterType(S, PT)) {
8026   case PtrPtrKernelParam:
8027     // OpenCL v1.2 s6.9.a:
8028     // A kernel function argument cannot be declared as a
8029     // pointer to a pointer type.
8030     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8031     D.setInvalidType();
8032     return;
8033 
8034   case InvalidAddrSpacePtrKernelParam:
8035     // OpenCL v1.0 s6.5:
8036     // __kernel function arguments declared to be a pointer of a type can point
8037     // to one of the following address spaces only : __global, __local or
8038     // __constant.
8039     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8040     D.setInvalidType();
8041     return;
8042 
8043     // OpenCL v1.2 s6.9.k:
8044     // Arguments to kernel functions in a program cannot be declared with the
8045     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8046     // uintptr_t or a struct and/or union that contain fields declared to be
8047     // one of these built-in scalar types.
8048 
8049   case InvalidKernelParam:
8050     // OpenCL v1.2 s6.8 n:
8051     // A kernel function argument cannot be declared
8052     // of event_t type.
8053     // Do not diagnose half type since it is diagnosed as invalid argument
8054     // type for any function elsewhere.
8055     if (!PT->isHalfType())
8056       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8057     D.setInvalidType();
8058     return;
8059 
8060   case PtrKernelParam:
8061   case ValidKernelParam:
8062     ValidTypes.insert(PT.getTypePtr());
8063     return;
8064 
8065   case RecordKernelParam:
8066     break;
8067   }
8068 
8069   // Track nested structs we will inspect
8070   SmallVector<const Decl *, 4> VisitStack;
8071 
8072   // Track where we are in the nested structs. Items will migrate from
8073   // VisitStack to HistoryStack as we do the DFS for bad field.
8074   SmallVector<const FieldDecl *, 4> HistoryStack;
8075   HistoryStack.push_back(nullptr);
8076 
8077   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8078   VisitStack.push_back(PD);
8079 
8080   assert(VisitStack.back() && "First decl null?");
8081 
8082   do {
8083     const Decl *Next = VisitStack.pop_back_val();
8084     if (!Next) {
8085       assert(!HistoryStack.empty());
8086       // Found a marker, we have gone up a level
8087       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8088         ValidTypes.insert(Hist->getType().getTypePtr());
8089 
8090       continue;
8091     }
8092 
8093     // Adds everything except the original parameter declaration (which is not a
8094     // field itself) to the history stack.
8095     const RecordDecl *RD;
8096     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8097       HistoryStack.push_back(Field);
8098       RD = Field->getType()->castAs<RecordType>()->getDecl();
8099     } else {
8100       RD = cast<RecordDecl>(Next);
8101     }
8102 
8103     // Add a null marker so we know when we've gone back up a level
8104     VisitStack.push_back(nullptr);
8105 
8106     for (const auto *FD : RD->fields()) {
8107       QualType QT = FD->getType();
8108 
8109       if (ValidTypes.count(QT.getTypePtr()))
8110         continue;
8111 
8112       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8113       if (ParamType == ValidKernelParam)
8114         continue;
8115 
8116       if (ParamType == RecordKernelParam) {
8117         VisitStack.push_back(FD);
8118         continue;
8119       }
8120 
8121       // OpenCL v1.2 s6.9.p:
8122       // Arguments to kernel functions that are declared to be a struct or union
8123       // do not allow OpenCL objects to be passed as elements of the struct or
8124       // union.
8125       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8126           ParamType == InvalidAddrSpacePtrKernelParam) {
8127         S.Diag(Param->getLocation(),
8128                diag::err_record_with_pointers_kernel_param)
8129           << PT->isUnionType()
8130           << PT;
8131       } else {
8132         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8133       }
8134 
8135       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8136         << PD->getDeclName();
8137 
8138       // We have an error, now let's go back up through history and show where
8139       // the offending field came from
8140       for (ArrayRef<const FieldDecl *>::const_iterator
8141                I = HistoryStack.begin() + 1,
8142                E = HistoryStack.end();
8143            I != E; ++I) {
8144         const FieldDecl *OuterField = *I;
8145         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8146           << OuterField->getType();
8147       }
8148 
8149       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8150         << QT->isPointerType()
8151         << QT;
8152       D.setInvalidType();
8153       return;
8154     }
8155   } while (!VisitStack.empty());
8156 }
8157 
8158 /// Find the DeclContext in which a tag is implicitly declared if we see an
8159 /// elaborated type specifier in the specified context, and lookup finds
8160 /// nothing.
8161 static DeclContext *getTagInjectionContext(DeclContext *DC) {
8162   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8163     DC = DC->getParent();
8164   return DC;
8165 }
8166 
8167 /// Find the Scope in which a tag is implicitly declared if we see an
8168 /// elaborated type specifier in the specified context, and lookup finds
8169 /// nothing.
8170 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8171   while (S->isClassScope() ||
8172          (LangOpts.CPlusPlus &&
8173           S->isFunctionPrototypeScope()) ||
8174          ((S->getFlags() & Scope::DeclScope) == 0) ||
8175          (S->getEntity() && S->getEntity()->isTransparentContext()))
8176     S = S->getParent();
8177   return S;
8178 }
8179 
8180 NamedDecl*
8181 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8182                               TypeSourceInfo *TInfo, LookupResult &Previous,
8183                               MultiTemplateParamsArg TemplateParamLists,
8184                               bool &AddToScope) {
8185   QualType R = TInfo->getType();
8186 
8187   assert(R.getTypePtr()->isFunctionType());
8188 
8189   // TODO: consider using NameInfo for diagnostic.
8190   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8191   DeclarationName Name = NameInfo.getName();
8192   StorageClass SC = getFunctionStorageClass(*this, D);
8193 
8194   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8195     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8196          diag::err_invalid_thread)
8197       << DeclSpec::getSpecifierName(TSCS);
8198 
8199   if (D.isFirstDeclarationOfMember())
8200     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8201                            D.getIdentifierLoc());
8202 
8203   bool isFriend = false;
8204   FunctionTemplateDecl *FunctionTemplate = nullptr;
8205   bool isMemberSpecialization = false;
8206   bool isFunctionTemplateSpecialization = false;
8207 
8208   bool isDependentClassScopeExplicitSpecialization = false;
8209   bool HasExplicitTemplateArgs = false;
8210   TemplateArgumentListInfo TemplateArgs;
8211 
8212   bool isVirtualOkay = false;
8213 
8214   DeclContext *OriginalDC = DC;
8215   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8216 
8217   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8218                                               isVirtualOkay);
8219   if (!NewFD) return nullptr;
8220 
8221   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8222     NewFD->setTopLevelDeclInObjCContainer();
8223 
8224   // Set the lexical context. If this is a function-scope declaration, or has a
8225   // C++ scope specifier, or is the object of a friend declaration, the lexical
8226   // context will be different from the semantic context.
8227   NewFD->setLexicalDeclContext(CurContext);
8228 
8229   if (IsLocalExternDecl)
8230     NewFD->setLocalExternDecl();
8231 
8232   if (getLangOpts().CPlusPlus) {
8233     bool isInline = D.getDeclSpec().isInlineSpecified();
8234     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8235     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8236     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8237     bool isConcept = D.getDeclSpec().isConceptSpecified();
8238     isFriend = D.getDeclSpec().isFriendSpecified();
8239     if (isFriend && !isInline && D.isFunctionDefinition()) {
8240       // C++ [class.friend]p5
8241       //   A function can be defined in a friend declaration of a
8242       //   class . . . . Such a function is implicitly inline.
8243       NewFD->setImplicitlyInline();
8244     }
8245 
8246     // If this is a method defined in an __interface, and is not a constructor
8247     // or an overloaded operator, then set the pure flag (isVirtual will already
8248     // return true).
8249     if (const CXXRecordDecl *Parent =
8250           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8251       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8252         NewFD->setPure(true);
8253 
8254       // C++ [class.union]p2
8255       //   A union can have member functions, but not virtual functions.
8256       if (isVirtual && Parent->isUnion())
8257         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8258     }
8259 
8260     SetNestedNameSpecifier(NewFD, D);
8261     isMemberSpecialization = false;
8262     isFunctionTemplateSpecialization = false;
8263     if (D.isInvalidType())
8264       NewFD->setInvalidDecl();
8265 
8266     // Match up the template parameter lists with the scope specifier, then
8267     // determine whether we have a template or a template specialization.
8268     bool Invalid = false;
8269     if (TemplateParameterList *TemplateParams =
8270             MatchTemplateParametersToScopeSpecifier(
8271                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8272                 D.getCXXScopeSpec(),
8273                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
8274                     ? D.getName().TemplateId
8275                     : nullptr,
8276                 TemplateParamLists, isFriend, isMemberSpecialization,
8277                 Invalid)) {
8278       if (TemplateParams->size() > 0) {
8279         // This is a function template
8280 
8281         // Check that we can declare a template here.
8282         if (CheckTemplateDeclScope(S, TemplateParams))
8283           NewFD->setInvalidDecl();
8284 
8285         // A destructor cannot be a template.
8286         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8287           Diag(NewFD->getLocation(), diag::err_destructor_template);
8288           NewFD->setInvalidDecl();
8289         }
8290 
8291         // If we're adding a template to a dependent context, we may need to
8292         // rebuilding some of the types used within the template parameter list,
8293         // now that we know what the current instantiation is.
8294         if (DC->isDependentContext()) {
8295           ContextRAII SavedContext(*this, DC);
8296           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8297             Invalid = true;
8298         }
8299 
8300         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8301                                                         NewFD->getLocation(),
8302                                                         Name, TemplateParams,
8303                                                         NewFD);
8304         FunctionTemplate->setLexicalDeclContext(CurContext);
8305         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8306 
8307         // For source fidelity, store the other template param lists.
8308         if (TemplateParamLists.size() > 1) {
8309           NewFD->setTemplateParameterListsInfo(Context,
8310                                                TemplateParamLists.drop_back(1));
8311         }
8312       } else {
8313         // This is a function template specialization.
8314         isFunctionTemplateSpecialization = true;
8315         // For source fidelity, store all the template param lists.
8316         if (TemplateParamLists.size() > 0)
8317           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8318 
8319         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8320         if (isFriend) {
8321           // We want to remove the "template<>", found here.
8322           SourceRange RemoveRange = TemplateParams->getSourceRange();
8323 
8324           // If we remove the template<> and the name is not a
8325           // template-id, we're actually silently creating a problem:
8326           // the friend declaration will refer to an untemplated decl,
8327           // and clearly the user wants a template specialization.  So
8328           // we need to insert '<>' after the name.
8329           SourceLocation InsertLoc;
8330           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8331             InsertLoc = D.getName().getSourceRange().getEnd();
8332             InsertLoc = getLocForEndOfToken(InsertLoc);
8333           }
8334 
8335           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8336             << Name << RemoveRange
8337             << FixItHint::CreateRemoval(RemoveRange)
8338             << FixItHint::CreateInsertion(InsertLoc, "<>");
8339         }
8340       }
8341     }
8342     else {
8343       // All template param lists were matched against the scope specifier:
8344       // this is NOT (an explicit specialization of) a template.
8345       if (TemplateParamLists.size() > 0)
8346         // For source fidelity, store all the template param lists.
8347         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8348     }
8349 
8350     if (Invalid) {
8351       NewFD->setInvalidDecl();
8352       if (FunctionTemplate)
8353         FunctionTemplate->setInvalidDecl();
8354     }
8355 
8356     // C++ [dcl.fct.spec]p5:
8357     //   The virtual specifier shall only be used in declarations of
8358     //   nonstatic class member functions that appear within a
8359     //   member-specification of a class declaration; see 10.3.
8360     //
8361     if (isVirtual && !NewFD->isInvalidDecl()) {
8362       if (!isVirtualOkay) {
8363         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8364              diag::err_virtual_non_function);
8365       } else if (!CurContext->isRecord()) {
8366         // 'virtual' was specified outside of the class.
8367         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8368              diag::err_virtual_out_of_class)
8369           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8370       } else if (NewFD->getDescribedFunctionTemplate()) {
8371         // C++ [temp.mem]p3:
8372         //  A member function template shall not be virtual.
8373         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8374              diag::err_virtual_member_function_template)
8375           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8376       } else {
8377         // Okay: Add virtual to the method.
8378         NewFD->setVirtualAsWritten(true);
8379       }
8380 
8381       if (getLangOpts().CPlusPlus14 &&
8382           NewFD->getReturnType()->isUndeducedType())
8383         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8384     }
8385 
8386     if (getLangOpts().CPlusPlus14 &&
8387         (NewFD->isDependentContext() ||
8388          (isFriend && CurContext->isDependentContext())) &&
8389         NewFD->getReturnType()->isUndeducedType()) {
8390       // If the function template is referenced directly (for instance, as a
8391       // member of the current instantiation), pretend it has a dependent type.
8392       // This is not really justified by the standard, but is the only sane
8393       // thing to do.
8394       // FIXME: For a friend function, we have not marked the function as being
8395       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8396       const FunctionProtoType *FPT =
8397           NewFD->getType()->castAs<FunctionProtoType>();
8398       QualType Result =
8399           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8400       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8401                                              FPT->getExtProtoInfo()));
8402     }
8403 
8404     // C++ [dcl.fct.spec]p3:
8405     //  The inline specifier shall not appear on a block scope function
8406     //  declaration.
8407     if (isInline && !NewFD->isInvalidDecl()) {
8408       if (CurContext->isFunctionOrMethod()) {
8409         // 'inline' is not allowed on block scope function declaration.
8410         Diag(D.getDeclSpec().getInlineSpecLoc(),
8411              diag::err_inline_declaration_block_scope) << Name
8412           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8413       }
8414     }
8415 
8416     // C++ [dcl.fct.spec]p6:
8417     //  The explicit specifier shall be used only in the declaration of a
8418     //  constructor or conversion function within its class definition;
8419     //  see 12.3.1 and 12.3.2.
8420     if (isExplicit && !NewFD->isInvalidDecl() &&
8421         !isa<CXXDeductionGuideDecl>(NewFD)) {
8422       if (!CurContext->isRecord()) {
8423         // 'explicit' was specified outside of the class.
8424         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8425              diag::err_explicit_out_of_class)
8426           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8427       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8428                  !isa<CXXConversionDecl>(NewFD)) {
8429         // 'explicit' was specified on a function that wasn't a constructor
8430         // or conversion function.
8431         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8432              diag::err_explicit_non_ctor_or_conv_function)
8433           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8434       }
8435     }
8436 
8437     if (isConstexpr) {
8438       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8439       // are implicitly inline.
8440       NewFD->setImplicitlyInline();
8441 
8442       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8443       // be either constructors or to return a literal type. Therefore,
8444       // destructors cannot be declared constexpr.
8445       if (isa<CXXDestructorDecl>(NewFD))
8446         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8447     }
8448 
8449     if (isConcept) {
8450       // This is a function concept.
8451       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8452         FTD->setConcept();
8453 
8454       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8455       // applied only to the definition of a function template [...]
8456       if (!D.isFunctionDefinition()) {
8457         Diag(D.getDeclSpec().getConceptSpecLoc(),
8458              diag::err_function_concept_not_defined);
8459         NewFD->setInvalidDecl();
8460       }
8461 
8462       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8463       // have no exception-specification and is treated as if it were specified
8464       // with noexcept(true) (15.4). [...]
8465       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8466         if (FPT->hasExceptionSpec()) {
8467           SourceRange Range;
8468           if (D.isFunctionDeclarator())
8469             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8470           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8471               << FixItHint::CreateRemoval(Range);
8472           NewFD->setInvalidDecl();
8473         } else {
8474           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8475         }
8476 
8477         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8478         // following restrictions:
8479         // - The declared return type shall have the type bool.
8480         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8481           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8482           NewFD->setInvalidDecl();
8483         }
8484 
8485         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8486         // following restrictions:
8487         // - The declaration's parameter list shall be equivalent to an empty
8488         //   parameter list.
8489         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8490           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8491       }
8492 
8493       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8494       // implicity defined to be a constexpr declaration (implicitly inline)
8495       NewFD->setImplicitlyInline();
8496 
8497       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8498       // be declared with the thread_local, inline, friend, or constexpr
8499       // specifiers, [...]
8500       if (isInline) {
8501         Diag(D.getDeclSpec().getInlineSpecLoc(),
8502              diag::err_concept_decl_invalid_specifiers)
8503             << 1 << 1;
8504         NewFD->setInvalidDecl(true);
8505       }
8506 
8507       if (isFriend) {
8508         Diag(D.getDeclSpec().getFriendSpecLoc(),
8509              diag::err_concept_decl_invalid_specifiers)
8510             << 1 << 2;
8511         NewFD->setInvalidDecl(true);
8512       }
8513 
8514       if (isConstexpr) {
8515         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8516              diag::err_concept_decl_invalid_specifiers)
8517             << 1 << 3;
8518         NewFD->setInvalidDecl(true);
8519       }
8520 
8521       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8522       // applied only to the definition of a function template or variable
8523       // template, declared in namespace scope.
8524       if (isFunctionTemplateSpecialization) {
8525         Diag(D.getDeclSpec().getConceptSpecLoc(),
8526              diag::err_concept_specified_specialization) << 1;
8527         NewFD->setInvalidDecl(true);
8528         return NewFD;
8529       }
8530     }
8531 
8532     // If __module_private__ was specified, mark the function accordingly.
8533     if (D.getDeclSpec().isModulePrivateSpecified()) {
8534       if (isFunctionTemplateSpecialization) {
8535         SourceLocation ModulePrivateLoc
8536           = D.getDeclSpec().getModulePrivateSpecLoc();
8537         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8538           << 0
8539           << FixItHint::CreateRemoval(ModulePrivateLoc);
8540       } else {
8541         NewFD->setModulePrivate();
8542         if (FunctionTemplate)
8543           FunctionTemplate->setModulePrivate();
8544       }
8545     }
8546 
8547     if (isFriend) {
8548       if (FunctionTemplate) {
8549         FunctionTemplate->setObjectOfFriendDecl();
8550         FunctionTemplate->setAccess(AS_public);
8551       }
8552       NewFD->setObjectOfFriendDecl();
8553       NewFD->setAccess(AS_public);
8554     }
8555 
8556     // If a function is defined as defaulted or deleted, mark it as such now.
8557     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8558     // definition kind to FDK_Definition.
8559     switch (D.getFunctionDefinitionKind()) {
8560       case FDK_Declaration:
8561       case FDK_Definition:
8562         break;
8563 
8564       case FDK_Defaulted:
8565         NewFD->setDefaulted();
8566         break;
8567 
8568       case FDK_Deleted:
8569         NewFD->setDeletedAsWritten();
8570         break;
8571     }
8572 
8573     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8574         D.isFunctionDefinition()) {
8575       // C++ [class.mfct]p2:
8576       //   A member function may be defined (8.4) in its class definition, in
8577       //   which case it is an inline member function (7.1.2)
8578       NewFD->setImplicitlyInline();
8579     }
8580 
8581     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8582         !CurContext->isRecord()) {
8583       // C++ [class.static]p1:
8584       //   A data or function member of a class may be declared static
8585       //   in a class definition, in which case it is a static member of
8586       //   the class.
8587 
8588       // Complain about the 'static' specifier if it's on an out-of-line
8589       // member function definition.
8590       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8591            diag::err_static_out_of_line)
8592         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8593     }
8594 
8595     // C++11 [except.spec]p15:
8596     //   A deallocation function with no exception-specification is treated
8597     //   as if it were specified with noexcept(true).
8598     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8599     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8600          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8601         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8602       NewFD->setType(Context.getFunctionType(
8603           FPT->getReturnType(), FPT->getParamTypes(),
8604           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8605   }
8606 
8607   // Filter out previous declarations that don't match the scope.
8608   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8609                        D.getCXXScopeSpec().isNotEmpty() ||
8610                        isMemberSpecialization ||
8611                        isFunctionTemplateSpecialization);
8612 
8613   // Handle GNU asm-label extension (encoded as an attribute).
8614   if (Expr *E = (Expr*) D.getAsmLabel()) {
8615     // The parser guarantees this is a string.
8616     StringLiteral *SE = cast<StringLiteral>(E);
8617     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8618                                                 SE->getString(), 0));
8619   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8620     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8621       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8622     if (I != ExtnameUndeclaredIdentifiers.end()) {
8623       if (isDeclExternC(NewFD)) {
8624         NewFD->addAttr(I->second);
8625         ExtnameUndeclaredIdentifiers.erase(I);
8626       } else
8627         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8628             << /*Variable*/0 << NewFD;
8629     }
8630   }
8631 
8632   // Copy the parameter declarations from the declarator D to the function
8633   // declaration NewFD, if they are available.  First scavenge them into Params.
8634   SmallVector<ParmVarDecl*, 16> Params;
8635   unsigned FTIIdx;
8636   if (D.isFunctionDeclarator(FTIIdx)) {
8637     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8638 
8639     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8640     // function that takes no arguments, not a function that takes a
8641     // single void argument.
8642     // We let through "const void" here because Sema::GetTypeForDeclarator
8643     // already checks for that case.
8644     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8645       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8646         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8647         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8648         Param->setDeclContext(NewFD);
8649         Params.push_back(Param);
8650 
8651         if (Param->isInvalidDecl())
8652           NewFD->setInvalidDecl();
8653       }
8654     }
8655 
8656     if (!getLangOpts().CPlusPlus) {
8657       // In C, find all the tag declarations from the prototype and move them
8658       // into the function DeclContext. Remove them from the surrounding tag
8659       // injection context of the function, which is typically but not always
8660       // the TU.
8661       DeclContext *PrototypeTagContext =
8662           getTagInjectionContext(NewFD->getLexicalDeclContext());
8663       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8664         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8665 
8666         // We don't want to reparent enumerators. Look at their parent enum
8667         // instead.
8668         if (!TD) {
8669           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8670             TD = cast<EnumDecl>(ECD->getDeclContext());
8671         }
8672         if (!TD)
8673           continue;
8674         DeclContext *TagDC = TD->getLexicalDeclContext();
8675         if (!TagDC->containsDecl(TD))
8676           continue;
8677         TagDC->removeDecl(TD);
8678         TD->setDeclContext(NewFD);
8679         NewFD->addDecl(TD);
8680 
8681         // Preserve the lexical DeclContext if it is not the surrounding tag
8682         // injection context of the FD. In this example, the semantic context of
8683         // E will be f and the lexical context will be S, while both the
8684         // semantic and lexical contexts of S will be f:
8685         //   void f(struct S { enum E { a } f; } s);
8686         if (TagDC != PrototypeTagContext)
8687           TD->setLexicalDeclContext(TagDC);
8688       }
8689     }
8690   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8691     // When we're declaring a function with a typedef, typeof, etc as in the
8692     // following example, we'll need to synthesize (unnamed)
8693     // parameters for use in the declaration.
8694     //
8695     // @code
8696     // typedef void fn(int);
8697     // fn f;
8698     // @endcode
8699 
8700     // Synthesize a parameter for each argument type.
8701     for (const auto &AI : FT->param_types()) {
8702       ParmVarDecl *Param =
8703           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8704       Param->setScopeInfo(0, Params.size());
8705       Params.push_back(Param);
8706     }
8707   } else {
8708     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8709            "Should not need args for typedef of non-prototype fn");
8710   }
8711 
8712   // Finally, we know we have the right number of parameters, install them.
8713   NewFD->setParams(Params);
8714 
8715   if (D.getDeclSpec().isNoreturnSpecified())
8716     NewFD->addAttr(
8717         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8718                                        Context, 0));
8719 
8720   // Functions returning a variably modified type violate C99 6.7.5.2p2
8721   // because all functions have linkage.
8722   if (!NewFD->isInvalidDecl() &&
8723       NewFD->getReturnType()->isVariablyModifiedType()) {
8724     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8725     NewFD->setInvalidDecl();
8726   }
8727 
8728   // Apply an implicit SectionAttr if '#pragma clang section text' is active
8729   if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8730       !NewFD->hasAttr<SectionAttr>()) {
8731     NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8732                                                  PragmaClangTextSection.SectionName,
8733                                                  PragmaClangTextSection.PragmaLocation));
8734   }
8735 
8736   // Apply an implicit SectionAttr if #pragma code_seg is active.
8737   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8738       !NewFD->hasAttr<SectionAttr>()) {
8739     NewFD->addAttr(
8740         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8741                                     CodeSegStack.CurrentValue->getString(),
8742                                     CodeSegStack.CurrentPragmaLocation));
8743     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8744                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8745                          ASTContext::PSF_Read,
8746                      NewFD))
8747       NewFD->dropAttr<SectionAttr>();
8748   }
8749 
8750   // Handle attributes.
8751   ProcessDeclAttributes(S, NewFD, D);
8752 
8753   if (getLangOpts().OpenCL) {
8754     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8755     // type declaration will generate a compilation error.
8756     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8757     if (AddressSpace == LangAS::opencl_local ||
8758         AddressSpace == LangAS::opencl_global ||
8759         AddressSpace == LangAS::opencl_constant) {
8760       Diag(NewFD->getLocation(),
8761            diag::err_opencl_return_value_with_address_space);
8762       NewFD->setInvalidDecl();
8763     }
8764   }
8765 
8766   if (!getLangOpts().CPlusPlus) {
8767     // Perform semantic checking on the function declaration.
8768     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8769       CheckMain(NewFD, D.getDeclSpec());
8770 
8771     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8772       CheckMSVCRTEntryPoint(NewFD);
8773 
8774     if (!NewFD->isInvalidDecl())
8775       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8776                                                   isMemberSpecialization));
8777     else if (!Previous.empty())
8778       // Recover gracefully from an invalid redeclaration.
8779       D.setRedeclaration(true);
8780     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8781             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8782            "previous declaration set still overloaded");
8783 
8784     // Diagnose no-prototype function declarations with calling conventions that
8785     // don't support variadic calls. Only do this in C and do it after merging
8786     // possibly prototyped redeclarations.
8787     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8788     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8789       CallingConv CC = FT->getExtInfo().getCC();
8790       if (!supportsVariadicCall(CC)) {
8791         // Windows system headers sometimes accidentally use stdcall without
8792         // (void) parameters, so we relax this to a warning.
8793         int DiagID =
8794             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8795         Diag(NewFD->getLocation(), DiagID)
8796             << FunctionType::getNameForCallConv(CC);
8797       }
8798     }
8799   } else {
8800     // C++11 [replacement.functions]p3:
8801     //  The program's definitions shall not be specified as inline.
8802     //
8803     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8804     //
8805     // Suppress the diagnostic if the function is __attribute__((used)), since
8806     // that forces an external definition to be emitted.
8807     if (D.getDeclSpec().isInlineSpecified() &&
8808         NewFD->isReplaceableGlobalAllocationFunction() &&
8809         !NewFD->hasAttr<UsedAttr>())
8810       Diag(D.getDeclSpec().getInlineSpecLoc(),
8811            diag::ext_operator_new_delete_declared_inline)
8812         << NewFD->getDeclName();
8813 
8814     // If the declarator is a template-id, translate the parser's template
8815     // argument list into our AST format.
8816     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8817       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8818       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8819       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8820       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8821                                          TemplateId->NumArgs);
8822       translateTemplateArguments(TemplateArgsPtr,
8823                                  TemplateArgs);
8824 
8825       HasExplicitTemplateArgs = true;
8826 
8827       if (NewFD->isInvalidDecl()) {
8828         HasExplicitTemplateArgs = false;
8829       } else if (FunctionTemplate) {
8830         // Function template with explicit template arguments.
8831         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8832           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8833 
8834         HasExplicitTemplateArgs = false;
8835       } else {
8836         assert((isFunctionTemplateSpecialization ||
8837                 D.getDeclSpec().isFriendSpecified()) &&
8838                "should have a 'template<>' for this decl");
8839         // "friend void foo<>(int);" is an implicit specialization decl.
8840         isFunctionTemplateSpecialization = true;
8841       }
8842     } else if (isFriend && isFunctionTemplateSpecialization) {
8843       // This combination is only possible in a recovery case;  the user
8844       // wrote something like:
8845       //   template <> friend void foo(int);
8846       // which we're recovering from as if the user had written:
8847       //   friend void foo<>(int);
8848       // Go ahead and fake up a template id.
8849       HasExplicitTemplateArgs = true;
8850       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8851       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8852     }
8853 
8854     // We do not add HD attributes to specializations here because
8855     // they may have different constexpr-ness compared to their
8856     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8857     // may end up with different effective targets. Instead, a
8858     // specialization inherits its target attributes from its template
8859     // in the CheckFunctionTemplateSpecialization() call below.
8860     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8861       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8862 
8863     // If it's a friend (and only if it's a friend), it's possible
8864     // that either the specialized function type or the specialized
8865     // template is dependent, and therefore matching will fail.  In
8866     // this case, don't check the specialization yet.
8867     bool InstantiationDependent = false;
8868     if (isFunctionTemplateSpecialization && isFriend &&
8869         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8870          TemplateSpecializationType::anyDependentTemplateArguments(
8871             TemplateArgs,
8872             InstantiationDependent))) {
8873       assert(HasExplicitTemplateArgs &&
8874              "friend function specialization without template args");
8875       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8876                                                        Previous))
8877         NewFD->setInvalidDecl();
8878     } else if (isFunctionTemplateSpecialization) {
8879       if (CurContext->isDependentContext() && CurContext->isRecord()
8880           && !isFriend) {
8881         isDependentClassScopeExplicitSpecialization = true;
8882         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8883           diag::ext_function_specialization_in_class :
8884           diag::err_function_specialization_in_class)
8885           << NewFD->getDeclName();
8886       } else if (CheckFunctionTemplateSpecialization(NewFD,
8887                                   (HasExplicitTemplateArgs ? &TemplateArgs
8888                                                            : nullptr),
8889                                                      Previous))
8890         NewFD->setInvalidDecl();
8891 
8892       // C++ [dcl.stc]p1:
8893       //   A storage-class-specifier shall not be specified in an explicit
8894       //   specialization (14.7.3)
8895       FunctionTemplateSpecializationInfo *Info =
8896           NewFD->getTemplateSpecializationInfo();
8897       if (Info && SC != SC_None) {
8898         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8899           Diag(NewFD->getLocation(),
8900                diag::err_explicit_specialization_inconsistent_storage_class)
8901             << SC
8902             << FixItHint::CreateRemoval(
8903                                       D.getDeclSpec().getStorageClassSpecLoc());
8904 
8905         else
8906           Diag(NewFD->getLocation(),
8907                diag::ext_explicit_specialization_storage_class)
8908             << FixItHint::CreateRemoval(
8909                                       D.getDeclSpec().getStorageClassSpecLoc());
8910       }
8911     } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8912       if (CheckMemberSpecialization(NewFD, Previous))
8913           NewFD->setInvalidDecl();
8914     }
8915 
8916     // Perform semantic checking on the function declaration.
8917     if (!isDependentClassScopeExplicitSpecialization) {
8918       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8919         CheckMain(NewFD, D.getDeclSpec());
8920 
8921       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8922         CheckMSVCRTEntryPoint(NewFD);
8923 
8924       if (!NewFD->isInvalidDecl())
8925         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8926                                                     isMemberSpecialization));
8927       else if (!Previous.empty())
8928         // Recover gracefully from an invalid redeclaration.
8929         D.setRedeclaration(true);
8930     }
8931 
8932     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8933             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8934            "previous declaration set still overloaded");
8935 
8936     NamedDecl *PrincipalDecl = (FunctionTemplate
8937                                 ? cast<NamedDecl>(FunctionTemplate)
8938                                 : NewFD);
8939 
8940     if (isFriend && NewFD->getPreviousDecl()) {
8941       AccessSpecifier Access = AS_public;
8942       if (!NewFD->isInvalidDecl())
8943         Access = NewFD->getPreviousDecl()->getAccess();
8944 
8945       NewFD->setAccess(Access);
8946       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8947     }
8948 
8949     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8950         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8951       PrincipalDecl->setNonMemberOperator();
8952 
8953     // If we have a function template, check the template parameter
8954     // list. This will check and merge default template arguments.
8955     if (FunctionTemplate) {
8956       FunctionTemplateDecl *PrevTemplate =
8957                                      FunctionTemplate->getPreviousDecl();
8958       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8959                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8960                                     : nullptr,
8961                             D.getDeclSpec().isFriendSpecified()
8962                               ? (D.isFunctionDefinition()
8963                                    ? TPC_FriendFunctionTemplateDefinition
8964                                    : TPC_FriendFunctionTemplate)
8965                               : (D.getCXXScopeSpec().isSet() &&
8966                                  DC && DC->isRecord() &&
8967                                  DC->isDependentContext())
8968                                   ? TPC_ClassTemplateMember
8969                                   : TPC_FunctionTemplate);
8970     }
8971 
8972     if (NewFD->isInvalidDecl()) {
8973       // Ignore all the rest of this.
8974     } else if (!D.isRedeclaration()) {
8975       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8976                                        AddToScope };
8977       // Fake up an access specifier if it's supposed to be a class member.
8978       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8979         NewFD->setAccess(AS_public);
8980 
8981       // Qualified decls generally require a previous declaration.
8982       if (D.getCXXScopeSpec().isSet()) {
8983         // ...with the major exception of templated-scope or
8984         // dependent-scope friend declarations.
8985 
8986         // TODO: we currently also suppress this check in dependent
8987         // contexts because (1) the parameter depth will be off when
8988         // matching friend templates and (2) we might actually be
8989         // selecting a friend based on a dependent factor.  But there
8990         // are situations where these conditions don't apply and we
8991         // can actually do this check immediately.
8992         if (isFriend &&
8993             (TemplateParamLists.size() ||
8994              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8995              CurContext->isDependentContext())) {
8996           // ignore these
8997         } else {
8998           // The user tried to provide an out-of-line definition for a
8999           // function that is a member of a class or namespace, but there
9000           // was no such member function declared (C++ [class.mfct]p2,
9001           // C++ [namespace.memdef]p2). For example:
9002           //
9003           // class X {
9004           //   void f() const;
9005           // };
9006           //
9007           // void X::f() { } // ill-formed
9008           //
9009           // Complain about this problem, and attempt to suggest close
9010           // matches (e.g., those that differ only in cv-qualifiers and
9011           // whether the parameter types are references).
9012 
9013           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9014                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9015             AddToScope = ExtraArgs.AddToScope;
9016             return Result;
9017           }
9018         }
9019 
9020         // Unqualified local friend declarations are required to resolve
9021         // to something.
9022       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9023         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9024                 *this, Previous, NewFD, ExtraArgs, true, S)) {
9025           AddToScope = ExtraArgs.AddToScope;
9026           return Result;
9027         }
9028       }
9029     } else if (!D.isFunctionDefinition() &&
9030                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9031                !isFriend && !isFunctionTemplateSpecialization &&
9032                !isMemberSpecialization) {
9033       // An out-of-line member function declaration must also be a
9034       // definition (C++ [class.mfct]p2).
9035       // Note that this is not the case for explicit specializations of
9036       // function templates or member functions of class templates, per
9037       // C++ [temp.expl.spec]p2. We also allow these declarations as an
9038       // extension for compatibility with old SWIG code which likes to
9039       // generate them.
9040       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9041         << D.getCXXScopeSpec().getRange();
9042     }
9043   }
9044 
9045   ProcessPragmaWeak(S, NewFD);
9046   checkAttributesAfterMerging(*this, *NewFD);
9047 
9048   AddKnownFunctionAttributes(NewFD);
9049 
9050   if (NewFD->hasAttr<OverloadableAttr>() &&
9051       !NewFD->getType()->getAs<FunctionProtoType>()) {
9052     Diag(NewFD->getLocation(),
9053          diag::err_attribute_overloadable_no_prototype)
9054       << NewFD;
9055 
9056     // Turn this into a variadic function with no parameters.
9057     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9058     FunctionProtoType::ExtProtoInfo EPI(
9059         Context.getDefaultCallingConvention(true, false));
9060     EPI.Variadic = true;
9061     EPI.ExtInfo = FT->getExtInfo();
9062 
9063     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9064     NewFD->setType(R);
9065   }
9066 
9067   // If there's a #pragma GCC visibility in scope, and this isn't a class
9068   // member, set the visibility of this function.
9069   if (!DC->isRecord() && NewFD->isExternallyVisible())
9070     AddPushedVisibilityAttribute(NewFD);
9071 
9072   // If there's a #pragma clang arc_cf_code_audited in scope, consider
9073   // marking the function.
9074   AddCFAuditedAttribute(NewFD);
9075 
9076   // If this is a function definition, check if we have to apply optnone due to
9077   // a pragma.
9078   if(D.isFunctionDefinition())
9079     AddRangeBasedOptnone(NewFD);
9080 
9081   // If this is the first declaration of an extern C variable, update
9082   // the map of such variables.
9083   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9084       isIncompleteDeclExternC(*this, NewFD))
9085     RegisterLocallyScopedExternCDecl(NewFD, S);
9086 
9087   // Set this FunctionDecl's range up to the right paren.
9088   NewFD->setRangeEnd(D.getSourceRange().getEnd());
9089 
9090   if (D.isRedeclaration() && !Previous.empty()) {
9091     checkDLLAttributeRedeclaration(
9092         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
9093         isMemberSpecialization || isFunctionTemplateSpecialization,
9094         D.isFunctionDefinition());
9095   }
9096 
9097   if (getLangOpts().CUDA) {
9098     IdentifierInfo *II = NewFD->getIdentifier();
9099     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9100         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9101       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9102         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9103 
9104       Context.setcudaConfigureCallDecl(NewFD);
9105     }
9106 
9107     // Variadic functions, other than a *declaration* of printf, are not allowed
9108     // in device-side CUDA code, unless someone passed
9109     // -fcuda-allow-variadic-functions.
9110     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9111         (NewFD->hasAttr<CUDADeviceAttr>() ||
9112          NewFD->hasAttr<CUDAGlobalAttr>()) &&
9113         !(II && II->isStr("printf") && NewFD->isExternC() &&
9114           !D.isFunctionDefinition())) {
9115       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9116     }
9117   }
9118 
9119   MarkUnusedFileScopedDecl(NewFD);
9120 
9121   if (getLangOpts().CPlusPlus) {
9122     if (FunctionTemplate) {
9123       if (NewFD->isInvalidDecl())
9124         FunctionTemplate->setInvalidDecl();
9125       return FunctionTemplate;
9126     }
9127 
9128     if (isMemberSpecialization && !NewFD->isInvalidDecl())
9129       CompleteMemberSpecialization(NewFD, Previous);
9130   }
9131 
9132   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9133     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9134     if ((getLangOpts().OpenCLVersion >= 120)
9135         && (SC == SC_Static)) {
9136       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9137       D.setInvalidType();
9138     }
9139 
9140     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9141     if (!NewFD->getReturnType()->isVoidType()) {
9142       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9143       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9144           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9145                                 : FixItHint());
9146       D.setInvalidType();
9147     }
9148 
9149     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9150     for (auto Param : NewFD->parameters())
9151       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9152   }
9153   for (const ParmVarDecl *Param : NewFD->parameters()) {
9154     QualType PT = Param->getType();
9155 
9156     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9157     // types.
9158     if (getLangOpts().OpenCLVersion >= 200) {
9159       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9160         QualType ElemTy = PipeTy->getElementType();
9161           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9162             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9163             D.setInvalidType();
9164           }
9165       }
9166     }
9167   }
9168 
9169   // Here we have an function template explicit specialization at class scope.
9170   // The actually specialization will be postponed to template instatiation
9171   // time via the ClassScopeFunctionSpecializationDecl node.
9172   if (isDependentClassScopeExplicitSpecialization) {
9173     ClassScopeFunctionSpecializationDecl *NewSpec =
9174                          ClassScopeFunctionSpecializationDecl::Create(
9175                                 Context, CurContext, SourceLocation(),
9176                                 cast<CXXMethodDecl>(NewFD),
9177                                 HasExplicitTemplateArgs, TemplateArgs);
9178     CurContext->addDecl(NewSpec);
9179     AddToScope = false;
9180   }
9181 
9182   return NewFD;
9183 }
9184 
9185 /// \brief Checks if the new declaration declared in dependent context must be
9186 /// put in the same redeclaration chain as the specified declaration.
9187 ///
9188 /// \param D Declaration that is checked.
9189 /// \param PrevDecl Previous declaration found with proper lookup method for the
9190 ///                 same declaration name.
9191 /// \returns True if D must be added to the redeclaration chain which PrevDecl
9192 ///          belongs to.
9193 ///
9194 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9195   // Any declarations should be put into redeclaration chains except for
9196   // friend declaration in a dependent context that names a function in
9197   // namespace scope.
9198   //
9199   // This allows to compile code like:
9200   //
9201   //       void func();
9202   //       template<typename T> class C1 { friend void func() { } };
9203   //       template<typename T> class C2 { friend void func() { } };
9204   //
9205   // This code snippet is a valid code unless both templates are instantiated.
9206   return !(D->getLexicalDeclContext()->isDependentContext() &&
9207            D->getDeclContext()->isFileContext() &&
9208            D->getFriendObjectKind() != Decl::FOK_None);
9209 }
9210 
9211 /// \brief Perform semantic checking of a new function declaration.
9212 ///
9213 /// Performs semantic analysis of the new function declaration
9214 /// NewFD. This routine performs all semantic checking that does not
9215 /// require the actual declarator involved in the declaration, and is
9216 /// used both for the declaration of functions as they are parsed
9217 /// (called via ActOnDeclarator) and for the declaration of functions
9218 /// that have been instantiated via C++ template instantiation (called
9219 /// via InstantiateDecl).
9220 ///
9221 /// \param IsMemberSpecialization whether this new function declaration is
9222 /// a member specialization (that replaces any definition provided by the
9223 /// previous declaration).
9224 ///
9225 /// This sets NewFD->isInvalidDecl() to true if there was an error.
9226 ///
9227 /// \returns true if the function declaration is a redeclaration.
9228 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9229                                     LookupResult &Previous,
9230                                     bool IsMemberSpecialization) {
9231   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9232          "Variably modified return types are not handled here");
9233 
9234   // Determine whether the type of this function should be merged with
9235   // a previous visible declaration. This never happens for functions in C++,
9236   // and always happens in C if the previous declaration was visible.
9237   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9238                                !Previous.isShadowed();
9239 
9240   bool Redeclaration = false;
9241   NamedDecl *OldDecl = nullptr;
9242   bool MayNeedOverloadableChecks = false;
9243 
9244   // Merge or overload the declaration with an existing declaration of
9245   // the same name, if appropriate.
9246   if (!Previous.empty()) {
9247     // Determine whether NewFD is an overload of PrevDecl or
9248     // a declaration that requires merging. If it's an overload,
9249     // there's no more work to do here; we'll just add the new
9250     // function to the scope.
9251     if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9252       NamedDecl *Candidate = Previous.getRepresentativeDecl();
9253       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9254         Redeclaration = true;
9255         OldDecl = Candidate;
9256       }
9257     } else {
9258       MayNeedOverloadableChecks = true;
9259       switch (CheckOverload(S, NewFD, Previous, OldDecl,
9260                             /*NewIsUsingDecl*/ false)) {
9261       case Ovl_Match:
9262         Redeclaration = true;
9263         break;
9264 
9265       case Ovl_NonFunction:
9266         Redeclaration = true;
9267         break;
9268 
9269       case Ovl_Overload:
9270         Redeclaration = false;
9271         break;
9272       }
9273     }
9274   }
9275 
9276   // Check for a previous extern "C" declaration with this name.
9277   if (!Redeclaration &&
9278       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9279     if (!Previous.empty()) {
9280       // This is an extern "C" declaration with the same name as a previous
9281       // declaration, and thus redeclares that entity...
9282       Redeclaration = true;
9283       OldDecl = Previous.getFoundDecl();
9284       MergeTypeWithPrevious = false;
9285 
9286       // ... except in the presence of __attribute__((overloadable)).
9287       if (OldDecl->hasAttr<OverloadableAttr>() ||
9288           NewFD->hasAttr<OverloadableAttr>()) {
9289         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9290           MayNeedOverloadableChecks = true;
9291           Redeclaration = false;
9292           OldDecl = nullptr;
9293         }
9294       }
9295     }
9296   }
9297 
9298   // C++11 [dcl.constexpr]p8:
9299   //   A constexpr specifier for a non-static member function that is not
9300   //   a constructor declares that member function to be const.
9301   //
9302   // This needs to be delayed until we know whether this is an out-of-line
9303   // definition of a static member function.
9304   //
9305   // This rule is not present in C++1y, so we produce a backwards
9306   // compatibility warning whenever it happens in C++11.
9307   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9308   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9309       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9310       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9311     CXXMethodDecl *OldMD = nullptr;
9312     if (OldDecl)
9313       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9314     if (!OldMD || !OldMD->isStatic()) {
9315       const FunctionProtoType *FPT =
9316         MD->getType()->castAs<FunctionProtoType>();
9317       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9318       EPI.TypeQuals |= Qualifiers::Const;
9319       MD->setType(Context.getFunctionType(FPT->getReturnType(),
9320                                           FPT->getParamTypes(), EPI));
9321 
9322       // Warn that we did this, if we're not performing template instantiation.
9323       // In that case, we'll have warned already when the template was defined.
9324       if (!inTemplateInstantiation()) {
9325         SourceLocation AddConstLoc;
9326         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9327                 .IgnoreParens().getAs<FunctionTypeLoc>())
9328           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9329 
9330         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9331           << FixItHint::CreateInsertion(AddConstLoc, " const");
9332       }
9333     }
9334   }
9335 
9336   if (Redeclaration) {
9337     // NewFD and OldDecl represent declarations that need to be
9338     // merged.
9339     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9340       NewFD->setInvalidDecl();
9341       return Redeclaration;
9342     }
9343 
9344     Previous.clear();
9345     Previous.addDecl(OldDecl);
9346 
9347     if (FunctionTemplateDecl *OldTemplateDecl
9348                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9349       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9350       FunctionTemplateDecl *NewTemplateDecl
9351         = NewFD->getDescribedFunctionTemplate();
9352       assert(NewTemplateDecl && "Template/non-template mismatch");
9353       if (CXXMethodDecl *Method
9354             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9355         Method->setAccess(OldTemplateDecl->getAccess());
9356         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9357       }
9358 
9359       // If this is an explicit specialization of a member that is a function
9360       // template, mark it as a member specialization.
9361       if (IsMemberSpecialization &&
9362           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9363         NewTemplateDecl->setMemberSpecialization();
9364         assert(OldTemplateDecl->isMemberSpecialization());
9365         // Explicit specializations of a member template do not inherit deleted
9366         // status from the parent member template that they are specializing.
9367         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9368           FunctionDecl *const OldTemplatedDecl =
9369               OldTemplateDecl->getTemplatedDecl();
9370           // FIXME: This assert will not hold in the presence of modules.
9371           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9372           // FIXME: We need an update record for this AST mutation.
9373           OldTemplatedDecl->setDeletedAsWritten(false);
9374         }
9375       }
9376 
9377     } else {
9378       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9379         // This needs to happen first so that 'inline' propagates.
9380         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9381         if (isa<CXXMethodDecl>(NewFD))
9382           NewFD->setAccess(OldDecl->getAccess());
9383       }
9384     }
9385   } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9386              !NewFD->getAttr<OverloadableAttr>()) {
9387     assert((Previous.empty() ||
9388             llvm::any_of(Previous,
9389                          [](const NamedDecl *ND) {
9390                            return ND->hasAttr<OverloadableAttr>();
9391                          })) &&
9392            "Non-redecls shouldn't happen without overloadable present");
9393 
9394     auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9395       const auto *FD = dyn_cast<FunctionDecl>(ND);
9396       return FD && !FD->hasAttr<OverloadableAttr>();
9397     });
9398 
9399     if (OtherUnmarkedIter != Previous.end()) {
9400       Diag(NewFD->getLocation(),
9401            diag::err_attribute_overloadable_multiple_unmarked_overloads);
9402       Diag((*OtherUnmarkedIter)->getLocation(),
9403            diag::note_attribute_overloadable_prev_overload)
9404           << false;
9405 
9406       NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9407     }
9408   }
9409 
9410   // Semantic checking for this function declaration (in isolation).
9411 
9412   if (getLangOpts().CPlusPlus) {
9413     // C++-specific checks.
9414     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9415       CheckConstructor(Constructor);
9416     } else if (CXXDestructorDecl *Destructor =
9417                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9418       CXXRecordDecl *Record = Destructor->getParent();
9419       QualType ClassType = Context.getTypeDeclType(Record);
9420 
9421       // FIXME: Shouldn't we be able to perform this check even when the class
9422       // type is dependent? Both gcc and edg can handle that.
9423       if (!ClassType->isDependentType()) {
9424         DeclarationName Name
9425           = Context.DeclarationNames.getCXXDestructorName(
9426                                         Context.getCanonicalType(ClassType));
9427         if (NewFD->getDeclName() != Name) {
9428           Diag(NewFD->getLocation(), diag::err_destructor_name);
9429           NewFD->setInvalidDecl();
9430           return Redeclaration;
9431         }
9432       }
9433     } else if (CXXConversionDecl *Conversion
9434                = dyn_cast<CXXConversionDecl>(NewFD)) {
9435       ActOnConversionDeclarator(Conversion);
9436     } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9437       if (auto *TD = Guide->getDescribedFunctionTemplate())
9438         CheckDeductionGuideTemplate(TD);
9439 
9440       // A deduction guide is not on the list of entities that can be
9441       // explicitly specialized.
9442       if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9443         Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9444             << /*explicit specialization*/ 1;
9445     }
9446 
9447     // Find any virtual functions that this function overrides.
9448     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9449       if (!Method->isFunctionTemplateSpecialization() &&
9450           !Method->getDescribedFunctionTemplate() &&
9451           Method->isCanonicalDecl()) {
9452         if (AddOverriddenMethods(Method->getParent(), Method)) {
9453           // If the function was marked as "static", we have a problem.
9454           if (NewFD->getStorageClass() == SC_Static) {
9455             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9456           }
9457         }
9458       }
9459 
9460       if (Method->isStatic())
9461         checkThisInStaticMemberFunctionType(Method);
9462     }
9463 
9464     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9465     if (NewFD->isOverloadedOperator() &&
9466         CheckOverloadedOperatorDeclaration(NewFD)) {
9467       NewFD->setInvalidDecl();
9468       return Redeclaration;
9469     }
9470 
9471     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9472     if (NewFD->getLiteralIdentifier() &&
9473         CheckLiteralOperatorDeclaration(NewFD)) {
9474       NewFD->setInvalidDecl();
9475       return Redeclaration;
9476     }
9477 
9478     // In C++, check default arguments now that we have merged decls. Unless
9479     // the lexical context is the class, because in this case this is done
9480     // during delayed parsing anyway.
9481     if (!CurContext->isRecord())
9482       CheckCXXDefaultArguments(NewFD);
9483 
9484     // If this function declares a builtin function, check the type of this
9485     // declaration against the expected type for the builtin.
9486     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9487       ASTContext::GetBuiltinTypeError Error;
9488       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9489       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9490       // If the type of the builtin differs only in its exception
9491       // specification, that's OK.
9492       // FIXME: If the types do differ in this way, it would be better to
9493       // retain the 'noexcept' form of the type.
9494       if (!T.isNull() &&
9495           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9496                                                             NewFD->getType()))
9497         // The type of this function differs from the type of the builtin,
9498         // so forget about the builtin entirely.
9499         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9500     }
9501 
9502     // If this function is declared as being extern "C", then check to see if
9503     // the function returns a UDT (class, struct, or union type) that is not C
9504     // compatible, and if it does, warn the user.
9505     // But, issue any diagnostic on the first declaration only.
9506     if (Previous.empty() && NewFD->isExternC()) {
9507       QualType R = NewFD->getReturnType();
9508       if (R->isIncompleteType() && !R->isVoidType())
9509         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9510             << NewFD << R;
9511       else if (!R.isPODType(Context) && !R->isVoidType() &&
9512                !R->isObjCObjectPointerType())
9513         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9514     }
9515 
9516     // C++1z [dcl.fct]p6:
9517     //   [...] whether the function has a non-throwing exception-specification
9518     //   [is] part of the function type
9519     //
9520     // This results in an ABI break between C++14 and C++17 for functions whose
9521     // declared type includes an exception-specification in a parameter or
9522     // return type. (Exception specifications on the function itself are OK in
9523     // most cases, and exception specifications are not permitted in most other
9524     // contexts where they could make it into a mangling.)
9525     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9526       auto HasNoexcept = [&](QualType T) -> bool {
9527         // Strip off declarator chunks that could be between us and a function
9528         // type. We don't need to look far, exception specifications are very
9529         // restricted prior to C++17.
9530         if (auto *RT = T->getAs<ReferenceType>())
9531           T = RT->getPointeeType();
9532         else if (T->isAnyPointerType())
9533           T = T->getPointeeType();
9534         else if (auto *MPT = T->getAs<MemberPointerType>())
9535           T = MPT->getPointeeType();
9536         if (auto *FPT = T->getAs<FunctionProtoType>())
9537           if (FPT->isNothrow(Context))
9538             return true;
9539         return false;
9540       };
9541 
9542       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9543       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9544       for (QualType T : FPT->param_types())
9545         AnyNoexcept |= HasNoexcept(T);
9546       if (AnyNoexcept)
9547         Diag(NewFD->getLocation(),
9548              diag::warn_cxx17_compat_exception_spec_in_signature)
9549             << NewFD;
9550     }
9551 
9552     if (!Redeclaration && LangOpts.CUDA)
9553       checkCUDATargetOverload(NewFD, Previous);
9554   }
9555   return Redeclaration;
9556 }
9557 
9558 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9559   // C++11 [basic.start.main]p3:
9560   //   A program that [...] declares main to be inline, static or
9561   //   constexpr is ill-formed.
9562   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9563   //   appear in a declaration of main.
9564   // static main is not an error under C99, but we should warn about it.
9565   // We accept _Noreturn main as an extension.
9566   if (FD->getStorageClass() == SC_Static)
9567     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9568          ? diag::err_static_main : diag::warn_static_main)
9569       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9570   if (FD->isInlineSpecified())
9571     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9572       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9573   if (DS.isNoreturnSpecified()) {
9574     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9575     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9576     Diag(NoreturnLoc, diag::ext_noreturn_main);
9577     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9578       << FixItHint::CreateRemoval(NoreturnRange);
9579   }
9580   if (FD->isConstexpr()) {
9581     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9582       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9583     FD->setConstexpr(false);
9584   }
9585 
9586   if (getLangOpts().OpenCL) {
9587     Diag(FD->getLocation(), diag::err_opencl_no_main)
9588         << FD->hasAttr<OpenCLKernelAttr>();
9589     FD->setInvalidDecl();
9590     return;
9591   }
9592 
9593   QualType T = FD->getType();
9594   assert(T->isFunctionType() && "function decl is not of function type");
9595   const FunctionType* FT = T->castAs<FunctionType>();
9596 
9597   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9598     // In C with GNU extensions we allow main() to have non-integer return
9599     // type, but we should warn about the extension, and we disable the
9600     // implicit-return-zero rule.
9601 
9602     // GCC in C mode accepts qualified 'int'.
9603     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9604       FD->setHasImplicitReturnZero(true);
9605     else {
9606       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9607       SourceRange RTRange = FD->getReturnTypeSourceRange();
9608       if (RTRange.isValid())
9609         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9610             << FixItHint::CreateReplacement(RTRange, "int");
9611     }
9612   } else {
9613     // In C and C++, main magically returns 0 if you fall off the end;
9614     // set the flag which tells us that.
9615     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9616 
9617     // All the standards say that main() should return 'int'.
9618     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9619       FD->setHasImplicitReturnZero(true);
9620     else {
9621       // Otherwise, this is just a flat-out error.
9622       SourceRange RTRange = FD->getReturnTypeSourceRange();
9623       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9624           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9625                                 : FixItHint());
9626       FD->setInvalidDecl(true);
9627     }
9628   }
9629 
9630   // Treat protoless main() as nullary.
9631   if (isa<FunctionNoProtoType>(FT)) return;
9632 
9633   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9634   unsigned nparams = FTP->getNumParams();
9635   assert(FD->getNumParams() == nparams);
9636 
9637   bool HasExtraParameters = (nparams > 3);
9638 
9639   if (FTP->isVariadic()) {
9640     Diag(FD->getLocation(), diag::ext_variadic_main);
9641     // FIXME: if we had information about the location of the ellipsis, we
9642     // could add a FixIt hint to remove it as a parameter.
9643   }
9644 
9645   // Darwin passes an undocumented fourth argument of type char**.  If
9646   // other platforms start sprouting these, the logic below will start
9647   // getting shifty.
9648   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9649     HasExtraParameters = false;
9650 
9651   if (HasExtraParameters) {
9652     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9653     FD->setInvalidDecl(true);
9654     nparams = 3;
9655   }
9656 
9657   // FIXME: a lot of the following diagnostics would be improved
9658   // if we had some location information about types.
9659 
9660   QualType CharPP =
9661     Context.getPointerType(Context.getPointerType(Context.CharTy));
9662   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9663 
9664   for (unsigned i = 0; i < nparams; ++i) {
9665     QualType AT = FTP->getParamType(i);
9666 
9667     bool mismatch = true;
9668 
9669     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9670       mismatch = false;
9671     else if (Expected[i] == CharPP) {
9672       // As an extension, the following forms are okay:
9673       //   char const **
9674       //   char const * const *
9675       //   char * const *
9676 
9677       QualifierCollector qs;
9678       const PointerType* PT;
9679       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9680           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9681           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9682                               Context.CharTy)) {
9683         qs.removeConst();
9684         mismatch = !qs.empty();
9685       }
9686     }
9687 
9688     if (mismatch) {
9689       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9690       // TODO: suggest replacing given type with expected type
9691       FD->setInvalidDecl(true);
9692     }
9693   }
9694 
9695   if (nparams == 1 && !FD->isInvalidDecl()) {
9696     Diag(FD->getLocation(), diag::warn_main_one_arg);
9697   }
9698 
9699   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9700     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9701     FD->setInvalidDecl();
9702   }
9703 }
9704 
9705 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9706   QualType T = FD->getType();
9707   assert(T->isFunctionType() && "function decl is not of function type");
9708   const FunctionType *FT = T->castAs<FunctionType>();
9709 
9710   // Set an implicit return of 'zero' if the function can return some integral,
9711   // enumeration, pointer or nullptr type.
9712   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9713       FT->getReturnType()->isAnyPointerType() ||
9714       FT->getReturnType()->isNullPtrType())
9715     // DllMain is exempt because a return value of zero means it failed.
9716     if (FD->getName() != "DllMain")
9717       FD->setHasImplicitReturnZero(true);
9718 
9719   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9720     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9721     FD->setInvalidDecl();
9722   }
9723 }
9724 
9725 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9726   // FIXME: Need strict checking.  In C89, we need to check for
9727   // any assignment, increment, decrement, function-calls, or
9728   // commas outside of a sizeof.  In C99, it's the same list,
9729   // except that the aforementioned are allowed in unevaluated
9730   // expressions.  Everything else falls under the
9731   // "may accept other forms of constant expressions" exception.
9732   // (We never end up here for C++, so the constant expression
9733   // rules there don't matter.)
9734   const Expr *Culprit;
9735   if (Init->isConstantInitializer(Context, false, &Culprit))
9736     return false;
9737   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9738     << Culprit->getSourceRange();
9739   return true;
9740 }
9741 
9742 namespace {
9743   // Visits an initialization expression to see if OrigDecl is evaluated in
9744   // its own initialization and throws a warning if it does.
9745   class SelfReferenceChecker
9746       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9747     Sema &S;
9748     Decl *OrigDecl;
9749     bool isRecordType;
9750     bool isPODType;
9751     bool isReferenceType;
9752 
9753     bool isInitList;
9754     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9755 
9756   public:
9757     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9758 
9759     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9760                                                     S(S), OrigDecl(OrigDecl) {
9761       isPODType = false;
9762       isRecordType = false;
9763       isReferenceType = false;
9764       isInitList = false;
9765       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9766         isPODType = VD->getType().isPODType(S.Context);
9767         isRecordType = VD->getType()->isRecordType();
9768         isReferenceType = VD->getType()->isReferenceType();
9769       }
9770     }
9771 
9772     // For most expressions, just call the visitor.  For initializer lists,
9773     // track the index of the field being initialized since fields are
9774     // initialized in order allowing use of previously initialized fields.
9775     void CheckExpr(Expr *E) {
9776       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9777       if (!InitList) {
9778         Visit(E);
9779         return;
9780       }
9781 
9782       // Track and increment the index here.
9783       isInitList = true;
9784       InitFieldIndex.push_back(0);
9785       for (auto Child : InitList->children()) {
9786         CheckExpr(cast<Expr>(Child));
9787         ++InitFieldIndex.back();
9788       }
9789       InitFieldIndex.pop_back();
9790     }
9791 
9792     // Returns true if MemberExpr is checked and no further checking is needed.
9793     // Returns false if additional checking is required.
9794     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9795       llvm::SmallVector<FieldDecl*, 4> Fields;
9796       Expr *Base = E;
9797       bool ReferenceField = false;
9798 
9799       // Get the field memebers used.
9800       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9801         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9802         if (!FD)
9803           return false;
9804         Fields.push_back(FD);
9805         if (FD->getType()->isReferenceType())
9806           ReferenceField = true;
9807         Base = ME->getBase()->IgnoreParenImpCasts();
9808       }
9809 
9810       // Keep checking only if the base Decl is the same.
9811       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9812       if (!DRE || DRE->getDecl() != OrigDecl)
9813         return false;
9814 
9815       // A reference field can be bound to an unininitialized field.
9816       if (CheckReference && !ReferenceField)
9817         return true;
9818 
9819       // Convert FieldDecls to their index number.
9820       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9821       for (const FieldDecl *I : llvm::reverse(Fields))
9822         UsedFieldIndex.push_back(I->getFieldIndex());
9823 
9824       // See if a warning is needed by checking the first difference in index
9825       // numbers.  If field being used has index less than the field being
9826       // initialized, then the use is safe.
9827       for (auto UsedIter = UsedFieldIndex.begin(),
9828                 UsedEnd = UsedFieldIndex.end(),
9829                 OrigIter = InitFieldIndex.begin(),
9830                 OrigEnd = InitFieldIndex.end();
9831            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9832         if (*UsedIter < *OrigIter)
9833           return true;
9834         if (*UsedIter > *OrigIter)
9835           break;
9836       }
9837 
9838       // TODO: Add a different warning which will print the field names.
9839       HandleDeclRefExpr(DRE);
9840       return true;
9841     }
9842 
9843     // For most expressions, the cast is directly above the DeclRefExpr.
9844     // For conditional operators, the cast can be outside the conditional
9845     // operator if both expressions are DeclRefExpr's.
9846     void HandleValue(Expr *E) {
9847       E = E->IgnoreParens();
9848       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9849         HandleDeclRefExpr(DRE);
9850         return;
9851       }
9852 
9853       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9854         Visit(CO->getCond());
9855         HandleValue(CO->getTrueExpr());
9856         HandleValue(CO->getFalseExpr());
9857         return;
9858       }
9859 
9860       if (BinaryConditionalOperator *BCO =
9861               dyn_cast<BinaryConditionalOperator>(E)) {
9862         Visit(BCO->getCond());
9863         HandleValue(BCO->getFalseExpr());
9864         return;
9865       }
9866 
9867       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9868         HandleValue(OVE->getSourceExpr());
9869         return;
9870       }
9871 
9872       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9873         if (BO->getOpcode() == BO_Comma) {
9874           Visit(BO->getLHS());
9875           HandleValue(BO->getRHS());
9876           return;
9877         }
9878       }
9879 
9880       if (isa<MemberExpr>(E)) {
9881         if (isInitList) {
9882           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9883                                       false /*CheckReference*/))
9884             return;
9885         }
9886 
9887         Expr *Base = E->IgnoreParenImpCasts();
9888         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9889           // Check for static member variables and don't warn on them.
9890           if (!isa<FieldDecl>(ME->getMemberDecl()))
9891             return;
9892           Base = ME->getBase()->IgnoreParenImpCasts();
9893         }
9894         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9895           HandleDeclRefExpr(DRE);
9896         return;
9897       }
9898 
9899       Visit(E);
9900     }
9901 
9902     // Reference types not handled in HandleValue are handled here since all
9903     // uses of references are bad, not just r-value uses.
9904     void VisitDeclRefExpr(DeclRefExpr *E) {
9905       if (isReferenceType)
9906         HandleDeclRefExpr(E);
9907     }
9908 
9909     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9910       if (E->getCastKind() == CK_LValueToRValue) {
9911         HandleValue(E->getSubExpr());
9912         return;
9913       }
9914 
9915       Inherited::VisitImplicitCastExpr(E);
9916     }
9917 
9918     void VisitMemberExpr(MemberExpr *E) {
9919       if (isInitList) {
9920         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9921           return;
9922       }
9923 
9924       // Don't warn on arrays since they can be treated as pointers.
9925       if (E->getType()->canDecayToPointerType()) return;
9926 
9927       // Warn when a non-static method call is followed by non-static member
9928       // field accesses, which is followed by a DeclRefExpr.
9929       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9930       bool Warn = (MD && !MD->isStatic());
9931       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9932       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9933         if (!isa<FieldDecl>(ME->getMemberDecl()))
9934           Warn = false;
9935         Base = ME->getBase()->IgnoreParenImpCasts();
9936       }
9937 
9938       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9939         if (Warn)
9940           HandleDeclRefExpr(DRE);
9941         return;
9942       }
9943 
9944       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9945       // Visit that expression.
9946       Visit(Base);
9947     }
9948 
9949     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9950       Expr *Callee = E->getCallee();
9951 
9952       if (isa<UnresolvedLookupExpr>(Callee))
9953         return Inherited::VisitCXXOperatorCallExpr(E);
9954 
9955       Visit(Callee);
9956       for (auto Arg: E->arguments())
9957         HandleValue(Arg->IgnoreParenImpCasts());
9958     }
9959 
9960     void VisitUnaryOperator(UnaryOperator *E) {
9961       // For POD record types, addresses of its own members are well-defined.
9962       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9963           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9964         if (!isPODType)
9965           HandleValue(E->getSubExpr());
9966         return;
9967       }
9968 
9969       if (E->isIncrementDecrementOp()) {
9970         HandleValue(E->getSubExpr());
9971         return;
9972       }
9973 
9974       Inherited::VisitUnaryOperator(E);
9975     }
9976 
9977     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9978 
9979     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9980       if (E->getConstructor()->isCopyConstructor()) {
9981         Expr *ArgExpr = E->getArg(0);
9982         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9983           if (ILE->getNumInits() == 1)
9984             ArgExpr = ILE->getInit(0);
9985         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9986           if (ICE->getCastKind() == CK_NoOp)
9987             ArgExpr = ICE->getSubExpr();
9988         HandleValue(ArgExpr);
9989         return;
9990       }
9991       Inherited::VisitCXXConstructExpr(E);
9992     }
9993 
9994     void VisitCallExpr(CallExpr *E) {
9995       // Treat std::move as a use.
9996       if (E->isCallToStdMove()) {
9997         HandleValue(E->getArg(0));
9998         return;
9999       }
10000 
10001       Inherited::VisitCallExpr(E);
10002     }
10003 
10004     void VisitBinaryOperator(BinaryOperator *E) {
10005       if (E->isCompoundAssignmentOp()) {
10006         HandleValue(E->getLHS());
10007         Visit(E->getRHS());
10008         return;
10009       }
10010 
10011       Inherited::VisitBinaryOperator(E);
10012     }
10013 
10014     // A custom visitor for BinaryConditionalOperator is needed because the
10015     // regular visitor would check the condition and true expression separately
10016     // but both point to the same place giving duplicate diagnostics.
10017     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10018       Visit(E->getCond());
10019       Visit(E->getFalseExpr());
10020     }
10021 
10022     void HandleDeclRefExpr(DeclRefExpr *DRE) {
10023       Decl* ReferenceDecl = DRE->getDecl();
10024       if (OrigDecl != ReferenceDecl) return;
10025       unsigned diag;
10026       if (isReferenceType) {
10027         diag = diag::warn_uninit_self_reference_in_reference_init;
10028       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10029         diag = diag::warn_static_self_reference_in_init;
10030       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10031                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10032                  DRE->getDecl()->getType()->isRecordType()) {
10033         diag = diag::warn_uninit_self_reference_in_init;
10034       } else {
10035         // Local variables will be handled by the CFG analysis.
10036         return;
10037       }
10038 
10039       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10040                             S.PDiag(diag)
10041                               << DRE->getNameInfo().getName()
10042                               << OrigDecl->getLocation()
10043                               << DRE->getSourceRange());
10044     }
10045   };
10046 
10047   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10048   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10049                                  bool DirectInit) {
10050     // Parameters arguments are occassionially constructed with itself,
10051     // for instance, in recursive functions.  Skip them.
10052     if (isa<ParmVarDecl>(OrigDecl))
10053       return;
10054 
10055     E = E->IgnoreParens();
10056 
10057     // Skip checking T a = a where T is not a record or reference type.
10058     // Doing so is a way to silence uninitialized warnings.
10059     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10060       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10061         if (ICE->getCastKind() == CK_LValueToRValue)
10062           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10063             if (DRE->getDecl() == OrigDecl)
10064               return;
10065 
10066     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10067   }
10068 } // end anonymous namespace
10069 
10070 namespace {
10071   // Simple wrapper to add the name of a variable or (if no variable is
10072   // available) a DeclarationName into a diagnostic.
10073   struct VarDeclOrName {
10074     VarDecl *VDecl;
10075     DeclarationName Name;
10076 
10077     friend const Sema::SemaDiagnosticBuilder &
10078     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10079       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10080     }
10081   };
10082 } // end anonymous namespace
10083 
10084 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10085                                             DeclarationName Name, QualType Type,
10086                                             TypeSourceInfo *TSI,
10087                                             SourceRange Range, bool DirectInit,
10088                                             Expr *Init) {
10089   bool IsInitCapture = !VDecl;
10090   assert((!VDecl || !VDecl->isInitCapture()) &&
10091          "init captures are expected to be deduced prior to initialization");
10092 
10093   VarDeclOrName VN{VDecl, Name};
10094 
10095   DeducedType *Deduced = Type->getContainedDeducedType();
10096   assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10097 
10098   // C++11 [dcl.spec.auto]p3
10099   if (!Init) {
10100     assert(VDecl && "no init for init capture deduction?");
10101     Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10102       << VDecl->getDeclName() << Type;
10103     return QualType();
10104   }
10105 
10106   ArrayRef<Expr*> DeduceInits = Init;
10107   if (DirectInit) {
10108     if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10109       DeduceInits = PL->exprs();
10110   }
10111 
10112   if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10113     assert(VDecl && "non-auto type for init capture deduction?");
10114     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10115     InitializationKind Kind = InitializationKind::CreateForInit(
10116         VDecl->getLocation(), DirectInit, Init);
10117     // FIXME: Initialization should not be taking a mutable list of inits.
10118     SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10119     return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10120                                                        InitsCopy);
10121   }
10122 
10123   if (DirectInit) {
10124     if (auto *IL = dyn_cast<InitListExpr>(Init))
10125       DeduceInits = IL->inits();
10126   }
10127 
10128   // Deduction only works if we have exactly one source expression.
10129   if (DeduceInits.empty()) {
10130     // It isn't possible to write this directly, but it is possible to
10131     // end up in this situation with "auto x(some_pack...);"
10132     Diag(Init->getLocStart(), IsInitCapture
10133                                   ? diag::err_init_capture_no_expression
10134                                   : diag::err_auto_var_init_no_expression)
10135         << VN << Type << Range;
10136     return QualType();
10137   }
10138 
10139   if (DeduceInits.size() > 1) {
10140     Diag(DeduceInits[1]->getLocStart(),
10141          IsInitCapture ? diag::err_init_capture_multiple_expressions
10142                        : diag::err_auto_var_init_multiple_expressions)
10143         << VN << Type << Range;
10144     return QualType();
10145   }
10146 
10147   Expr *DeduceInit = DeduceInits[0];
10148   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10149     Diag(Init->getLocStart(), IsInitCapture
10150                                   ? diag::err_init_capture_paren_braces
10151                                   : diag::err_auto_var_init_paren_braces)
10152         << isa<InitListExpr>(Init) << VN << Type << Range;
10153     return QualType();
10154   }
10155 
10156   // Expressions default to 'id' when we're in a debugger.
10157   bool DefaultedAnyToId = false;
10158   if (getLangOpts().DebuggerCastResultToId &&
10159       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10160     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10161     if (Result.isInvalid()) {
10162       return QualType();
10163     }
10164     Init = Result.get();
10165     DefaultedAnyToId = true;
10166   }
10167 
10168   // C++ [dcl.decomp]p1:
10169   //   If the assignment-expression [...] has array type A and no ref-qualifier
10170   //   is present, e has type cv A
10171   if (VDecl && isa<DecompositionDecl>(VDecl) &&
10172       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10173       DeduceInit->getType()->isConstantArrayType())
10174     return Context.getQualifiedType(DeduceInit->getType(),
10175                                     Type.getQualifiers());
10176 
10177   QualType DeducedType;
10178   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10179     if (!IsInitCapture)
10180       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10181     else if (isa<InitListExpr>(Init))
10182       Diag(Range.getBegin(),
10183            diag::err_init_capture_deduction_failure_from_init_list)
10184           << VN
10185           << (DeduceInit->getType().isNull() ? TSI->getType()
10186                                              : DeduceInit->getType())
10187           << DeduceInit->getSourceRange();
10188     else
10189       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10190           << VN << TSI->getType()
10191           << (DeduceInit->getType().isNull() ? TSI->getType()
10192                                              : DeduceInit->getType())
10193           << DeduceInit->getSourceRange();
10194   }
10195 
10196   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10197   // 'id' instead of a specific object type prevents most of our usual
10198   // checks.
10199   // We only want to warn outside of template instantiations, though:
10200   // inside a template, the 'id' could have come from a parameter.
10201   if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10202       !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10203     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10204     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10205   }
10206 
10207   return DeducedType;
10208 }
10209 
10210 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10211                                          Expr *Init) {
10212   QualType DeducedType = deduceVarTypeFromInitializer(
10213       VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10214       VDecl->getSourceRange(), DirectInit, Init);
10215   if (DeducedType.isNull()) {
10216     VDecl->setInvalidDecl();
10217     return true;
10218   }
10219 
10220   VDecl->setType(DeducedType);
10221   assert(VDecl->isLinkageValid());
10222 
10223   // In ARC, infer lifetime.
10224   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10225     VDecl->setInvalidDecl();
10226 
10227   // If this is a redeclaration, check that the type we just deduced matches
10228   // the previously declared type.
10229   if (VarDecl *Old = VDecl->getPreviousDecl()) {
10230     // We never need to merge the type, because we cannot form an incomplete
10231     // array of auto, nor deduce such a type.
10232     MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10233   }
10234 
10235   // Check the deduced type is valid for a variable declaration.
10236   CheckVariableDeclarationType(VDecl);
10237   return VDecl->isInvalidDecl();
10238 }
10239 
10240 /// AddInitializerToDecl - Adds the initializer Init to the
10241 /// declaration dcl. If DirectInit is true, this is C++ direct
10242 /// initialization rather than copy initialization.
10243 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10244   // If there is no declaration, there was an error parsing it.  Just ignore
10245   // the initializer.
10246   if (!RealDecl || RealDecl->isInvalidDecl()) {
10247     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10248     return;
10249   }
10250 
10251   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10252     // Pure-specifiers are handled in ActOnPureSpecifier.
10253     Diag(Method->getLocation(), diag::err_member_function_initialization)
10254       << Method->getDeclName() << Init->getSourceRange();
10255     Method->setInvalidDecl();
10256     return;
10257   }
10258 
10259   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10260   if (!VDecl) {
10261     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
10262     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10263     RealDecl->setInvalidDecl();
10264     return;
10265   }
10266 
10267   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10268   if (VDecl->getType()->isUndeducedType()) {
10269     // Attempt typo correction early so that the type of the init expression can
10270     // be deduced based on the chosen correction if the original init contains a
10271     // TypoExpr.
10272     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10273     if (!Res.isUsable()) {
10274       RealDecl->setInvalidDecl();
10275       return;
10276     }
10277     Init = Res.get();
10278 
10279     if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10280       return;
10281   }
10282 
10283   // dllimport cannot be used on variable definitions.
10284   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10285     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10286     VDecl->setInvalidDecl();
10287     return;
10288   }
10289 
10290   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10291     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10292     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10293     VDecl->setInvalidDecl();
10294     return;
10295   }
10296 
10297   if (!VDecl->getType()->isDependentType()) {
10298     // A definition must end up with a complete type, which means it must be
10299     // complete with the restriction that an array type might be completed by
10300     // the initializer; note that later code assumes this restriction.
10301     QualType BaseDeclType = VDecl->getType();
10302     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10303       BaseDeclType = Array->getElementType();
10304     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10305                             diag::err_typecheck_decl_incomplete_type)) {
10306       RealDecl->setInvalidDecl();
10307       return;
10308     }
10309 
10310     // The variable can not have an abstract class type.
10311     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10312                                diag::err_abstract_type_in_decl,
10313                                AbstractVariableType))
10314       VDecl->setInvalidDecl();
10315   }
10316 
10317   // If adding the initializer will turn this declaration into a definition,
10318   // and we already have a definition for this variable, diagnose or otherwise
10319   // handle the situation.
10320   VarDecl *Def;
10321   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10322       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10323       !VDecl->isThisDeclarationADemotedDefinition() &&
10324       checkVarDeclRedefinition(Def, VDecl))
10325     return;
10326 
10327   if (getLangOpts().CPlusPlus) {
10328     // C++ [class.static.data]p4
10329     //   If a static data member is of const integral or const
10330     //   enumeration type, its declaration in the class definition can
10331     //   specify a constant-initializer which shall be an integral
10332     //   constant expression (5.19). In that case, the member can appear
10333     //   in integral constant expressions. The member shall still be
10334     //   defined in a namespace scope if it is used in the program and the
10335     //   namespace scope definition shall not contain an initializer.
10336     //
10337     // We already performed a redefinition check above, but for static
10338     // data members we also need to check whether there was an in-class
10339     // declaration with an initializer.
10340     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10341       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10342           << VDecl->getDeclName();
10343       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10344            diag::note_previous_initializer)
10345           << 0;
10346       return;
10347     }
10348 
10349     if (VDecl->hasLocalStorage())
10350       getCurFunction()->setHasBranchProtectedScope();
10351 
10352     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10353       VDecl->setInvalidDecl();
10354       return;
10355     }
10356   }
10357 
10358   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10359   // a kernel function cannot be initialized."
10360   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10361     Diag(VDecl->getLocation(), diag::err_local_cant_init);
10362     VDecl->setInvalidDecl();
10363     return;
10364   }
10365 
10366   // Get the decls type and save a reference for later, since
10367   // CheckInitializerTypes may change it.
10368   QualType DclT = VDecl->getType(), SavT = DclT;
10369 
10370   // Expressions default to 'id' when we're in a debugger
10371   // and we are assigning it to a variable of Objective-C pointer type.
10372   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10373       Init->getType() == Context.UnknownAnyTy) {
10374     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10375     if (Result.isInvalid()) {
10376       VDecl->setInvalidDecl();
10377       return;
10378     }
10379     Init = Result.get();
10380   }
10381 
10382   // Perform the initialization.
10383   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10384   if (!VDecl->isInvalidDecl()) {
10385     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10386     InitializationKind Kind = InitializationKind::CreateForInit(
10387         VDecl->getLocation(), DirectInit, Init);
10388 
10389     MultiExprArg Args = Init;
10390     if (CXXDirectInit)
10391       Args = MultiExprArg(CXXDirectInit->getExprs(),
10392                           CXXDirectInit->getNumExprs());
10393 
10394     // Try to correct any TypoExprs in the initialization arguments.
10395     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10396       ExprResult Res = CorrectDelayedTyposInExpr(
10397           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10398             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10399             return Init.Failed() ? ExprError() : E;
10400           });
10401       if (Res.isInvalid()) {
10402         VDecl->setInvalidDecl();
10403       } else if (Res.get() != Args[Idx]) {
10404         Args[Idx] = Res.get();
10405       }
10406     }
10407     if (VDecl->isInvalidDecl())
10408       return;
10409 
10410     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10411                                    /*TopLevelOfInitList=*/false,
10412                                    /*TreatUnavailableAsInvalid=*/false);
10413     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10414     if (Result.isInvalid()) {
10415       VDecl->setInvalidDecl();
10416       return;
10417     }
10418 
10419     Init = Result.getAs<Expr>();
10420   }
10421 
10422   // Check for self-references within variable initializers.
10423   // Variables declared within a function/method body (except for references)
10424   // are handled by a dataflow analysis.
10425   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10426       VDecl->getType()->isReferenceType()) {
10427     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10428   }
10429 
10430   // If the type changed, it means we had an incomplete type that was
10431   // completed by the initializer. For example:
10432   //   int ary[] = { 1, 3, 5 };
10433   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10434   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10435     VDecl->setType(DclT);
10436 
10437   if (!VDecl->isInvalidDecl()) {
10438     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10439 
10440     if (VDecl->hasAttr<BlocksAttr>())
10441       checkRetainCycles(VDecl, Init);
10442 
10443     // It is safe to assign a weak reference into a strong variable.
10444     // Although this code can still have problems:
10445     //   id x = self.weakProp;
10446     //   id y = self.weakProp;
10447     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10448     // paths through the function. This should be revisited if
10449     // -Wrepeated-use-of-weak is made flow-sensitive.
10450     if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10451          VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10452         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10453                          Init->getLocStart()))
10454       getCurFunction()->markSafeWeakUse(Init);
10455   }
10456 
10457   // The initialization is usually a full-expression.
10458   //
10459   // FIXME: If this is a braced initialization of an aggregate, it is not
10460   // an expression, and each individual field initializer is a separate
10461   // full-expression. For instance, in:
10462   //
10463   //   struct Temp { ~Temp(); };
10464   //   struct S { S(Temp); };
10465   //   struct T { S a, b; } t = { Temp(), Temp() }
10466   //
10467   // we should destroy the first Temp before constructing the second.
10468   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10469                                           false,
10470                                           VDecl->isConstexpr());
10471   if (Result.isInvalid()) {
10472     VDecl->setInvalidDecl();
10473     return;
10474   }
10475   Init = Result.get();
10476 
10477   // Attach the initializer to the decl.
10478   VDecl->setInit(Init);
10479 
10480   if (VDecl->isLocalVarDecl()) {
10481     // Don't check the initializer if the declaration is malformed.
10482     if (VDecl->isInvalidDecl()) {
10483       // do nothing
10484 
10485     // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10486     // This is true even in OpenCL C++.
10487     } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10488       CheckForConstantInitializer(Init, DclT);
10489 
10490     // Otherwise, C++ does not restrict the initializer.
10491     } else if (getLangOpts().CPlusPlus) {
10492       // do nothing
10493 
10494     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10495     // static storage duration shall be constant expressions or string literals.
10496     } else if (VDecl->getStorageClass() == SC_Static) {
10497       CheckForConstantInitializer(Init, DclT);
10498 
10499     // C89 is stricter than C99 for aggregate initializers.
10500     // C89 6.5.7p3: All the expressions [...] in an initializer list
10501     // for an object that has aggregate or union type shall be
10502     // constant expressions.
10503     } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10504                isa<InitListExpr>(Init)) {
10505       const Expr *Culprit;
10506       if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10507         Diag(Culprit->getExprLoc(),
10508              diag::ext_aggregate_init_not_constant)
10509           << Culprit->getSourceRange();
10510       }
10511     }
10512   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10513              VDecl->getLexicalDeclContext()->isRecord()) {
10514     // This is an in-class initialization for a static data member, e.g.,
10515     //
10516     // struct S {
10517     //   static const int value = 17;
10518     // };
10519 
10520     // C++ [class.mem]p4:
10521     //   A member-declarator can contain a constant-initializer only
10522     //   if it declares a static member (9.4) of const integral or
10523     //   const enumeration type, see 9.4.2.
10524     //
10525     // C++11 [class.static.data]p3:
10526     //   If a non-volatile non-inline const static data member is of integral
10527     //   or enumeration type, its declaration in the class definition can
10528     //   specify a brace-or-equal-initializer in which every initializer-clause
10529     //   that is an assignment-expression is a constant expression. A static
10530     //   data member of literal type can be declared in the class definition
10531     //   with the constexpr specifier; if so, its declaration shall specify a
10532     //   brace-or-equal-initializer in which every initializer-clause that is
10533     //   an assignment-expression is a constant expression.
10534 
10535     // Do nothing on dependent types.
10536     if (DclT->isDependentType()) {
10537 
10538     // Allow any 'static constexpr' members, whether or not they are of literal
10539     // type. We separately check that every constexpr variable is of literal
10540     // type.
10541     } else if (VDecl->isConstexpr()) {
10542 
10543     // Require constness.
10544     } else if (!DclT.isConstQualified()) {
10545       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10546         << Init->getSourceRange();
10547       VDecl->setInvalidDecl();
10548 
10549     // We allow integer constant expressions in all cases.
10550     } else if (DclT->isIntegralOrEnumerationType()) {
10551       // Check whether the expression is a constant expression.
10552       SourceLocation Loc;
10553       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10554         // In C++11, a non-constexpr const static data member with an
10555         // in-class initializer cannot be volatile.
10556         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10557       else if (Init->isValueDependent())
10558         ; // Nothing to check.
10559       else if (Init->isIntegerConstantExpr(Context, &Loc))
10560         ; // Ok, it's an ICE!
10561       else if (Init->isEvaluatable(Context)) {
10562         // If we can constant fold the initializer through heroics, accept it,
10563         // but report this as a use of an extension for -pedantic.
10564         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10565           << Init->getSourceRange();
10566       } else {
10567         // Otherwise, this is some crazy unknown case.  Report the issue at the
10568         // location provided by the isIntegerConstantExpr failed check.
10569         Diag(Loc, diag::err_in_class_initializer_non_constant)
10570           << Init->getSourceRange();
10571         VDecl->setInvalidDecl();
10572       }
10573 
10574     // We allow foldable floating-point constants as an extension.
10575     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10576       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10577       // it anyway and provide a fixit to add the 'constexpr'.
10578       if (getLangOpts().CPlusPlus11) {
10579         Diag(VDecl->getLocation(),
10580              diag::ext_in_class_initializer_float_type_cxx11)
10581             << DclT << Init->getSourceRange();
10582         Diag(VDecl->getLocStart(),
10583              diag::note_in_class_initializer_float_type_cxx11)
10584             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10585       } else {
10586         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10587           << DclT << Init->getSourceRange();
10588 
10589         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10590           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10591             << Init->getSourceRange();
10592           VDecl->setInvalidDecl();
10593         }
10594       }
10595 
10596     // Suggest adding 'constexpr' in C++11 for literal types.
10597     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10598       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10599         << DclT << Init->getSourceRange()
10600         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10601       VDecl->setConstexpr(true);
10602 
10603     } else {
10604       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10605         << DclT << Init->getSourceRange();
10606       VDecl->setInvalidDecl();
10607     }
10608   } else if (VDecl->isFileVarDecl()) {
10609     // In C, extern is typically used to avoid tentative definitions when
10610     // declaring variables in headers, but adding an intializer makes it a
10611     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10612     // In C++, extern is often used to give implictly static const variables
10613     // external linkage, so don't warn in that case. If selectany is present,
10614     // this might be header code intended for C and C++ inclusion, so apply the
10615     // C++ rules.
10616     if (VDecl->getStorageClass() == SC_Extern &&
10617         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10618          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10619         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10620         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10621       Diag(VDecl->getLocation(), diag::warn_extern_init);
10622 
10623     // C99 6.7.8p4. All file scoped initializers need to be constant.
10624     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10625       CheckForConstantInitializer(Init, DclT);
10626   }
10627 
10628   // We will represent direct-initialization similarly to copy-initialization:
10629   //    int x(1);  -as-> int x = 1;
10630   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10631   //
10632   // Clients that want to distinguish between the two forms, can check for
10633   // direct initializer using VarDecl::getInitStyle().
10634   // A major benefit is that clients that don't particularly care about which
10635   // exactly form was it (like the CodeGen) can handle both cases without
10636   // special case code.
10637 
10638   // C++ 8.5p11:
10639   // The form of initialization (using parentheses or '=') is generally
10640   // insignificant, but does matter when the entity being initialized has a
10641   // class type.
10642   if (CXXDirectInit) {
10643     assert(DirectInit && "Call-style initializer must be direct init.");
10644     VDecl->setInitStyle(VarDecl::CallInit);
10645   } else if (DirectInit) {
10646     // This must be list-initialization. No other way is direct-initialization.
10647     VDecl->setInitStyle(VarDecl::ListInit);
10648   }
10649 
10650   CheckCompleteVariableDeclaration(VDecl);
10651 }
10652 
10653 /// ActOnInitializerError - Given that there was an error parsing an
10654 /// initializer for the given declaration, try to return to some form
10655 /// of sanity.
10656 void Sema::ActOnInitializerError(Decl *D) {
10657   // Our main concern here is re-establishing invariants like "a
10658   // variable's type is either dependent or complete".
10659   if (!D || D->isInvalidDecl()) return;
10660 
10661   VarDecl *VD = dyn_cast<VarDecl>(D);
10662   if (!VD) return;
10663 
10664   // Bindings are not usable if we can't make sense of the initializer.
10665   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10666     for (auto *BD : DD->bindings())
10667       BD->setInvalidDecl();
10668 
10669   // Auto types are meaningless if we can't make sense of the initializer.
10670   if (ParsingInitForAutoVars.count(D)) {
10671     D->setInvalidDecl();
10672     return;
10673   }
10674 
10675   QualType Ty = VD->getType();
10676   if (Ty->isDependentType()) return;
10677 
10678   // Require a complete type.
10679   if (RequireCompleteType(VD->getLocation(),
10680                           Context.getBaseElementType(Ty),
10681                           diag::err_typecheck_decl_incomplete_type)) {
10682     VD->setInvalidDecl();
10683     return;
10684   }
10685 
10686   // Require a non-abstract type.
10687   if (RequireNonAbstractType(VD->getLocation(), Ty,
10688                              diag::err_abstract_type_in_decl,
10689                              AbstractVariableType)) {
10690     VD->setInvalidDecl();
10691     return;
10692   }
10693 
10694   // Don't bother complaining about constructors or destructors,
10695   // though.
10696 }
10697 
10698 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10699   // If there is no declaration, there was an error parsing it. Just ignore it.
10700   if (!RealDecl)
10701     return;
10702 
10703   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10704     QualType Type = Var->getType();
10705 
10706     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10707     if (isa<DecompositionDecl>(RealDecl)) {
10708       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10709       Var->setInvalidDecl();
10710       return;
10711     }
10712 
10713     if (Type->isUndeducedType() &&
10714         DeduceVariableDeclarationType(Var, false, nullptr))
10715       return;
10716 
10717     // C++11 [class.static.data]p3: A static data member can be declared with
10718     // the constexpr specifier; if so, its declaration shall specify
10719     // a brace-or-equal-initializer.
10720     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10721     // the definition of a variable [...] or the declaration of a static data
10722     // member.
10723     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10724         !Var->isThisDeclarationADemotedDefinition()) {
10725       if (Var->isStaticDataMember()) {
10726         // C++1z removes the relevant rule; the in-class declaration is always
10727         // a definition there.
10728         if (!getLangOpts().CPlusPlus1z) {
10729           Diag(Var->getLocation(),
10730                diag::err_constexpr_static_mem_var_requires_init)
10731             << Var->getDeclName();
10732           Var->setInvalidDecl();
10733           return;
10734         }
10735       } else {
10736         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10737         Var->setInvalidDecl();
10738         return;
10739       }
10740     }
10741 
10742     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10743     // definition having the concept specifier is called a variable concept. A
10744     // concept definition refers to [...] a variable concept and its initializer.
10745     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10746       if (VTD->isConcept()) {
10747         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10748         Var->setInvalidDecl();
10749         return;
10750       }
10751     }
10752 
10753     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10754     // be initialized.
10755     if (!Var->isInvalidDecl() &&
10756         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10757         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10758       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10759       Var->setInvalidDecl();
10760       return;
10761     }
10762 
10763     switch (Var->isThisDeclarationADefinition()) {
10764     case VarDecl::Definition:
10765       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10766         break;
10767 
10768       // We have an out-of-line definition of a static data member
10769       // that has an in-class initializer, so we type-check this like
10770       // a declaration.
10771       //
10772       // Fall through
10773 
10774     case VarDecl::DeclarationOnly:
10775       // It's only a declaration.
10776 
10777       // Block scope. C99 6.7p7: If an identifier for an object is
10778       // declared with no linkage (C99 6.2.2p6), the type for the
10779       // object shall be complete.
10780       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10781           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10782           RequireCompleteType(Var->getLocation(), Type,
10783                               diag::err_typecheck_decl_incomplete_type))
10784         Var->setInvalidDecl();
10785 
10786       // Make sure that the type is not abstract.
10787       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10788           RequireNonAbstractType(Var->getLocation(), Type,
10789                                  diag::err_abstract_type_in_decl,
10790                                  AbstractVariableType))
10791         Var->setInvalidDecl();
10792       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10793           Var->getStorageClass() == SC_PrivateExtern) {
10794         Diag(Var->getLocation(), diag::warn_private_extern);
10795         Diag(Var->getLocation(), diag::note_private_extern);
10796       }
10797 
10798       return;
10799 
10800     case VarDecl::TentativeDefinition:
10801       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10802       // object that has file scope without an initializer, and without a
10803       // storage-class specifier or with the storage-class specifier "static",
10804       // constitutes a tentative definition. Note: A tentative definition with
10805       // external linkage is valid (C99 6.2.2p5).
10806       if (!Var->isInvalidDecl()) {
10807         if (const IncompleteArrayType *ArrayT
10808                                     = Context.getAsIncompleteArrayType(Type)) {
10809           if (RequireCompleteType(Var->getLocation(),
10810                                   ArrayT->getElementType(),
10811                                   diag::err_illegal_decl_array_incomplete_type))
10812             Var->setInvalidDecl();
10813         } else if (Var->getStorageClass() == SC_Static) {
10814           // C99 6.9.2p3: If the declaration of an identifier for an object is
10815           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10816           // declared type shall not be an incomplete type.
10817           // NOTE: code such as the following
10818           //     static struct s;
10819           //     struct s { int a; };
10820           // is accepted by gcc. Hence here we issue a warning instead of
10821           // an error and we do not invalidate the static declaration.
10822           // NOTE: to avoid multiple warnings, only check the first declaration.
10823           if (Var->isFirstDecl())
10824             RequireCompleteType(Var->getLocation(), Type,
10825                                 diag::ext_typecheck_decl_incomplete_type);
10826         }
10827       }
10828 
10829       // Record the tentative definition; we're done.
10830       if (!Var->isInvalidDecl())
10831         TentativeDefinitions.push_back(Var);
10832       return;
10833     }
10834 
10835     // Provide a specific diagnostic for uninitialized variable
10836     // definitions with incomplete array type.
10837     if (Type->isIncompleteArrayType()) {
10838       Diag(Var->getLocation(),
10839            diag::err_typecheck_incomplete_array_needs_initializer);
10840       Var->setInvalidDecl();
10841       return;
10842     }
10843 
10844     // Provide a specific diagnostic for uninitialized variable
10845     // definitions with reference type.
10846     if (Type->isReferenceType()) {
10847       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10848         << Var->getDeclName()
10849         << SourceRange(Var->getLocation(), Var->getLocation());
10850       Var->setInvalidDecl();
10851       return;
10852     }
10853 
10854     // Do not attempt to type-check the default initializer for a
10855     // variable with dependent type.
10856     if (Type->isDependentType())
10857       return;
10858 
10859     if (Var->isInvalidDecl())
10860       return;
10861 
10862     if (!Var->hasAttr<AliasAttr>()) {
10863       if (RequireCompleteType(Var->getLocation(),
10864                               Context.getBaseElementType(Type),
10865                               diag::err_typecheck_decl_incomplete_type)) {
10866         Var->setInvalidDecl();
10867         return;
10868       }
10869     } else {
10870       return;
10871     }
10872 
10873     // The variable can not have an abstract class type.
10874     if (RequireNonAbstractType(Var->getLocation(), Type,
10875                                diag::err_abstract_type_in_decl,
10876                                AbstractVariableType)) {
10877       Var->setInvalidDecl();
10878       return;
10879     }
10880 
10881     // Check for jumps past the implicit initializer.  C++0x
10882     // clarifies that this applies to a "variable with automatic
10883     // storage duration", not a "local variable".
10884     // C++11 [stmt.dcl]p3
10885     //   A program that jumps from a point where a variable with automatic
10886     //   storage duration is not in scope to a point where it is in scope is
10887     //   ill-formed unless the variable has scalar type, class type with a
10888     //   trivial default constructor and a trivial destructor, a cv-qualified
10889     //   version of one of these types, or an array of one of the preceding
10890     //   types and is declared without an initializer.
10891     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10892       if (const RecordType *Record
10893             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10894         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10895         // Mark the function for further checking even if the looser rules of
10896         // C++11 do not require such checks, so that we can diagnose
10897         // incompatibilities with C++98.
10898         if (!CXXRecord->isPOD())
10899           getCurFunction()->setHasBranchProtectedScope();
10900       }
10901     }
10902 
10903     // C++03 [dcl.init]p9:
10904     //   If no initializer is specified for an object, and the
10905     //   object is of (possibly cv-qualified) non-POD class type (or
10906     //   array thereof), the object shall be default-initialized; if
10907     //   the object is of const-qualified type, the underlying class
10908     //   type shall have a user-declared default
10909     //   constructor. Otherwise, if no initializer is specified for
10910     //   a non- static object, the object and its subobjects, if
10911     //   any, have an indeterminate initial value); if the object
10912     //   or any of its subobjects are of const-qualified type, the
10913     //   program is ill-formed.
10914     // C++0x [dcl.init]p11:
10915     //   If no initializer is specified for an object, the object is
10916     //   default-initialized; [...].
10917     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10918     InitializationKind Kind
10919       = InitializationKind::CreateDefault(Var->getLocation());
10920 
10921     InitializationSequence InitSeq(*this, Entity, Kind, None);
10922     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10923     if (Init.isInvalid())
10924       Var->setInvalidDecl();
10925     else if (Init.get()) {
10926       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10927       // This is important for template substitution.
10928       Var->setInitStyle(VarDecl::CallInit);
10929     }
10930 
10931     CheckCompleteVariableDeclaration(Var);
10932   }
10933 }
10934 
10935 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10936   // If there is no declaration, there was an error parsing it. Ignore it.
10937   if (!D)
10938     return;
10939 
10940   VarDecl *VD = dyn_cast<VarDecl>(D);
10941   if (!VD) {
10942     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10943     D->setInvalidDecl();
10944     return;
10945   }
10946 
10947   VD->setCXXForRangeDecl(true);
10948 
10949   // for-range-declaration cannot be given a storage class specifier.
10950   int Error = -1;
10951   switch (VD->getStorageClass()) {
10952   case SC_None:
10953     break;
10954   case SC_Extern:
10955     Error = 0;
10956     break;
10957   case SC_Static:
10958     Error = 1;
10959     break;
10960   case SC_PrivateExtern:
10961     Error = 2;
10962     break;
10963   case SC_Auto:
10964     Error = 3;
10965     break;
10966   case SC_Register:
10967     Error = 4;
10968     break;
10969   }
10970   if (Error != -1) {
10971     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10972       << VD->getDeclName() << Error;
10973     D->setInvalidDecl();
10974   }
10975 }
10976 
10977 StmtResult
10978 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10979                                  IdentifierInfo *Ident,
10980                                  ParsedAttributes &Attrs,
10981                                  SourceLocation AttrEnd) {
10982   // C++1y [stmt.iter]p1:
10983   //   A range-based for statement of the form
10984   //      for ( for-range-identifier : for-range-initializer ) statement
10985   //   is equivalent to
10986   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10987   DeclSpec DS(Attrs.getPool().getFactory());
10988 
10989   const char *PrevSpec;
10990   unsigned DiagID;
10991   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10992                      getPrintingPolicy());
10993 
10994   Declarator D(DS, Declarator::ForContext);
10995   D.SetIdentifier(Ident, IdentLoc);
10996   D.takeAttributes(Attrs, AttrEnd);
10997 
10998   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10999   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11000                 EmptyAttrs, IdentLoc);
11001   Decl *Var = ActOnDeclarator(S, D);
11002   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11003   FinalizeDeclaration(Var);
11004   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11005                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
11006 }
11007 
11008 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11009   if (var->isInvalidDecl()) return;
11010 
11011   if (getLangOpts().OpenCL) {
11012     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11013     // initialiser
11014     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11015         !var->hasInit()) {
11016       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11017           << 1 /*Init*/;
11018       var->setInvalidDecl();
11019       return;
11020     }
11021   }
11022 
11023   // In Objective-C, don't allow jumps past the implicit initialization of a
11024   // local retaining variable.
11025   if (getLangOpts().ObjC1 &&
11026       var->hasLocalStorage()) {
11027     switch (var->getType().getObjCLifetime()) {
11028     case Qualifiers::OCL_None:
11029     case Qualifiers::OCL_ExplicitNone:
11030     case Qualifiers::OCL_Autoreleasing:
11031       break;
11032 
11033     case Qualifiers::OCL_Weak:
11034     case Qualifiers::OCL_Strong:
11035       getCurFunction()->setHasBranchProtectedScope();
11036       break;
11037     }
11038   }
11039 
11040   // Warn about externally-visible variables being defined without a
11041   // prior declaration.  We only want to do this for global
11042   // declarations, but we also specifically need to avoid doing it for
11043   // class members because the linkage of an anonymous class can
11044   // change if it's later given a typedef name.
11045   if (var->isThisDeclarationADefinition() &&
11046       var->getDeclContext()->getRedeclContext()->isFileContext() &&
11047       var->isExternallyVisible() && var->hasLinkage() &&
11048       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11049                                   var->getLocation())) {
11050     // Find a previous declaration that's not a definition.
11051     VarDecl *prev = var->getPreviousDecl();
11052     while (prev && prev->isThisDeclarationADefinition())
11053       prev = prev->getPreviousDecl();
11054 
11055     if (!prev)
11056       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11057   }
11058 
11059   // Cache the result of checking for constant initialization.
11060   Optional<bool> CacheHasConstInit;
11061   const Expr *CacheCulprit;
11062   auto checkConstInit = [&]() mutable {
11063     if (!CacheHasConstInit)
11064       CacheHasConstInit = var->getInit()->isConstantInitializer(
11065             Context, var->getType()->isReferenceType(), &CacheCulprit);
11066     return *CacheHasConstInit;
11067   };
11068 
11069   if (var->getTLSKind() == VarDecl::TLS_Static) {
11070     if (var->getType().isDestructedType()) {
11071       // GNU C++98 edits for __thread, [basic.start.term]p3:
11072       //   The type of an object with thread storage duration shall not
11073       //   have a non-trivial destructor.
11074       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11075       if (getLangOpts().CPlusPlus11)
11076         Diag(var->getLocation(), diag::note_use_thread_local);
11077     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11078       if (!checkConstInit()) {
11079         // GNU C++98 edits for __thread, [basic.start.init]p4:
11080         //   An object of thread storage duration shall not require dynamic
11081         //   initialization.
11082         // FIXME: Need strict checking here.
11083         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11084           << CacheCulprit->getSourceRange();
11085         if (getLangOpts().CPlusPlus11)
11086           Diag(var->getLocation(), diag::note_use_thread_local);
11087       }
11088     }
11089   }
11090 
11091   // Apply section attributes and pragmas to global variables.
11092   bool GlobalStorage = var->hasGlobalStorage();
11093   if (GlobalStorage && var->isThisDeclarationADefinition() &&
11094       !inTemplateInstantiation()) {
11095     PragmaStack<StringLiteral *> *Stack = nullptr;
11096     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11097     if (var->getType().isConstQualified())
11098       Stack = &ConstSegStack;
11099     else if (!var->getInit()) {
11100       Stack = &BSSSegStack;
11101       SectionFlags |= ASTContext::PSF_Write;
11102     } else {
11103       Stack = &DataSegStack;
11104       SectionFlags |= ASTContext::PSF_Write;
11105     }
11106     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11107       var->addAttr(SectionAttr::CreateImplicit(
11108           Context, SectionAttr::Declspec_allocate,
11109           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11110     }
11111     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11112       if (UnifySection(SA->getName(), SectionFlags, var))
11113         var->dropAttr<SectionAttr>();
11114 
11115     // Apply the init_seg attribute if this has an initializer.  If the
11116     // initializer turns out to not be dynamic, we'll end up ignoring this
11117     // attribute.
11118     if (CurInitSeg && var->getInit())
11119       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11120                                                CurInitSegLoc));
11121   }
11122 
11123   // All the following checks are C++ only.
11124   if (!getLangOpts().CPlusPlus) {
11125       // If this variable must be emitted, add it as an initializer for the
11126       // current module.
11127      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11128        Context.addModuleInitializer(ModuleScopes.back().Module, var);
11129      return;
11130   }
11131 
11132   if (auto *DD = dyn_cast<DecompositionDecl>(var))
11133     CheckCompleteDecompositionDeclaration(DD);
11134 
11135   QualType type = var->getType();
11136   if (type->isDependentType()) return;
11137 
11138   // __block variables might require us to capture a copy-initializer.
11139   if (var->hasAttr<BlocksAttr>()) {
11140     // It's currently invalid to ever have a __block variable with an
11141     // array type; should we diagnose that here?
11142 
11143     // Regardless, we don't want to ignore array nesting when
11144     // constructing this copy.
11145     if (type->isStructureOrClassType()) {
11146       EnterExpressionEvaluationContext scope(
11147           *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11148       SourceLocation poi = var->getLocation();
11149       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11150       ExprResult result
11151         = PerformMoveOrCopyInitialization(
11152             InitializedEntity::InitializeBlock(poi, type, false),
11153             var, var->getType(), varRef, /*AllowNRVO=*/true);
11154       if (!result.isInvalid()) {
11155         result = MaybeCreateExprWithCleanups(result);
11156         Expr *init = result.getAs<Expr>();
11157         Context.setBlockVarCopyInits(var, init);
11158       }
11159     }
11160   }
11161 
11162   Expr *Init = var->getInit();
11163   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11164   QualType baseType = Context.getBaseElementType(type);
11165 
11166   if (Init && !Init->isValueDependent()) {
11167     if (var->isConstexpr()) {
11168       SmallVector<PartialDiagnosticAt, 8> Notes;
11169       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11170         SourceLocation DiagLoc = var->getLocation();
11171         // If the note doesn't add any useful information other than a source
11172         // location, fold it into the primary diagnostic.
11173         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11174               diag::note_invalid_subexpr_in_const_expr) {
11175           DiagLoc = Notes[0].first;
11176           Notes.clear();
11177         }
11178         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11179           << var << Init->getSourceRange();
11180         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11181           Diag(Notes[I].first, Notes[I].second);
11182       }
11183     } else if (var->isUsableInConstantExpressions(Context)) {
11184       // Check whether the initializer of a const variable of integral or
11185       // enumeration type is an ICE now, since we can't tell whether it was
11186       // initialized by a constant expression if we check later.
11187       var->checkInitIsICE();
11188     }
11189 
11190     // Don't emit further diagnostics about constexpr globals since they
11191     // were just diagnosed.
11192     if (!var->isConstexpr() && GlobalStorage &&
11193             var->hasAttr<RequireConstantInitAttr>()) {
11194       // FIXME: Need strict checking in C++03 here.
11195       bool DiagErr = getLangOpts().CPlusPlus11
11196           ? !var->checkInitIsICE() : !checkConstInit();
11197       if (DiagErr) {
11198         auto attr = var->getAttr<RequireConstantInitAttr>();
11199         Diag(var->getLocation(), diag::err_require_constant_init_failed)
11200           << Init->getSourceRange();
11201         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11202           << attr->getRange();
11203         if (getLangOpts().CPlusPlus11) {
11204           APValue Value;
11205           SmallVector<PartialDiagnosticAt, 8> Notes;
11206           Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11207           for (auto &it : Notes)
11208             Diag(it.first, it.second);
11209         } else {
11210           Diag(CacheCulprit->getExprLoc(),
11211                diag::note_invalid_subexpr_in_const_expr)
11212               << CacheCulprit->getSourceRange();
11213         }
11214       }
11215     }
11216     else if (!var->isConstexpr() && IsGlobal &&
11217              !getDiagnostics().isIgnored(diag::warn_global_constructor,
11218                                     var->getLocation())) {
11219       // Warn about globals which don't have a constant initializer.  Don't
11220       // warn about globals with a non-trivial destructor because we already
11221       // warned about them.
11222       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11223       if (!(RD && !RD->hasTrivialDestructor())) {
11224         if (!checkConstInit())
11225           Diag(var->getLocation(), diag::warn_global_constructor)
11226             << Init->getSourceRange();
11227       }
11228     }
11229   }
11230 
11231   // Require the destructor.
11232   if (const RecordType *recordType = baseType->getAs<RecordType>())
11233     FinalizeVarWithDestructor(var, recordType);
11234 
11235   // If this variable must be emitted, add it as an initializer for the current
11236   // module.
11237   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11238     Context.addModuleInitializer(ModuleScopes.back().Module, var);
11239 }
11240 
11241 /// \brief Determines if a variable's alignment is dependent.
11242 static bool hasDependentAlignment(VarDecl *VD) {
11243   if (VD->getType()->isDependentType())
11244     return true;
11245   for (auto *I : VD->specific_attrs<AlignedAttr>())
11246     if (I->isAlignmentDependent())
11247       return true;
11248   return false;
11249 }
11250 
11251 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11252 /// any semantic actions necessary after any initializer has been attached.
11253 void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11254   // Note that we are no longer parsing the initializer for this declaration.
11255   ParsingInitForAutoVars.erase(ThisDecl);
11256 
11257   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11258   if (!VD)
11259     return;
11260 
11261   // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11262   if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
11263       !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11264     if (PragmaClangBSSSection.Valid)
11265       VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11266                                                             PragmaClangBSSSection.SectionName,
11267                                                             PragmaClangBSSSection.PragmaLocation));
11268     if (PragmaClangDataSection.Valid)
11269       VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
11270                                                              PragmaClangDataSection.SectionName,
11271                                                              PragmaClangDataSection.PragmaLocation));
11272     if (PragmaClangRodataSection.Valid)
11273       VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11274                                                                PragmaClangRodataSection.SectionName,
11275                                                                PragmaClangRodataSection.PragmaLocation));
11276   }
11277 
11278   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11279     for (auto *BD : DD->bindings()) {
11280       FinalizeDeclaration(BD);
11281     }
11282   }
11283 
11284   checkAttributesAfterMerging(*this, *VD);
11285 
11286   // Perform TLS alignment check here after attributes attached to the variable
11287   // which may affect the alignment have been processed. Only perform the check
11288   // if the target has a maximum TLS alignment (zero means no constraints).
11289   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11290     // Protect the check so that it's not performed on dependent types and
11291     // dependent alignments (we can't determine the alignment in that case).
11292     if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11293         !VD->isInvalidDecl()) {
11294       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11295       if (Context.getDeclAlign(VD) > MaxAlignChars) {
11296         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11297           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11298           << (unsigned)MaxAlignChars.getQuantity();
11299       }
11300     }
11301   }
11302 
11303   if (VD->isStaticLocal()) {
11304     if (FunctionDecl *FD =
11305             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11306       // Static locals inherit dll attributes from their function.
11307       if (Attr *A = getDLLAttr(FD)) {
11308         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11309         NewAttr->setInherited(true);
11310         VD->addAttr(NewAttr);
11311       }
11312       // CUDA E.2.9.4: Within the body of a __device__ or __global__
11313       // function, only __shared__ variables may be declared with
11314       // static storage class.
11315       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11316           CUDADiagIfDeviceCode(VD->getLocation(),
11317                                diag::err_device_static_local_var)
11318               << CurrentCUDATarget())
11319         VD->setInvalidDecl();
11320     }
11321   }
11322 
11323   // Perform check for initializers of device-side global variables.
11324   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11325   // 7.5). We must also apply the same checks to all __shared__
11326   // variables whether they are local or not. CUDA also allows
11327   // constant initializers for __constant__ and __device__ variables.
11328   if (getLangOpts().CUDA) {
11329     const Expr *Init = VD->getInit();
11330     if (Init && VD->hasGlobalStorage()) {
11331       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11332           VD->hasAttr<CUDASharedAttr>()) {
11333         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
11334         bool AllowedInit = false;
11335         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11336           AllowedInit =
11337               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11338         // We'll allow constant initializers even if it's a non-empty
11339         // constructor according to CUDA rules. This deviates from NVCC,
11340         // but allows us to handle things like constexpr constructors.
11341         if (!AllowedInit &&
11342             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11343           AllowedInit = VD->getInit()->isConstantInitializer(
11344               Context, VD->getType()->isReferenceType());
11345 
11346         // Also make sure that destructor, if there is one, is empty.
11347         if (AllowedInit)
11348           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11349             AllowedInit =
11350                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11351 
11352         if (!AllowedInit) {
11353           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11354                                       ? diag::err_shared_var_init
11355                                       : diag::err_dynamic_var_init)
11356               << Init->getSourceRange();
11357           VD->setInvalidDecl();
11358         }
11359       } else {
11360         // This is a host-side global variable.  Check that the initializer is
11361         // callable from the host side.
11362         const FunctionDecl *InitFn = nullptr;
11363         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11364           InitFn = CE->getConstructor();
11365         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11366           InitFn = CE->getDirectCallee();
11367         }
11368         if (InitFn) {
11369           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11370           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11371             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11372                 << InitFnTarget << InitFn;
11373             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11374             VD->setInvalidDecl();
11375           }
11376         }
11377       }
11378     }
11379   }
11380 
11381   // Grab the dllimport or dllexport attribute off of the VarDecl.
11382   const InheritableAttr *DLLAttr = getDLLAttr(VD);
11383 
11384   // Imported static data members cannot be defined out-of-line.
11385   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11386     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11387         VD->isThisDeclarationADefinition()) {
11388       // We allow definitions of dllimport class template static data members
11389       // with a warning.
11390       CXXRecordDecl *Context =
11391         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11392       bool IsClassTemplateMember =
11393           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11394           Context->getDescribedClassTemplate();
11395 
11396       Diag(VD->getLocation(),
11397            IsClassTemplateMember
11398                ? diag::warn_attribute_dllimport_static_field_definition
11399                : diag::err_attribute_dllimport_static_field_definition);
11400       Diag(IA->getLocation(), diag::note_attribute);
11401       if (!IsClassTemplateMember)
11402         VD->setInvalidDecl();
11403     }
11404   }
11405 
11406   // dllimport/dllexport variables cannot be thread local, their TLS index
11407   // isn't exported with the variable.
11408   if (DLLAttr && VD->getTLSKind()) {
11409     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11410     if (F && getDLLAttr(F)) {
11411       assert(VD->isStaticLocal());
11412       // But if this is a static local in a dlimport/dllexport function, the
11413       // function will never be inlined, which means the var would never be
11414       // imported, so having it marked import/export is safe.
11415     } else {
11416       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11417                                                                     << DLLAttr;
11418       VD->setInvalidDecl();
11419     }
11420   }
11421 
11422   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11423     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11424       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11425       VD->dropAttr<UsedAttr>();
11426     }
11427   }
11428 
11429   const DeclContext *DC = VD->getDeclContext();
11430   // If there's a #pragma GCC visibility in scope, and this isn't a class
11431   // member, set the visibility of this variable.
11432   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11433     AddPushedVisibilityAttribute(VD);
11434 
11435   // FIXME: Warn on unused var template partial specializations.
11436   if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11437     MarkUnusedFileScopedDecl(VD);
11438 
11439   // Now we have parsed the initializer and can update the table of magic
11440   // tag values.
11441   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11442       !VD->getType()->isIntegralOrEnumerationType())
11443     return;
11444 
11445   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11446     const Expr *MagicValueExpr = VD->getInit();
11447     if (!MagicValueExpr) {
11448       continue;
11449     }
11450     llvm::APSInt MagicValueInt;
11451     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11452       Diag(I->getRange().getBegin(),
11453            diag::err_type_tag_for_datatype_not_ice)
11454         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11455       continue;
11456     }
11457     if (MagicValueInt.getActiveBits() > 64) {
11458       Diag(I->getRange().getBegin(),
11459            diag::err_type_tag_for_datatype_too_large)
11460         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11461       continue;
11462     }
11463     uint64_t MagicValue = MagicValueInt.getZExtValue();
11464     RegisterTypeTagForDatatype(I->getArgumentKind(),
11465                                MagicValue,
11466                                I->getMatchingCType(),
11467                                I->getLayoutCompatible(),
11468                                I->getMustBeNull());
11469   }
11470 }
11471 
11472 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11473   auto *VD = dyn_cast<VarDecl>(DD);
11474   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11475 }
11476 
11477 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11478                                                    ArrayRef<Decl *> Group) {
11479   SmallVector<Decl*, 8> Decls;
11480 
11481   if (DS.isTypeSpecOwned())
11482     Decls.push_back(DS.getRepAsDecl());
11483 
11484   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11485   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11486   bool DiagnosedMultipleDecomps = false;
11487   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11488   bool DiagnosedNonDeducedAuto = false;
11489 
11490   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11491     if (Decl *D = Group[i]) {
11492       // For declarators, there are some additional syntactic-ish checks we need
11493       // to perform.
11494       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11495         if (!FirstDeclaratorInGroup)
11496           FirstDeclaratorInGroup = DD;
11497         if (!FirstDecompDeclaratorInGroup)
11498           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11499         if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11500             !hasDeducedAuto(DD))
11501           FirstNonDeducedAutoInGroup = DD;
11502 
11503         if (FirstDeclaratorInGroup != DD) {
11504           // A decomposition declaration cannot be combined with any other
11505           // declaration in the same group.
11506           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11507             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11508                  diag::err_decomp_decl_not_alone)
11509                 << FirstDeclaratorInGroup->getSourceRange()
11510                 << DD->getSourceRange();
11511             DiagnosedMultipleDecomps = true;
11512           }
11513 
11514           // A declarator that uses 'auto' in any way other than to declare a
11515           // variable with a deduced type cannot be combined with any other
11516           // declarator in the same group.
11517           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11518             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11519                  diag::err_auto_non_deduced_not_alone)
11520                 << FirstNonDeducedAutoInGroup->getType()
11521                        ->hasAutoForTrailingReturnType()
11522                 << FirstDeclaratorInGroup->getSourceRange()
11523                 << DD->getSourceRange();
11524             DiagnosedNonDeducedAuto = true;
11525           }
11526         }
11527       }
11528 
11529       Decls.push_back(D);
11530     }
11531   }
11532 
11533   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11534     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11535       handleTagNumbering(Tag, S);
11536       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11537           getLangOpts().CPlusPlus)
11538         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11539     }
11540   }
11541 
11542   return BuildDeclaratorGroup(Decls);
11543 }
11544 
11545 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11546 /// group, performing any necessary semantic checking.
11547 Sema::DeclGroupPtrTy
11548 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11549   // C++14 [dcl.spec.auto]p7: (DR1347)
11550   //   If the type that replaces the placeholder type is not the same in each
11551   //   deduction, the program is ill-formed.
11552   if (Group.size() > 1) {
11553     QualType Deduced;
11554     VarDecl *DeducedDecl = nullptr;
11555     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11556       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11557       if (!D || D->isInvalidDecl())
11558         break;
11559       DeducedType *DT = D->getType()->getContainedDeducedType();
11560       if (!DT || DT->getDeducedType().isNull())
11561         continue;
11562       if (Deduced.isNull()) {
11563         Deduced = DT->getDeducedType();
11564         DeducedDecl = D;
11565       } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11566         auto *AT = dyn_cast<AutoType>(DT);
11567         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11568              diag::err_auto_different_deductions)
11569           << (AT ? (unsigned)AT->getKeyword() : 3)
11570           << Deduced << DeducedDecl->getDeclName()
11571           << DT->getDeducedType() << D->getDeclName()
11572           << DeducedDecl->getInit()->getSourceRange()
11573           << D->getInit()->getSourceRange();
11574         D->setInvalidDecl();
11575         break;
11576       }
11577     }
11578   }
11579 
11580   ActOnDocumentableDecls(Group);
11581 
11582   return DeclGroupPtrTy::make(
11583       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11584 }
11585 
11586 void Sema::ActOnDocumentableDecl(Decl *D) {
11587   ActOnDocumentableDecls(D);
11588 }
11589 
11590 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11591   // Don't parse the comment if Doxygen diagnostics are ignored.
11592   if (Group.empty() || !Group[0])
11593     return;
11594 
11595   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11596                       Group[0]->getLocation()) &&
11597       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11598                       Group[0]->getLocation()))
11599     return;
11600 
11601   if (Group.size() >= 2) {
11602     // This is a decl group.  Normally it will contain only declarations
11603     // produced from declarator list.  But in case we have any definitions or
11604     // additional declaration references:
11605     //   'typedef struct S {} S;'
11606     //   'typedef struct S *S;'
11607     //   'struct S *pS;'
11608     // FinalizeDeclaratorGroup adds these as separate declarations.
11609     Decl *MaybeTagDecl = Group[0];
11610     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11611       Group = Group.slice(1);
11612     }
11613   }
11614 
11615   // See if there are any new comments that are not attached to a decl.
11616   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11617   if (!Comments.empty() &&
11618       !Comments.back()->isAttached()) {
11619     // There is at least one comment that not attached to a decl.
11620     // Maybe it should be attached to one of these decls?
11621     //
11622     // Note that this way we pick up not only comments that precede the
11623     // declaration, but also comments that *follow* the declaration -- thanks to
11624     // the lookahead in the lexer: we've consumed the semicolon and looked
11625     // ahead through comments.
11626     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11627       Context.getCommentForDecl(Group[i], &PP);
11628   }
11629 }
11630 
11631 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11632 /// to introduce parameters into function prototype scope.
11633 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11634   const DeclSpec &DS = D.getDeclSpec();
11635 
11636   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11637 
11638   // C++03 [dcl.stc]p2 also permits 'auto'.
11639   StorageClass SC = SC_None;
11640   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11641     SC = SC_Register;
11642   } else if (getLangOpts().CPlusPlus &&
11643              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11644     SC = SC_Auto;
11645   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11646     Diag(DS.getStorageClassSpecLoc(),
11647          diag::err_invalid_storage_class_in_func_decl);
11648     D.getMutableDeclSpec().ClearStorageClassSpecs();
11649   }
11650 
11651   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11652     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11653       << DeclSpec::getSpecifierName(TSCS);
11654   if (DS.isInlineSpecified())
11655     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11656         << getLangOpts().CPlusPlus1z;
11657   if (DS.isConstexprSpecified())
11658     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11659       << 0;
11660   if (DS.isConceptSpecified())
11661     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11662 
11663   DiagnoseFunctionSpecifiers(DS);
11664 
11665   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11666   QualType parmDeclType = TInfo->getType();
11667 
11668   if (getLangOpts().CPlusPlus) {
11669     // Check that there are no default arguments inside the type of this
11670     // parameter.
11671     CheckExtraCXXDefaultArguments(D);
11672 
11673     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11674     if (D.getCXXScopeSpec().isSet()) {
11675       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11676         << D.getCXXScopeSpec().getRange();
11677       D.getCXXScopeSpec().clear();
11678     }
11679   }
11680 
11681   // Ensure we have a valid name
11682   IdentifierInfo *II = nullptr;
11683   if (D.hasName()) {
11684     II = D.getIdentifier();
11685     if (!II) {
11686       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11687         << GetNameForDeclarator(D).getName();
11688       D.setInvalidType(true);
11689     }
11690   }
11691 
11692   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11693   if (II) {
11694     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11695                    ForRedeclaration);
11696     LookupName(R, S);
11697     if (R.isSingleResult()) {
11698       NamedDecl *PrevDecl = R.getFoundDecl();
11699       if (PrevDecl->isTemplateParameter()) {
11700         // Maybe we will complain about the shadowed template parameter.
11701         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11702         // Just pretend that we didn't see the previous declaration.
11703         PrevDecl = nullptr;
11704       } else if (S->isDeclScope(PrevDecl)) {
11705         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11706         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11707 
11708         // Recover by removing the name
11709         II = nullptr;
11710         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11711         D.setInvalidType(true);
11712       }
11713     }
11714   }
11715 
11716   // Temporarily put parameter variables in the translation unit, not
11717   // the enclosing context.  This prevents them from accidentally
11718   // looking like class members in C++.
11719   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11720                                     D.getLocStart(),
11721                                     D.getIdentifierLoc(), II,
11722                                     parmDeclType, TInfo,
11723                                     SC);
11724 
11725   if (D.isInvalidType())
11726     New->setInvalidDecl();
11727 
11728   assert(S->isFunctionPrototypeScope());
11729   assert(S->getFunctionPrototypeDepth() >= 1);
11730   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11731                     S->getNextFunctionPrototypeIndex());
11732 
11733   // Add the parameter declaration into this scope.
11734   S->AddDecl(New);
11735   if (II)
11736     IdResolver.AddDecl(New);
11737 
11738   ProcessDeclAttributes(S, New, D);
11739 
11740   if (D.getDeclSpec().isModulePrivateSpecified())
11741     Diag(New->getLocation(), diag::err_module_private_local)
11742       << 1 << New->getDeclName()
11743       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11744       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11745 
11746   if (New->hasAttr<BlocksAttr>()) {
11747     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11748   }
11749   return New;
11750 }
11751 
11752 /// \brief Synthesizes a variable for a parameter arising from a
11753 /// typedef.
11754 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11755                                               SourceLocation Loc,
11756                                               QualType T) {
11757   /* FIXME: setting StartLoc == Loc.
11758      Would it be worth to modify callers so as to provide proper source
11759      location for the unnamed parameters, embedding the parameter's type? */
11760   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11761                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11762                                            SC_None, nullptr);
11763   Param->setImplicit();
11764   return Param;
11765 }
11766 
11767 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11768   // Don't diagnose unused-parameter errors in template instantiations; we
11769   // will already have done so in the template itself.
11770   if (inTemplateInstantiation())
11771     return;
11772 
11773   for (const ParmVarDecl *Parameter : Parameters) {
11774     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11775         !Parameter->hasAttr<UnusedAttr>()) {
11776       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11777         << Parameter->getDeclName();
11778     }
11779   }
11780 }
11781 
11782 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11783     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11784   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11785     return;
11786 
11787   // Warn if the return value is pass-by-value and larger than the specified
11788   // threshold.
11789   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11790     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11791     if (Size > LangOpts.NumLargeByValueCopy)
11792       Diag(D->getLocation(), diag::warn_return_value_size)
11793           << D->getDeclName() << Size;
11794   }
11795 
11796   // Warn if any parameter is pass-by-value and larger than the specified
11797   // threshold.
11798   for (const ParmVarDecl *Parameter : Parameters) {
11799     QualType T = Parameter->getType();
11800     if (T->isDependentType() || !T.isPODType(Context))
11801       continue;
11802     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11803     if (Size > LangOpts.NumLargeByValueCopy)
11804       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11805           << Parameter->getDeclName() << Size;
11806   }
11807 }
11808 
11809 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11810                                   SourceLocation NameLoc, IdentifierInfo *Name,
11811                                   QualType T, TypeSourceInfo *TSInfo,
11812                                   StorageClass SC) {
11813   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11814   if (getLangOpts().ObjCAutoRefCount &&
11815       T.getObjCLifetime() == Qualifiers::OCL_None &&
11816       T->isObjCLifetimeType()) {
11817 
11818     Qualifiers::ObjCLifetime lifetime;
11819 
11820     // Special cases for arrays:
11821     //   - if it's const, use __unsafe_unretained
11822     //   - otherwise, it's an error
11823     if (T->isArrayType()) {
11824       if (!T.isConstQualified()) {
11825         DelayedDiagnostics.add(
11826             sema::DelayedDiagnostic::makeForbiddenType(
11827             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11828       }
11829       lifetime = Qualifiers::OCL_ExplicitNone;
11830     } else {
11831       lifetime = T->getObjCARCImplicitLifetime();
11832     }
11833     T = Context.getLifetimeQualifiedType(T, lifetime);
11834   }
11835 
11836   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11837                                          Context.getAdjustedParameterType(T),
11838                                          TSInfo, SC, nullptr);
11839 
11840   // Parameters can not be abstract class types.
11841   // For record types, this is done by the AbstractClassUsageDiagnoser once
11842   // the class has been completely parsed.
11843   if (!CurContext->isRecord() &&
11844       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11845                              AbstractParamType))
11846     New->setInvalidDecl();
11847 
11848   // Parameter declarators cannot be interface types. All ObjC objects are
11849   // passed by reference.
11850   if (T->isObjCObjectType()) {
11851     SourceLocation TypeEndLoc =
11852         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11853     Diag(NameLoc,
11854          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11855       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11856     T = Context.getObjCObjectPointerType(T);
11857     New->setType(T);
11858   }
11859 
11860   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11861   // duration shall not be qualified by an address-space qualifier."
11862   // Since all parameters have automatic store duration, they can not have
11863   // an address space.
11864   if (T.getAddressSpace() != 0) {
11865     // OpenCL allows function arguments declared to be an array of a type
11866     // to be qualified with an address space.
11867     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11868       Diag(NameLoc, diag::err_arg_with_address_space);
11869       New->setInvalidDecl();
11870     }
11871   }
11872 
11873   return New;
11874 }
11875 
11876 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11877                                            SourceLocation LocAfterDecls) {
11878   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11879 
11880   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11881   // for a K&R function.
11882   if (!FTI.hasPrototype) {
11883     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11884       --i;
11885       if (FTI.Params[i].Param == nullptr) {
11886         SmallString<256> Code;
11887         llvm::raw_svector_ostream(Code)
11888             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11889         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11890             << FTI.Params[i].Ident
11891             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11892 
11893         // Implicitly declare the argument as type 'int' for lack of a better
11894         // type.
11895         AttributeFactory attrs;
11896         DeclSpec DS(attrs);
11897         const char* PrevSpec; // unused
11898         unsigned DiagID; // unused
11899         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11900                            DiagID, Context.getPrintingPolicy());
11901         // Use the identifier location for the type source range.
11902         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11903         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11904         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11905         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11906         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11907       }
11908     }
11909   }
11910 }
11911 
11912 Decl *
11913 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11914                               MultiTemplateParamsArg TemplateParameterLists,
11915                               SkipBodyInfo *SkipBody) {
11916   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11917   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11918   Scope *ParentScope = FnBodyScope->getParent();
11919 
11920   D.setFunctionDefinitionKind(FDK_Definition);
11921   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11922   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11923 }
11924 
11925 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11926   Consumer.HandleInlineFunctionDefinition(D);
11927 }
11928 
11929 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11930                              const FunctionDecl*& PossibleZeroParamPrototype) {
11931   // Don't warn about invalid declarations.
11932   if (FD->isInvalidDecl())
11933     return false;
11934 
11935   // Or declarations that aren't global.
11936   if (!FD->isGlobal())
11937     return false;
11938 
11939   // Don't warn about C++ member functions.
11940   if (isa<CXXMethodDecl>(FD))
11941     return false;
11942 
11943   // Don't warn about 'main'.
11944   if (FD->isMain())
11945     return false;
11946 
11947   // Don't warn about inline functions.
11948   if (FD->isInlined())
11949     return false;
11950 
11951   // Don't warn about function templates.
11952   if (FD->getDescribedFunctionTemplate())
11953     return false;
11954 
11955   // Don't warn about function template specializations.
11956   if (FD->isFunctionTemplateSpecialization())
11957     return false;
11958 
11959   // Don't warn for OpenCL kernels.
11960   if (FD->hasAttr<OpenCLKernelAttr>())
11961     return false;
11962 
11963   // Don't warn on explicitly deleted functions.
11964   if (FD->isDeleted())
11965     return false;
11966 
11967   bool MissingPrototype = true;
11968   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11969        Prev; Prev = Prev->getPreviousDecl()) {
11970     // Ignore any declarations that occur in function or method
11971     // scope, because they aren't visible from the header.
11972     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11973       continue;
11974 
11975     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11976     if (FD->getNumParams() == 0)
11977       PossibleZeroParamPrototype = Prev;
11978     break;
11979   }
11980 
11981   return MissingPrototype;
11982 }
11983 
11984 void
11985 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11986                                    const FunctionDecl *EffectiveDefinition,
11987                                    SkipBodyInfo *SkipBody) {
11988   const FunctionDecl *Definition = EffectiveDefinition;
11989   if (!Definition)
11990     if (!FD->isDefined(Definition))
11991       return;
11992 
11993   if (canRedefineFunction(Definition, getLangOpts()))
11994     return;
11995 
11996   // Don't emit an error when this is redefinition of a typo-corrected
11997   // definition.
11998   if (TypoCorrectedFunctionDefinitions.count(Definition))
11999     return;
12000 
12001   // If we don't have a visible definition of the function, and it's inline or
12002   // a template, skip the new definition.
12003   if (SkipBody && !hasVisibleDefinition(Definition) &&
12004       (Definition->getFormalLinkage() == InternalLinkage ||
12005        Definition->isInlined() ||
12006        Definition->getDescribedFunctionTemplate() ||
12007        Definition->getNumTemplateParameterLists())) {
12008     SkipBody->ShouldSkip = true;
12009     if (auto *TD = Definition->getDescribedFunctionTemplate())
12010       makeMergedDefinitionVisible(TD);
12011     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12012     return;
12013   }
12014 
12015   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12016       Definition->getStorageClass() == SC_Extern)
12017     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12018         << FD->getDeclName() << getLangOpts().CPlusPlus;
12019   else
12020     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12021 
12022   Diag(Definition->getLocation(), diag::note_previous_definition);
12023   FD->setInvalidDecl();
12024 }
12025 
12026 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12027                                    Sema &S) {
12028   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12029 
12030   LambdaScopeInfo *LSI = S.PushLambdaScope();
12031   LSI->CallOperator = CallOperator;
12032   LSI->Lambda = LambdaClass;
12033   LSI->ReturnType = CallOperator->getReturnType();
12034   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12035 
12036   if (LCD == LCD_None)
12037     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12038   else if (LCD == LCD_ByCopy)
12039     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12040   else if (LCD == LCD_ByRef)
12041     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12042   DeclarationNameInfo DNI = CallOperator->getNameInfo();
12043 
12044   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12045   LSI->Mutable = !CallOperator->isConst();
12046 
12047   // Add the captures to the LSI so they can be noted as already
12048   // captured within tryCaptureVar.
12049   auto I = LambdaClass->field_begin();
12050   for (const auto &C : LambdaClass->captures()) {
12051     if (C.capturesVariable()) {
12052       VarDecl *VD = C.getCapturedVar();
12053       if (VD->isInitCapture())
12054         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12055       QualType CaptureType = VD->getType();
12056       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12057       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12058           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12059           /*EllipsisLoc*/C.isPackExpansion()
12060                          ? C.getEllipsisLoc() : SourceLocation(),
12061           CaptureType, /*Expr*/ nullptr);
12062 
12063     } else if (C.capturesThis()) {
12064       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12065                               /*Expr*/ nullptr,
12066                               C.getCaptureKind() == LCK_StarThis);
12067     } else {
12068       LSI->addVLATypeCapture(C.getLocation(), I->getType());
12069     }
12070     ++I;
12071   }
12072 }
12073 
12074 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12075                                     SkipBodyInfo *SkipBody) {
12076   if (!D)
12077     return D;
12078   FunctionDecl *FD = nullptr;
12079 
12080   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12081     FD = FunTmpl->getTemplatedDecl();
12082   else
12083     FD = cast<FunctionDecl>(D);
12084 
12085   // Check for defining attributes before the check for redefinition.
12086   if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12087     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12088     FD->dropAttr<AliasAttr>();
12089     FD->setInvalidDecl();
12090   }
12091   if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12092     Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12093     FD->dropAttr<IFuncAttr>();
12094     FD->setInvalidDecl();
12095   }
12096 
12097   // See if this is a redefinition. If 'will have body' is already set, then
12098   // these checks were already performed when it was set.
12099   if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12100     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12101 
12102     // If we're skipping the body, we're done. Don't enter the scope.
12103     if (SkipBody && SkipBody->ShouldSkip)
12104       return D;
12105   }
12106 
12107   // Mark this function as "will have a body eventually".  This lets users to
12108   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12109   // this function.
12110   FD->setWillHaveBody();
12111 
12112   // If we are instantiating a generic lambda call operator, push
12113   // a LambdaScopeInfo onto the function stack.  But use the information
12114   // that's already been calculated (ActOnLambdaExpr) to prime the current
12115   // LambdaScopeInfo.
12116   // When the template operator is being specialized, the LambdaScopeInfo,
12117   // has to be properly restored so that tryCaptureVariable doesn't try
12118   // and capture any new variables. In addition when calculating potential
12119   // captures during transformation of nested lambdas, it is necessary to
12120   // have the LSI properly restored.
12121   if (isGenericLambdaCallOperatorSpecialization(FD)) {
12122     assert(inTemplateInstantiation() &&
12123            "There should be an active template instantiation on the stack "
12124            "when instantiating a generic lambda!");
12125     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12126   } else {
12127     // Enter a new function scope
12128     PushFunctionScope();
12129   }
12130 
12131   // Builtin functions cannot be defined.
12132   if (unsigned BuiltinID = FD->getBuiltinID()) {
12133     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12134         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12135       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12136       FD->setInvalidDecl();
12137     }
12138   }
12139 
12140   // The return type of a function definition must be complete
12141   // (C99 6.9.1p3, C++ [dcl.fct]p6).
12142   QualType ResultType = FD->getReturnType();
12143   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12144       !FD->isInvalidDecl() &&
12145       RequireCompleteType(FD->getLocation(), ResultType,
12146                           diag::err_func_def_incomplete_result))
12147     FD->setInvalidDecl();
12148 
12149   if (FnBodyScope)
12150     PushDeclContext(FnBodyScope, FD);
12151 
12152   // Check the validity of our function parameters
12153   CheckParmsForFunctionDef(FD->parameters(),
12154                            /*CheckParameterNames=*/true);
12155 
12156   // Add non-parameter declarations already in the function to the current
12157   // scope.
12158   if (FnBodyScope) {
12159     for (Decl *NPD : FD->decls()) {
12160       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12161       if (!NonParmDecl)
12162         continue;
12163       assert(!isa<ParmVarDecl>(NonParmDecl) &&
12164              "parameters should not be in newly created FD yet");
12165 
12166       // If the decl has a name, make it accessible in the current scope.
12167       if (NonParmDecl->getDeclName())
12168         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12169 
12170       // Similarly, dive into enums and fish their constants out, making them
12171       // accessible in this scope.
12172       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12173         for (auto *EI : ED->enumerators())
12174           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12175       }
12176     }
12177   }
12178 
12179   // Introduce our parameters into the function scope
12180   for (auto Param : FD->parameters()) {
12181     Param->setOwningFunction(FD);
12182 
12183     // If this has an identifier, add it to the scope stack.
12184     if (Param->getIdentifier() && FnBodyScope) {
12185       CheckShadow(FnBodyScope, Param);
12186 
12187       PushOnScopeChains(Param, FnBodyScope);
12188     }
12189   }
12190 
12191   // Ensure that the function's exception specification is instantiated.
12192   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12193     ResolveExceptionSpec(D->getLocation(), FPT);
12194 
12195   // dllimport cannot be applied to non-inline function definitions.
12196   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12197       !FD->isTemplateInstantiation()) {
12198     assert(!FD->hasAttr<DLLExportAttr>());
12199     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12200     FD->setInvalidDecl();
12201     return D;
12202   }
12203   // We want to attach documentation to original Decl (which might be
12204   // a function template).
12205   ActOnDocumentableDecl(D);
12206   if (getCurLexicalContext()->isObjCContainer() &&
12207       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12208       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12209     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12210 
12211   return D;
12212 }
12213 
12214 /// \brief Given the set of return statements within a function body,
12215 /// compute the variables that are subject to the named return value
12216 /// optimization.
12217 ///
12218 /// Each of the variables that is subject to the named return value
12219 /// optimization will be marked as NRVO variables in the AST, and any
12220 /// return statement that has a marked NRVO variable as its NRVO candidate can
12221 /// use the named return value optimization.
12222 ///
12223 /// This function applies a very simplistic algorithm for NRVO: if every return
12224 /// statement in the scope of a variable has the same NRVO candidate, that
12225 /// candidate is an NRVO variable.
12226 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12227   ReturnStmt **Returns = Scope->Returns.data();
12228 
12229   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12230     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12231       if (!NRVOCandidate->isNRVOVariable())
12232         Returns[I]->setNRVOCandidate(nullptr);
12233     }
12234   }
12235 }
12236 
12237 bool Sema::canDelayFunctionBody(const Declarator &D) {
12238   // We can't delay parsing the body of a constexpr function template (yet).
12239   if (D.getDeclSpec().isConstexprSpecified())
12240     return false;
12241 
12242   // We can't delay parsing the body of a function template with a deduced
12243   // return type (yet).
12244   if (D.getDeclSpec().hasAutoTypeSpec()) {
12245     // If the placeholder introduces a non-deduced trailing return type,
12246     // we can still delay parsing it.
12247     if (D.getNumTypeObjects()) {
12248       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12249       if (Outer.Kind == DeclaratorChunk::Function &&
12250           Outer.Fun.hasTrailingReturnType()) {
12251         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12252         return Ty.isNull() || !Ty->isUndeducedType();
12253       }
12254     }
12255     return false;
12256   }
12257 
12258   return true;
12259 }
12260 
12261 bool Sema::canSkipFunctionBody(Decl *D) {
12262   // We cannot skip the body of a function (or function template) which is
12263   // constexpr, since we may need to evaluate its body in order to parse the
12264   // rest of the file.
12265   // We cannot skip the body of a function with an undeduced return type,
12266   // because any callers of that function need to know the type.
12267   if (const FunctionDecl *FD = D->getAsFunction())
12268     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12269       return false;
12270   return Consumer.shouldSkipFunctionBody(D);
12271 }
12272 
12273 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12274   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
12275     FD->setHasSkippedBody();
12276   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
12277     MD->setHasSkippedBody();
12278   return Decl;
12279 }
12280 
12281 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12282   return ActOnFinishFunctionBody(D, BodyArg, false);
12283 }
12284 
12285 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12286                                     bool IsInstantiation) {
12287   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12288 
12289   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12290   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12291 
12292   if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12293     CheckCompletedCoroutineBody(FD, Body);
12294 
12295   if (FD) {
12296     FD->setBody(Body);
12297     FD->setWillHaveBody(false);
12298 
12299     if (getLangOpts().CPlusPlus14) {
12300       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12301           FD->getReturnType()->isUndeducedType()) {
12302         // If the function has a deduced result type but contains no 'return'
12303         // statements, the result type as written must be exactly 'auto', and
12304         // the deduced result type is 'void'.
12305         if (!FD->getReturnType()->getAs<AutoType>()) {
12306           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12307               << FD->getReturnType();
12308           FD->setInvalidDecl();
12309         } else {
12310           // Substitute 'void' for the 'auto' in the type.
12311           TypeLoc ResultType = getReturnTypeLoc(FD);
12312           Context.adjustDeducedFunctionResultType(
12313               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12314         }
12315       }
12316     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12317       // In C++11, we don't use 'auto' deduction rules for lambda call
12318       // operators because we don't support return type deduction.
12319       auto *LSI = getCurLambda();
12320       if (LSI->HasImplicitReturnType) {
12321         deduceClosureReturnType(*LSI);
12322 
12323         // C++11 [expr.prim.lambda]p4:
12324         //   [...] if there are no return statements in the compound-statement
12325         //   [the deduced type is] the type void
12326         QualType RetType =
12327             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12328 
12329         // Update the return type to the deduced type.
12330         const FunctionProtoType *Proto =
12331             FD->getType()->getAs<FunctionProtoType>();
12332         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12333                                             Proto->getExtProtoInfo()));
12334       }
12335     }
12336 
12337     // If the function implicitly returns zero (like 'main') or is naked,
12338     // don't complain about missing return statements.
12339     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12340       WP.disableCheckFallThrough();
12341 
12342     // MSVC permits the use of pure specifier (=0) on function definition,
12343     // defined at class scope, warn about this non-standard construct.
12344     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12345       Diag(FD->getLocation(), diag::ext_pure_function_definition);
12346 
12347     if (!FD->isInvalidDecl()) {
12348       // Don't diagnose unused parameters of defaulted or deleted functions.
12349       if (!FD->isDeleted() && !FD->isDefaulted())
12350         DiagnoseUnusedParameters(FD->parameters());
12351       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12352                                              FD->getReturnType(), FD);
12353 
12354       // If this is a structor, we need a vtable.
12355       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12356         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12357       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12358         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12359 
12360       // Try to apply the named return value optimization. We have to check
12361       // if we can do this here because lambdas keep return statements around
12362       // to deduce an implicit return type.
12363       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
12364           !FD->isDependentContext())
12365         computeNRVO(Body, getCurFunction());
12366     }
12367 
12368     // GNU warning -Wmissing-prototypes:
12369     //   Warn if a global function is defined without a previous
12370     //   prototype declaration. This warning is issued even if the
12371     //   definition itself provides a prototype. The aim is to detect
12372     //   global functions that fail to be declared in header files.
12373     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12374     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12375       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12376 
12377       if (PossibleZeroParamPrototype) {
12378         // We found a declaration that is not a prototype,
12379         // but that could be a zero-parameter prototype
12380         if (TypeSourceInfo *TI =
12381                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12382           TypeLoc TL = TI->getTypeLoc();
12383           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12384             Diag(PossibleZeroParamPrototype->getLocation(),
12385                  diag::note_declaration_not_a_prototype)
12386                 << PossibleZeroParamPrototype
12387                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12388         }
12389       }
12390 
12391       // GNU warning -Wstrict-prototypes
12392       //   Warn if K&R function is defined without a previous declaration.
12393       //   This warning is issued only if the definition itself does not provide
12394       //   a prototype. Only K&R definitions do not provide a prototype.
12395       //   An empty list in a function declarator that is part of a definition
12396       //   of that function specifies that the function has no parameters
12397       //   (C99 6.7.5.3p14)
12398       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12399           !LangOpts.CPlusPlus) {
12400         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12401         TypeLoc TL = TI->getTypeLoc();
12402         FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12403         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12404       }
12405     }
12406 
12407     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12408       const CXXMethodDecl *KeyFunction;
12409       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12410           MD->isVirtual() &&
12411           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12412           MD == KeyFunction->getCanonicalDecl()) {
12413         // Update the key-function state if necessary for this ABI.
12414         if (FD->isInlined() &&
12415             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12416           Context.setNonKeyFunction(MD);
12417 
12418           // If the newly-chosen key function is already defined, then we
12419           // need to mark the vtable as used retroactively.
12420           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12421           const FunctionDecl *Definition;
12422           if (KeyFunction && KeyFunction->isDefined(Definition))
12423             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12424         } else {
12425           // We just defined they key function; mark the vtable as used.
12426           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12427         }
12428       }
12429     }
12430 
12431     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12432            "Function parsing confused");
12433   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12434     assert(MD == getCurMethodDecl() && "Method parsing confused");
12435     MD->setBody(Body);
12436     if (!MD->isInvalidDecl()) {
12437       DiagnoseUnusedParameters(MD->parameters());
12438       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12439                                              MD->getReturnType(), MD);
12440 
12441       if (Body)
12442         computeNRVO(Body, getCurFunction());
12443     }
12444     if (getCurFunction()->ObjCShouldCallSuper) {
12445       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12446         << MD->getSelector().getAsString();
12447       getCurFunction()->ObjCShouldCallSuper = false;
12448     }
12449     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12450       const ObjCMethodDecl *InitMethod = nullptr;
12451       bool isDesignated =
12452           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12453       assert(isDesignated && InitMethod);
12454       (void)isDesignated;
12455 
12456       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12457         auto IFace = MD->getClassInterface();
12458         if (!IFace)
12459           return false;
12460         auto SuperD = IFace->getSuperClass();
12461         if (!SuperD)
12462           return false;
12463         return SuperD->getIdentifier() ==
12464             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12465       };
12466       // Don't issue this warning for unavailable inits or direct subclasses
12467       // of NSObject.
12468       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12469         Diag(MD->getLocation(),
12470              diag::warn_objc_designated_init_missing_super_call);
12471         Diag(InitMethod->getLocation(),
12472              diag::note_objc_designated_init_marked_here);
12473       }
12474       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12475     }
12476     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12477       // Don't issue this warning for unavaialable inits.
12478       if (!MD->isUnavailable())
12479         Diag(MD->getLocation(),
12480              diag::warn_objc_secondary_init_missing_init_call);
12481       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12482     }
12483   } else {
12484     return nullptr;
12485   }
12486 
12487   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12488     DiagnoseUnguardedAvailabilityViolations(dcl);
12489 
12490   assert(!getCurFunction()->ObjCShouldCallSuper &&
12491          "This should only be set for ObjC methods, which should have been "
12492          "handled in the block above.");
12493 
12494   // Verify and clean out per-function state.
12495   if (Body && (!FD || !FD->isDefaulted())) {
12496     // C++ constructors that have function-try-blocks can't have return
12497     // statements in the handlers of that block. (C++ [except.handle]p14)
12498     // Verify this.
12499     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12500       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12501 
12502     // Verify that gotos and switch cases don't jump into scopes illegally.
12503     if (getCurFunction()->NeedsScopeChecking() &&
12504         !PP.isCodeCompletionEnabled())
12505       DiagnoseInvalidJumps(Body);
12506 
12507     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12508       if (!Destructor->getParent()->isDependentType())
12509         CheckDestructor(Destructor);
12510 
12511       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12512                                              Destructor->getParent());
12513     }
12514 
12515     // If any errors have occurred, clear out any temporaries that may have
12516     // been leftover. This ensures that these temporaries won't be picked up for
12517     // deletion in some later function.
12518     if (getDiagnostics().hasErrorOccurred() ||
12519         getDiagnostics().getSuppressAllDiagnostics()) {
12520       DiscardCleanupsInEvaluationContext();
12521     }
12522     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12523         !isa<FunctionTemplateDecl>(dcl)) {
12524       // Since the body is valid, issue any analysis-based warnings that are
12525       // enabled.
12526       ActivePolicy = &WP;
12527     }
12528 
12529     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12530         (!CheckConstexprFunctionDecl(FD) ||
12531          !CheckConstexprFunctionBody(FD, Body)))
12532       FD->setInvalidDecl();
12533 
12534     if (FD && FD->hasAttr<NakedAttr>()) {
12535       for (const Stmt *S : Body->children()) {
12536         // Allow local register variables without initializer as they don't
12537         // require prologue.
12538         bool RegisterVariables = false;
12539         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12540           for (const auto *Decl : DS->decls()) {
12541             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12542               RegisterVariables =
12543                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12544               if (!RegisterVariables)
12545                 break;
12546             }
12547           }
12548         }
12549         if (RegisterVariables)
12550           continue;
12551         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12552           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12553           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12554           FD->setInvalidDecl();
12555           break;
12556         }
12557       }
12558     }
12559 
12560     assert(ExprCleanupObjects.size() ==
12561                ExprEvalContexts.back().NumCleanupObjects &&
12562            "Leftover temporaries in function");
12563     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12564     assert(MaybeODRUseExprs.empty() &&
12565            "Leftover expressions for odr-use checking");
12566   }
12567 
12568   if (!IsInstantiation)
12569     PopDeclContext();
12570 
12571   PopFunctionScopeInfo(ActivePolicy, dcl);
12572   // If any errors have occurred, clear out any temporaries that may have
12573   // been leftover. This ensures that these temporaries won't be picked up for
12574   // deletion in some later function.
12575   if (getDiagnostics().hasErrorOccurred()) {
12576     DiscardCleanupsInEvaluationContext();
12577   }
12578 
12579   return dcl;
12580 }
12581 
12582 /// When we finish delayed parsing of an attribute, we must attach it to the
12583 /// relevant Decl.
12584 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12585                                        ParsedAttributes &Attrs) {
12586   // Always attach attributes to the underlying decl.
12587   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12588     D = TD->getTemplatedDecl();
12589   ProcessDeclAttributeList(S, D, Attrs.getList());
12590 
12591   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12592     if (Method->isStatic())
12593       checkThisInStaticMemberFunctionAttributes(Method);
12594 }
12595 
12596 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12597 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12598 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12599                                           IdentifierInfo &II, Scope *S) {
12600   // Before we produce a declaration for an implicitly defined
12601   // function, see whether there was a locally-scoped declaration of
12602   // this name as a function or variable. If so, use that
12603   // (non-visible) declaration, and complain about it.
12604   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12605     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12606     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12607     return ExternCPrev;
12608   }
12609 
12610   // Extension in C99.  Legal in C90, but warn about it.
12611   unsigned diag_id;
12612   if (II.getName().startswith("__builtin_"))
12613     diag_id = diag::warn_builtin_unknown;
12614   // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12615   else if (getLangOpts().OpenCL)
12616     diag_id = diag::err_opencl_implicit_function_decl;
12617   else if (getLangOpts().C99)
12618     diag_id = diag::ext_implicit_function_decl;
12619   else
12620     diag_id = diag::warn_implicit_function_decl;
12621   Diag(Loc, diag_id) << &II;
12622 
12623   // Because typo correction is expensive, only do it if the implicit
12624   // function declaration is going to be treated as an error.
12625   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12626     TypoCorrection Corrected;
12627     if (S &&
12628         (Corrected = CorrectTypo(
12629              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12630              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12631       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12632                    /*ErrorRecovery*/false);
12633   }
12634 
12635   // Set a Declarator for the implicit definition: int foo();
12636   const char *Dummy;
12637   AttributeFactory attrFactory;
12638   DeclSpec DS(attrFactory);
12639   unsigned DiagID;
12640   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12641                                   Context.getPrintingPolicy());
12642   (void)Error; // Silence warning.
12643   assert(!Error && "Error setting up implicit decl!");
12644   SourceLocation NoLoc;
12645   Declarator D(DS, Declarator::BlockContext);
12646   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12647                                              /*IsAmbiguous=*/false,
12648                                              /*LParenLoc=*/NoLoc,
12649                                              /*Params=*/nullptr,
12650                                              /*NumParams=*/0,
12651                                              /*EllipsisLoc=*/NoLoc,
12652                                              /*RParenLoc=*/NoLoc,
12653                                              /*TypeQuals=*/0,
12654                                              /*RefQualifierIsLvalueRef=*/true,
12655                                              /*RefQualifierLoc=*/NoLoc,
12656                                              /*ConstQualifierLoc=*/NoLoc,
12657                                              /*VolatileQualifierLoc=*/NoLoc,
12658                                              /*RestrictQualifierLoc=*/NoLoc,
12659                                              /*MutableLoc=*/NoLoc,
12660                                              EST_None,
12661                                              /*ESpecRange=*/SourceRange(),
12662                                              /*Exceptions=*/nullptr,
12663                                              /*ExceptionRanges=*/nullptr,
12664                                              /*NumExceptions=*/0,
12665                                              /*NoexceptExpr=*/nullptr,
12666                                              /*ExceptionSpecTokens=*/nullptr,
12667                                              /*DeclsInPrototype=*/None,
12668                                              Loc, Loc, D),
12669                 DS.getAttributes(),
12670                 SourceLocation());
12671   D.SetIdentifier(&II, Loc);
12672 
12673   // Insert this function into the enclosing block scope.
12674   while (S && !S->isCompoundStmtScope())
12675     S = S->getParent();
12676   if (S == nullptr)
12677     S = TUScope;
12678 
12679   DeclContext *PrevDC = CurContext;
12680   CurContext = Context.getTranslationUnitDecl();
12681 
12682   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(S, D));
12683   FD->setImplicit();
12684 
12685   CurContext = PrevDC;
12686 
12687   AddKnownFunctionAttributes(FD);
12688 
12689   return FD;
12690 }
12691 
12692 /// \brief Adds any function attributes that we know a priori based on
12693 /// the declaration of this function.
12694 ///
12695 /// These attributes can apply both to implicitly-declared builtins
12696 /// (like __builtin___printf_chk) or to library-declared functions
12697 /// like NSLog or printf.
12698 ///
12699 /// We need to check for duplicate attributes both here and where user-written
12700 /// attributes are applied to declarations.
12701 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12702   if (FD->isInvalidDecl())
12703     return;
12704 
12705   // If this is a built-in function, map its builtin attributes to
12706   // actual attributes.
12707   if (unsigned BuiltinID = FD->getBuiltinID()) {
12708     // Handle printf-formatting attributes.
12709     unsigned FormatIdx;
12710     bool HasVAListArg;
12711     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12712       if (!FD->hasAttr<FormatAttr>()) {
12713         const char *fmt = "printf";
12714         unsigned int NumParams = FD->getNumParams();
12715         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12716             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12717           fmt = "NSString";
12718         FD->addAttr(FormatAttr::CreateImplicit(Context,
12719                                                &Context.Idents.get(fmt),
12720                                                FormatIdx+1,
12721                                                HasVAListArg ? 0 : FormatIdx+2,
12722                                                FD->getLocation()));
12723       }
12724     }
12725     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12726                                              HasVAListArg)) {
12727      if (!FD->hasAttr<FormatAttr>())
12728        FD->addAttr(FormatAttr::CreateImplicit(Context,
12729                                               &Context.Idents.get("scanf"),
12730                                               FormatIdx+1,
12731                                               HasVAListArg ? 0 : FormatIdx+2,
12732                                               FD->getLocation()));
12733     }
12734 
12735     // Mark const if we don't care about errno and that is the only
12736     // thing preventing the function from being const. This allows
12737     // IRgen to use LLVM intrinsics for such functions.
12738     if (!getLangOpts().MathErrno &&
12739         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12740       if (!FD->hasAttr<ConstAttr>())
12741         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12742     }
12743 
12744     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12745         !FD->hasAttr<ReturnsTwiceAttr>())
12746       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12747                                          FD->getLocation()));
12748     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12749       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12750     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12751       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12752     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12753       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12754     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12755         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12756       // Add the appropriate attribute, depending on the CUDA compilation mode
12757       // and which target the builtin belongs to. For example, during host
12758       // compilation, aux builtins are __device__, while the rest are __host__.
12759       if (getLangOpts().CUDAIsDevice !=
12760           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12761         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12762       else
12763         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12764     }
12765   }
12766 
12767   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12768   // throw, add an implicit nothrow attribute to any extern "C" function we come
12769   // across.
12770   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12771       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12772     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12773     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12774       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12775   }
12776 
12777   IdentifierInfo *Name = FD->getIdentifier();
12778   if (!Name)
12779     return;
12780   if ((!getLangOpts().CPlusPlus &&
12781        FD->getDeclContext()->isTranslationUnit()) ||
12782       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12783        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12784        LinkageSpecDecl::lang_c)) {
12785     // Okay: this could be a libc/libm/Objective-C function we know
12786     // about.
12787   } else
12788     return;
12789 
12790   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12791     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12792     // target-specific builtins, perhaps?
12793     if (!FD->hasAttr<FormatAttr>())
12794       FD->addAttr(FormatAttr::CreateImplicit(Context,
12795                                              &Context.Idents.get("printf"), 2,
12796                                              Name->isStr("vasprintf") ? 0 : 3,
12797                                              FD->getLocation()));
12798   }
12799 
12800   if (Name->isStr("__CFStringMakeConstantString")) {
12801     // We already have a __builtin___CFStringMakeConstantString,
12802     // but builds that use -fno-constant-cfstrings don't go through that.
12803     if (!FD->hasAttr<FormatArgAttr>())
12804       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12805                                                 FD->getLocation()));
12806   }
12807 }
12808 
12809 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12810                                     TypeSourceInfo *TInfo) {
12811   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12812   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12813 
12814   if (!TInfo) {
12815     assert(D.isInvalidType() && "no declarator info for valid type");
12816     TInfo = Context.getTrivialTypeSourceInfo(T);
12817   }
12818 
12819   // Scope manipulation handled by caller.
12820   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12821                                            D.getLocStart(),
12822                                            D.getIdentifierLoc(),
12823                                            D.getIdentifier(),
12824                                            TInfo);
12825 
12826   // Bail out immediately if we have an invalid declaration.
12827   if (D.isInvalidType()) {
12828     NewTD->setInvalidDecl();
12829     return NewTD;
12830   }
12831 
12832   if (D.getDeclSpec().isModulePrivateSpecified()) {
12833     if (CurContext->isFunctionOrMethod())
12834       Diag(NewTD->getLocation(), diag::err_module_private_local)
12835         << 2 << NewTD->getDeclName()
12836         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12837         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12838     else
12839       NewTD->setModulePrivate();
12840   }
12841 
12842   // C++ [dcl.typedef]p8:
12843   //   If the typedef declaration defines an unnamed class (or
12844   //   enum), the first typedef-name declared by the declaration
12845   //   to be that class type (or enum type) is used to denote the
12846   //   class type (or enum type) for linkage purposes only.
12847   // We need to check whether the type was declared in the declaration.
12848   switch (D.getDeclSpec().getTypeSpecType()) {
12849   case TST_enum:
12850   case TST_struct:
12851   case TST_interface:
12852   case TST_union:
12853   case TST_class: {
12854     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12855     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12856     break;
12857   }
12858 
12859   default:
12860     break;
12861   }
12862 
12863   return NewTD;
12864 }
12865 
12866 /// \brief Check that this is a valid underlying type for an enum declaration.
12867 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12868   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12869   QualType T = TI->getType();
12870 
12871   if (T->isDependentType())
12872     return false;
12873 
12874   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12875     if (BT->isInteger())
12876       return false;
12877 
12878   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12879   return true;
12880 }
12881 
12882 /// Check whether this is a valid redeclaration of a previous enumeration.
12883 /// \return true if the redeclaration was invalid.
12884 bool Sema::CheckEnumRedeclaration(
12885     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12886     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12887   bool IsFixed = !EnumUnderlyingTy.isNull();
12888 
12889   if (IsScoped != Prev->isScoped()) {
12890     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12891       << Prev->isScoped();
12892     Diag(Prev->getLocation(), diag::note_previous_declaration);
12893     return true;
12894   }
12895 
12896   if (IsFixed && Prev->isFixed()) {
12897     if (!EnumUnderlyingTy->isDependentType() &&
12898         !Prev->getIntegerType()->isDependentType() &&
12899         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12900                                         Prev->getIntegerType())) {
12901       // TODO: Highlight the underlying type of the redeclaration.
12902       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12903         << EnumUnderlyingTy << Prev->getIntegerType();
12904       Diag(Prev->getLocation(), diag::note_previous_declaration)
12905           << Prev->getIntegerTypeRange();
12906       return true;
12907     }
12908   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12909     ;
12910   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12911     ;
12912   } else if (IsFixed != Prev->isFixed()) {
12913     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12914       << Prev->isFixed();
12915     Diag(Prev->getLocation(), diag::note_previous_declaration);
12916     return true;
12917   }
12918 
12919   return false;
12920 }
12921 
12922 /// \brief Get diagnostic %select index for tag kind for
12923 /// redeclaration diagnostic message.
12924 /// WARNING: Indexes apply to particular diagnostics only!
12925 ///
12926 /// \returns diagnostic %select index.
12927 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12928   switch (Tag) {
12929   case TTK_Struct: return 0;
12930   case TTK_Interface: return 1;
12931   case TTK_Class:  return 2;
12932   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12933   }
12934 }
12935 
12936 /// \brief Determine if tag kind is a class-key compatible with
12937 /// class for redeclaration (class, struct, or __interface).
12938 ///
12939 /// \returns true iff the tag kind is compatible.
12940 static bool isClassCompatTagKind(TagTypeKind Tag)
12941 {
12942   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12943 }
12944 
12945 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12946                                              TagTypeKind TTK) {
12947   if (isa<TypedefDecl>(PrevDecl))
12948     return NTK_Typedef;
12949   else if (isa<TypeAliasDecl>(PrevDecl))
12950     return NTK_TypeAlias;
12951   else if (isa<ClassTemplateDecl>(PrevDecl))
12952     return NTK_Template;
12953   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12954     return NTK_TypeAliasTemplate;
12955   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12956     return NTK_TemplateTemplateArgument;
12957   switch (TTK) {
12958   case TTK_Struct:
12959   case TTK_Interface:
12960   case TTK_Class:
12961     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12962   case TTK_Union:
12963     return NTK_NonUnion;
12964   case TTK_Enum:
12965     return NTK_NonEnum;
12966   }
12967   llvm_unreachable("invalid TTK");
12968 }
12969 
12970 /// \brief Determine whether a tag with a given kind is acceptable
12971 /// as a redeclaration of the given tag declaration.
12972 ///
12973 /// \returns true if the new tag kind is acceptable, false otherwise.
12974 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12975                                         TagTypeKind NewTag, bool isDefinition,
12976                                         SourceLocation NewTagLoc,
12977                                         const IdentifierInfo *Name) {
12978   // C++ [dcl.type.elab]p3:
12979   //   The class-key or enum keyword present in the
12980   //   elaborated-type-specifier shall agree in kind with the
12981   //   declaration to which the name in the elaborated-type-specifier
12982   //   refers. This rule also applies to the form of
12983   //   elaborated-type-specifier that declares a class-name or
12984   //   friend class since it can be construed as referring to the
12985   //   definition of the class. Thus, in any
12986   //   elaborated-type-specifier, the enum keyword shall be used to
12987   //   refer to an enumeration (7.2), the union class-key shall be
12988   //   used to refer to a union (clause 9), and either the class or
12989   //   struct class-key shall be used to refer to a class (clause 9)
12990   //   declared using the class or struct class-key.
12991   TagTypeKind OldTag = Previous->getTagKind();
12992   if (!isDefinition || !isClassCompatTagKind(NewTag))
12993     if (OldTag == NewTag)
12994       return true;
12995 
12996   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12997     // Warn about the struct/class tag mismatch.
12998     bool isTemplate = false;
12999     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13000       isTemplate = Record->getDescribedClassTemplate();
13001 
13002     if (inTemplateInstantiation()) {
13003       // In a template instantiation, do not offer fix-its for tag mismatches
13004       // since they usually mess up the template instead of fixing the problem.
13005       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13006         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13007         << getRedeclDiagFromTagKind(OldTag);
13008       return true;
13009     }
13010 
13011     if (isDefinition) {
13012       // On definitions, check previous tags and issue a fix-it for each
13013       // one that doesn't match the current tag.
13014       if (Previous->getDefinition()) {
13015         // Don't suggest fix-its for redefinitions.
13016         return true;
13017       }
13018 
13019       bool previousMismatch = false;
13020       for (auto I : Previous->redecls()) {
13021         if (I->getTagKind() != NewTag) {
13022           if (!previousMismatch) {
13023             previousMismatch = true;
13024             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13025               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13026               << getRedeclDiagFromTagKind(I->getTagKind());
13027           }
13028           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13029             << getRedeclDiagFromTagKind(NewTag)
13030             << FixItHint::CreateReplacement(I->getInnerLocStart(),
13031                  TypeWithKeyword::getTagTypeKindName(NewTag));
13032         }
13033       }
13034       return true;
13035     }
13036 
13037     // Check for a previous definition.  If current tag and definition
13038     // are same type, do nothing.  If no definition, but disagree with
13039     // with previous tag type, give a warning, but no fix-it.
13040     const TagDecl *Redecl = Previous->getDefinition() ?
13041                             Previous->getDefinition() : Previous;
13042     if (Redecl->getTagKind() == NewTag) {
13043       return true;
13044     }
13045 
13046     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13047       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13048       << getRedeclDiagFromTagKind(OldTag);
13049     Diag(Redecl->getLocation(), diag::note_previous_use);
13050 
13051     // If there is a previous definition, suggest a fix-it.
13052     if (Previous->getDefinition()) {
13053         Diag(NewTagLoc, diag::note_struct_class_suggestion)
13054           << getRedeclDiagFromTagKind(Redecl->getTagKind())
13055           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13056                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13057     }
13058 
13059     return true;
13060   }
13061   return false;
13062 }
13063 
13064 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13065 /// from an outer enclosing namespace or file scope inside a friend declaration.
13066 /// This should provide the commented out code in the following snippet:
13067 ///   namespace N {
13068 ///     struct X;
13069 ///     namespace M {
13070 ///       struct Y { friend struct /*N::*/ X; };
13071 ///     }
13072 ///   }
13073 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13074                                          SourceLocation NameLoc) {
13075   // While the decl is in a namespace, do repeated lookup of that name and see
13076   // if we get the same namespace back.  If we do not, continue until
13077   // translation unit scope, at which point we have a fully qualified NNS.
13078   SmallVector<IdentifierInfo *, 4> Namespaces;
13079   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13080   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13081     // This tag should be declared in a namespace, which can only be enclosed by
13082     // other namespaces.  Bail if there's an anonymous namespace in the chain.
13083     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13084     if (!Namespace || Namespace->isAnonymousNamespace())
13085       return FixItHint();
13086     IdentifierInfo *II = Namespace->getIdentifier();
13087     Namespaces.push_back(II);
13088     NamedDecl *Lookup = SemaRef.LookupSingleName(
13089         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13090     if (Lookup == Namespace)
13091       break;
13092   }
13093 
13094   // Once we have all the namespaces, reverse them to go outermost first, and
13095   // build an NNS.
13096   SmallString<64> Insertion;
13097   llvm::raw_svector_ostream OS(Insertion);
13098   if (DC->isTranslationUnit())
13099     OS << "::";
13100   std::reverse(Namespaces.begin(), Namespaces.end());
13101   for (auto *II : Namespaces)
13102     OS << II->getName() << "::";
13103   return FixItHint::CreateInsertion(NameLoc, Insertion);
13104 }
13105 
13106 /// \brief Determine whether a tag originally declared in context \p OldDC can
13107 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
13108 /// found a declaration in \p OldDC as a previous decl, perhaps through a
13109 /// using-declaration).
13110 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13111                                          DeclContext *NewDC) {
13112   OldDC = OldDC->getRedeclContext();
13113   NewDC = NewDC->getRedeclContext();
13114 
13115   if (OldDC->Equals(NewDC))
13116     return true;
13117 
13118   // In MSVC mode, we allow a redeclaration if the contexts are related (either
13119   // encloses the other).
13120   if (S.getLangOpts().MSVCCompat &&
13121       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13122     return true;
13123 
13124   return false;
13125 }
13126 
13127 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
13128 /// former case, Name will be non-null.  In the later case, Name will be null.
13129 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13130 /// reference/declaration/definition of a tag.
13131 ///
13132 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
13133 /// trailing-type-specifier) other than one in an alias-declaration.
13134 ///
13135 /// \param SkipBody If non-null, will be set to indicate if the caller should
13136 /// skip the definition of this tag and treat it as if it were a declaration.
13137 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13138                      SourceLocation KWLoc, CXXScopeSpec &SS,
13139                      IdentifierInfo *Name, SourceLocation NameLoc,
13140                      AttributeList *Attr, AccessSpecifier AS,
13141                      SourceLocation ModulePrivateLoc,
13142                      MultiTemplateParamsArg TemplateParameterLists,
13143                      bool &OwnedDecl, bool &IsDependent,
13144                      SourceLocation ScopedEnumKWLoc,
13145                      bool ScopedEnumUsesClassTag,
13146                      TypeResult UnderlyingType,
13147                      bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13148                      SkipBodyInfo *SkipBody) {
13149   // If this is not a definition, it must have a name.
13150   IdentifierInfo *OrigName = Name;
13151   assert((Name != nullptr || TUK == TUK_Definition) &&
13152          "Nameless record must be a definition!");
13153   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
13154 
13155   OwnedDecl = false;
13156   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13157   bool ScopedEnum = ScopedEnumKWLoc.isValid();
13158 
13159   // FIXME: Check member specializations more carefully.
13160   bool isMemberSpecialization = false;
13161   bool Invalid = false;
13162 
13163   // We only need to do this matching if we have template parameters
13164   // or a scope specifier, which also conveniently avoids this work
13165   // for non-C++ cases.
13166   if (TemplateParameterLists.size() > 0 ||
13167       (SS.isNotEmpty() && TUK != TUK_Reference)) {
13168     if (TemplateParameterList *TemplateParams =
13169             MatchTemplateParametersToScopeSpecifier(
13170                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13171                 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13172       if (Kind == TTK_Enum) {
13173         Diag(KWLoc, diag::err_enum_template);
13174         return nullptr;
13175       }
13176 
13177       if (TemplateParams->size() > 0) {
13178         // This is a declaration or definition of a class template (which may
13179         // be a member of another template).
13180 
13181         if (Invalid)
13182           return nullptr;
13183 
13184         OwnedDecl = false;
13185         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13186                                                SS, Name, NameLoc, Attr,
13187                                                TemplateParams, AS,
13188                                                ModulePrivateLoc,
13189                                                /*FriendLoc*/SourceLocation(),
13190                                                TemplateParameterLists.size()-1,
13191                                                TemplateParameterLists.data(),
13192                                                SkipBody);
13193         return Result.get();
13194       } else {
13195         // The "template<>" header is extraneous.
13196         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13197           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13198         isMemberSpecialization = true;
13199       }
13200     }
13201   }
13202 
13203   // Figure out the underlying type if this a enum declaration. We need to do
13204   // this early, because it's needed to detect if this is an incompatible
13205   // redeclaration.
13206   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13207   bool EnumUnderlyingIsImplicit = false;
13208 
13209   if (Kind == TTK_Enum) {
13210     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
13211       // No underlying type explicitly specified, or we failed to parse the
13212       // type, default to int.
13213       EnumUnderlying = Context.IntTy.getTypePtr();
13214     else if (UnderlyingType.get()) {
13215       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13216       // integral type; any cv-qualification is ignored.
13217       TypeSourceInfo *TI = nullptr;
13218       GetTypeFromParser(UnderlyingType.get(), &TI);
13219       EnumUnderlying = TI;
13220 
13221       if (CheckEnumUnderlyingType(TI))
13222         // Recover by falling back to int.
13223         EnumUnderlying = Context.IntTy.getTypePtr();
13224 
13225       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13226                                           UPPC_FixedUnderlyingType))
13227         EnumUnderlying = Context.IntTy.getTypePtr();
13228 
13229     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13230       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
13231         // Microsoft enums are always of int type.
13232         EnumUnderlying = Context.IntTy.getTypePtr();
13233         EnumUnderlyingIsImplicit = true;
13234       }
13235     }
13236   }
13237 
13238   DeclContext *SearchDC = CurContext;
13239   DeclContext *DC = CurContext;
13240   bool isStdBadAlloc = false;
13241   bool isStdAlignValT = false;
13242 
13243   RedeclarationKind Redecl = ForRedeclaration;
13244   if (TUK == TUK_Friend || TUK == TUK_Reference)
13245     Redecl = NotForRedeclaration;
13246 
13247   /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13248   /// implemented asks for structural equivalence checking, the returned decl
13249   /// here is passed back to the parser, allowing the tag body to be parsed.
13250   auto createTagFromNewDecl = [&]() -> TagDecl * {
13251     assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
13252     // If there is an identifier, use the location of the identifier as the
13253     // location of the decl, otherwise use the location of the struct/union
13254     // keyword.
13255     SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13256     TagDecl *New = nullptr;
13257 
13258     if (Kind == TTK_Enum) {
13259       New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13260                              ScopedEnum, ScopedEnumUsesClassTag,
13261                              !EnumUnderlying.isNull());
13262       // If this is an undefined enum, bail.
13263       if (TUK != TUK_Definition && !Invalid)
13264         return nullptr;
13265       if (EnumUnderlying) {
13266         EnumDecl *ED = cast<EnumDecl>(New);
13267         if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13268           ED->setIntegerTypeSourceInfo(TI);
13269         else
13270           ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13271         ED->setPromotionType(ED->getIntegerType());
13272       }
13273     } else { // struct/union
13274       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13275                                nullptr);
13276     }
13277 
13278     if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13279       // Add alignment attributes if necessary; these attributes are checked
13280       // when the ASTContext lays out the structure.
13281       //
13282       // It is important for implementing the correct semantics that this
13283       // happen here (in ActOnTag). The #pragma pack stack is
13284       // maintained as a result of parser callbacks which can occur at
13285       // many points during the parsing of a struct declaration (because
13286       // the #pragma tokens are effectively skipped over during the
13287       // parsing of the struct).
13288       if (TUK == TUK_Definition) {
13289         AddAlignmentAttributesForRecord(RD);
13290         AddMsStructLayoutForRecord(RD);
13291       }
13292     }
13293     New->setLexicalDeclContext(CurContext);
13294     return New;
13295   };
13296 
13297   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13298   if (Name && SS.isNotEmpty()) {
13299     // We have a nested-name tag ('struct foo::bar').
13300 
13301     // Check for invalid 'foo::'.
13302     if (SS.isInvalid()) {
13303       Name = nullptr;
13304       goto CreateNewDecl;
13305     }
13306 
13307     // If this is a friend or a reference to a class in a dependent
13308     // context, don't try to make a decl for it.
13309     if (TUK == TUK_Friend || TUK == TUK_Reference) {
13310       DC = computeDeclContext(SS, false);
13311       if (!DC) {
13312         IsDependent = true;
13313         return nullptr;
13314       }
13315     } else {
13316       DC = computeDeclContext(SS, true);
13317       if (!DC) {
13318         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13319           << SS.getRange();
13320         return nullptr;
13321       }
13322     }
13323 
13324     if (RequireCompleteDeclContext(SS, DC))
13325       return nullptr;
13326 
13327     SearchDC = DC;
13328     // Look-up name inside 'foo::'.
13329     LookupQualifiedName(Previous, DC);
13330 
13331     if (Previous.isAmbiguous())
13332       return nullptr;
13333 
13334     if (Previous.empty()) {
13335       // Name lookup did not find anything. However, if the
13336       // nested-name-specifier refers to the current instantiation,
13337       // and that current instantiation has any dependent base
13338       // classes, we might find something at instantiation time: treat
13339       // this as a dependent elaborated-type-specifier.
13340       // But this only makes any sense for reference-like lookups.
13341       if (Previous.wasNotFoundInCurrentInstantiation() &&
13342           (TUK == TUK_Reference || TUK == TUK_Friend)) {
13343         IsDependent = true;
13344         return nullptr;
13345       }
13346 
13347       // A tag 'foo::bar' must already exist.
13348       Diag(NameLoc, diag::err_not_tag_in_scope)
13349         << Kind << Name << DC << SS.getRange();
13350       Name = nullptr;
13351       Invalid = true;
13352       goto CreateNewDecl;
13353     }
13354   } else if (Name) {
13355     // C++14 [class.mem]p14:
13356     //   If T is the name of a class, then each of the following shall have a
13357     //   name different from T:
13358     //    -- every member of class T that is itself a type
13359     if (TUK != TUK_Reference && TUK != TUK_Friend &&
13360         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13361       return nullptr;
13362 
13363     // If this is a named struct, check to see if there was a previous forward
13364     // declaration or definition.
13365     // FIXME: We're looking into outer scopes here, even when we
13366     // shouldn't be. Doing so can result in ambiguities that we
13367     // shouldn't be diagnosing.
13368     LookupName(Previous, S);
13369 
13370     // When declaring or defining a tag, ignore ambiguities introduced
13371     // by types using'ed into this scope.
13372     if (Previous.isAmbiguous() &&
13373         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13374       LookupResult::Filter F = Previous.makeFilter();
13375       while (F.hasNext()) {
13376         NamedDecl *ND = F.next();
13377         if (!ND->getDeclContext()->getRedeclContext()->Equals(
13378                 SearchDC->getRedeclContext()))
13379           F.erase();
13380       }
13381       F.done();
13382     }
13383 
13384     // C++11 [namespace.memdef]p3:
13385     //   If the name in a friend declaration is neither qualified nor
13386     //   a template-id and the declaration is a function or an
13387     //   elaborated-type-specifier, the lookup to determine whether
13388     //   the entity has been previously declared shall not consider
13389     //   any scopes outside the innermost enclosing namespace.
13390     //
13391     // MSVC doesn't implement the above rule for types, so a friend tag
13392     // declaration may be a redeclaration of a type declared in an enclosing
13393     // scope.  They do implement this rule for friend functions.
13394     //
13395     // Does it matter that this should be by scope instead of by
13396     // semantic context?
13397     if (!Previous.empty() && TUK == TUK_Friend) {
13398       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13399       LookupResult::Filter F = Previous.makeFilter();
13400       bool FriendSawTagOutsideEnclosingNamespace = false;
13401       while (F.hasNext()) {
13402         NamedDecl *ND = F.next();
13403         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13404         if (DC->isFileContext() &&
13405             !EnclosingNS->Encloses(ND->getDeclContext())) {
13406           if (getLangOpts().MSVCCompat)
13407             FriendSawTagOutsideEnclosingNamespace = true;
13408           else
13409             F.erase();
13410         }
13411       }
13412       F.done();
13413 
13414       // Diagnose this MSVC extension in the easy case where lookup would have
13415       // unambiguously found something outside the enclosing namespace.
13416       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13417         NamedDecl *ND = Previous.getFoundDecl();
13418         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13419             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13420       }
13421     }
13422 
13423     // Note:  there used to be some attempt at recovery here.
13424     if (Previous.isAmbiguous())
13425       return nullptr;
13426 
13427     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13428       // FIXME: This makes sure that we ignore the contexts associated
13429       // with C structs, unions, and enums when looking for a matching
13430       // tag declaration or definition. See the similar lookup tweak
13431       // in Sema::LookupName; is there a better way to deal with this?
13432       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13433         SearchDC = SearchDC->getParent();
13434     }
13435   }
13436 
13437   if (Previous.isSingleResult() &&
13438       Previous.getFoundDecl()->isTemplateParameter()) {
13439     // Maybe we will complain about the shadowed template parameter.
13440     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13441     // Just pretend that we didn't see the previous declaration.
13442     Previous.clear();
13443   }
13444 
13445   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13446       DC->Equals(getStdNamespace())) {
13447     if (Name->isStr("bad_alloc")) {
13448       // This is a declaration of or a reference to "std::bad_alloc".
13449       isStdBadAlloc = true;
13450 
13451       // If std::bad_alloc has been implicitly declared (but made invisible to
13452       // name lookup), fill in this implicit declaration as the previous
13453       // declaration, so that the declarations get chained appropriately.
13454       if (Previous.empty() && StdBadAlloc)
13455         Previous.addDecl(getStdBadAlloc());
13456     } else if (Name->isStr("align_val_t")) {
13457       isStdAlignValT = true;
13458       if (Previous.empty() && StdAlignValT)
13459         Previous.addDecl(getStdAlignValT());
13460     }
13461   }
13462 
13463   // If we didn't find a previous declaration, and this is a reference
13464   // (or friend reference), move to the correct scope.  In C++, we
13465   // also need to do a redeclaration lookup there, just in case
13466   // there's a shadow friend decl.
13467   if (Name && Previous.empty() &&
13468       (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13469     if (Invalid) goto CreateNewDecl;
13470     assert(SS.isEmpty());
13471 
13472     if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13473       // C++ [basic.scope.pdecl]p5:
13474       //   -- for an elaborated-type-specifier of the form
13475       //
13476       //          class-key identifier
13477       //
13478       //      if the elaborated-type-specifier is used in the
13479       //      decl-specifier-seq or parameter-declaration-clause of a
13480       //      function defined in namespace scope, the identifier is
13481       //      declared as a class-name in the namespace that contains
13482       //      the declaration; otherwise, except as a friend
13483       //      declaration, the identifier is declared in the smallest
13484       //      non-class, non-function-prototype scope that contains the
13485       //      declaration.
13486       //
13487       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13488       // C structs and unions.
13489       //
13490       // It is an error in C++ to declare (rather than define) an enum
13491       // type, including via an elaborated type specifier.  We'll
13492       // diagnose that later; for now, declare the enum in the same
13493       // scope as we would have picked for any other tag type.
13494       //
13495       // GNU C also supports this behavior as part of its incomplete
13496       // enum types extension, while GNU C++ does not.
13497       //
13498       // Find the context where we'll be declaring the tag.
13499       // FIXME: We would like to maintain the current DeclContext as the
13500       // lexical context,
13501       SearchDC = getTagInjectionContext(SearchDC);
13502 
13503       // Find the scope where we'll be declaring the tag.
13504       S = getTagInjectionScope(S, getLangOpts());
13505     } else {
13506       assert(TUK == TUK_Friend);
13507       // C++ [namespace.memdef]p3:
13508       //   If a friend declaration in a non-local class first declares a
13509       //   class or function, the friend class or function is a member of
13510       //   the innermost enclosing namespace.
13511       SearchDC = SearchDC->getEnclosingNamespaceContext();
13512     }
13513 
13514     // In C++, we need to do a redeclaration lookup to properly
13515     // diagnose some problems.
13516     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13517     // hidden declaration so that we don't get ambiguity errors when using a
13518     // type declared by an elaborated-type-specifier.  In C that is not correct
13519     // and we should instead merge compatible types found by lookup.
13520     if (getLangOpts().CPlusPlus) {
13521       Previous.setRedeclarationKind(ForRedeclaration);
13522       LookupQualifiedName(Previous, SearchDC);
13523     } else {
13524       Previous.setRedeclarationKind(ForRedeclaration);
13525       LookupName(Previous, S);
13526     }
13527   }
13528 
13529   // If we have a known previous declaration to use, then use it.
13530   if (Previous.empty() && SkipBody && SkipBody->Previous)
13531     Previous.addDecl(SkipBody->Previous);
13532 
13533   if (!Previous.empty()) {
13534     NamedDecl *PrevDecl = Previous.getFoundDecl();
13535     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13536 
13537     // It's okay to have a tag decl in the same scope as a typedef
13538     // which hides a tag decl in the same scope.  Finding this
13539     // insanity with a redeclaration lookup can only actually happen
13540     // in C++.
13541     //
13542     // This is also okay for elaborated-type-specifiers, which is
13543     // technically forbidden by the current standard but which is
13544     // okay according to the likely resolution of an open issue;
13545     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13546     if (getLangOpts().CPlusPlus) {
13547       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13548         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13549           TagDecl *Tag = TT->getDecl();
13550           if (Tag->getDeclName() == Name &&
13551               Tag->getDeclContext()->getRedeclContext()
13552                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13553             PrevDecl = Tag;
13554             Previous.clear();
13555             Previous.addDecl(Tag);
13556             Previous.resolveKind();
13557           }
13558         }
13559       }
13560     }
13561 
13562     // If this is a redeclaration of a using shadow declaration, it must
13563     // declare a tag in the same context. In MSVC mode, we allow a
13564     // redefinition if either context is within the other.
13565     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13566       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13567       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13568           isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13569           !(OldTag && isAcceptableTagRedeclContext(
13570                           *this, OldTag->getDeclContext(), SearchDC))) {
13571         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13572         Diag(Shadow->getTargetDecl()->getLocation(),
13573              diag::note_using_decl_target);
13574         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13575             << 0;
13576         // Recover by ignoring the old declaration.
13577         Previous.clear();
13578         goto CreateNewDecl;
13579       }
13580     }
13581 
13582     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13583       // If this is a use of a previous tag, or if the tag is already declared
13584       // in the same scope (so that the definition/declaration completes or
13585       // rementions the tag), reuse the decl.
13586       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13587           isDeclInScope(DirectPrevDecl, SearchDC, S,
13588                         SS.isNotEmpty() || isMemberSpecialization)) {
13589         // Make sure that this wasn't declared as an enum and now used as a
13590         // struct or something similar.
13591         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13592                                           TUK == TUK_Definition, KWLoc,
13593                                           Name)) {
13594           bool SafeToContinue
13595             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13596                Kind != TTK_Enum);
13597           if (SafeToContinue)
13598             Diag(KWLoc, diag::err_use_with_wrong_tag)
13599               << Name
13600               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13601                                               PrevTagDecl->getKindName());
13602           else
13603             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13604           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13605 
13606           if (SafeToContinue)
13607             Kind = PrevTagDecl->getTagKind();
13608           else {
13609             // Recover by making this an anonymous redefinition.
13610             Name = nullptr;
13611             Previous.clear();
13612             Invalid = true;
13613           }
13614         }
13615 
13616         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13617           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13618 
13619           // If this is an elaborated-type-specifier for a scoped enumeration,
13620           // the 'class' keyword is not necessary and not permitted.
13621           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13622             if (ScopedEnum)
13623               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13624                 << PrevEnum->isScoped()
13625                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13626             return PrevTagDecl;
13627           }
13628 
13629           QualType EnumUnderlyingTy;
13630           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13631             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13632           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13633             EnumUnderlyingTy = QualType(T, 0);
13634 
13635           // All conflicts with previous declarations are recovered by
13636           // returning the previous declaration, unless this is a definition,
13637           // in which case we want the caller to bail out.
13638           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13639                                      ScopedEnum, EnumUnderlyingTy,
13640                                      EnumUnderlyingIsImplicit, PrevEnum))
13641             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13642         }
13643 
13644         // C++11 [class.mem]p1:
13645         //   A member shall not be declared twice in the member-specification,
13646         //   except that a nested class or member class template can be declared
13647         //   and then later defined.
13648         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13649             S->isDeclScope(PrevDecl)) {
13650           Diag(NameLoc, diag::ext_member_redeclared);
13651           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13652         }
13653 
13654         if (!Invalid) {
13655           // If this is a use, just return the declaration we found, unless
13656           // we have attributes.
13657           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13658             if (Attr) {
13659               // FIXME: Diagnose these attributes. For now, we create a new
13660               // declaration to hold them.
13661             } else if (TUK == TUK_Reference &&
13662                        (PrevTagDecl->getFriendObjectKind() ==
13663                             Decl::FOK_Undeclared ||
13664                         PrevDecl->getOwningModule() != getCurrentModule()) &&
13665                        SS.isEmpty()) {
13666               // This declaration is a reference to an existing entity, but
13667               // has different visibility from that entity: it either makes
13668               // a friend visible or it makes a type visible in a new module.
13669               // In either case, create a new declaration. We only do this if
13670               // the declaration would have meant the same thing if no prior
13671               // declaration were found, that is, if it was found in the same
13672               // scope where we would have injected a declaration.
13673               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13674                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13675                 return PrevTagDecl;
13676               // This is in the injected scope, create a new declaration in
13677               // that scope.
13678               S = getTagInjectionScope(S, getLangOpts());
13679             } else {
13680               return PrevTagDecl;
13681             }
13682           }
13683 
13684           // Diagnose attempts to redefine a tag.
13685           if (TUK == TUK_Definition) {
13686             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13687               // If we're defining a specialization and the previous definition
13688               // is from an implicit instantiation, don't emit an error
13689               // here; we'll catch this in the general case below.
13690               bool IsExplicitSpecializationAfterInstantiation = false;
13691               if (isMemberSpecialization) {
13692                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13693                   IsExplicitSpecializationAfterInstantiation =
13694                     RD->getTemplateSpecializationKind() !=
13695                     TSK_ExplicitSpecialization;
13696                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13697                   IsExplicitSpecializationAfterInstantiation =
13698                     ED->getTemplateSpecializationKind() !=
13699                     TSK_ExplicitSpecialization;
13700               }
13701 
13702               // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
13703               // not keep more that one definition around (merge them). However,
13704               // ensure the decl passes the structural compatibility check in
13705               // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
13706               NamedDecl *Hidden = nullptr;
13707               if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
13708                 // There is a definition of this tag, but it is not visible. We
13709                 // explicitly make use of C++'s one definition rule here, and
13710                 // assume that this definition is identical to the hidden one
13711                 // we already have. Make the existing definition visible and
13712                 // use it in place of this one.
13713                 if (!getLangOpts().CPlusPlus) {
13714                   // Postpone making the old definition visible until after we
13715                   // complete parsing the new one and do the structural
13716                   // comparison.
13717                   SkipBody->CheckSameAsPrevious = true;
13718                   SkipBody->New = createTagFromNewDecl();
13719                   SkipBody->Previous = Hidden;
13720                 } else {
13721                   SkipBody->ShouldSkip = true;
13722                   makeMergedDefinitionVisible(Hidden);
13723                 }
13724                 return Def;
13725               } else if (!IsExplicitSpecializationAfterInstantiation) {
13726                 // A redeclaration in function prototype scope in C isn't
13727                 // visible elsewhere, so merely issue a warning.
13728                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13729                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13730                 else
13731                   Diag(NameLoc, diag::err_redefinition) << Name;
13732                 notePreviousDefinition(Def,
13733                                        NameLoc.isValid() ? NameLoc : KWLoc);
13734                 // If this is a redefinition, recover by making this
13735                 // struct be anonymous, which will make any later
13736                 // references get the previous definition.
13737                 Name = nullptr;
13738                 Previous.clear();
13739                 Invalid = true;
13740               }
13741             } else {
13742               // If the type is currently being defined, complain
13743               // about a nested redefinition.
13744               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13745               if (TD->isBeingDefined()) {
13746                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13747                 Diag(PrevTagDecl->getLocation(),
13748                      diag::note_previous_definition);
13749                 Name = nullptr;
13750                 Previous.clear();
13751                 Invalid = true;
13752               }
13753             }
13754 
13755             // Okay, this is definition of a previously declared or referenced
13756             // tag. We're going to create a new Decl for it.
13757           }
13758 
13759           // Okay, we're going to make a redeclaration.  If this is some kind
13760           // of reference, make sure we build the redeclaration in the same DC
13761           // as the original, and ignore the current access specifier.
13762           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13763             SearchDC = PrevTagDecl->getDeclContext();
13764             AS = AS_none;
13765           }
13766         }
13767         // If we get here we have (another) forward declaration or we
13768         // have a definition.  Just create a new decl.
13769 
13770       } else {
13771         // If we get here, this is a definition of a new tag type in a nested
13772         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13773         // new decl/type.  We set PrevDecl to NULL so that the entities
13774         // have distinct types.
13775         Previous.clear();
13776       }
13777       // If we get here, we're going to create a new Decl. If PrevDecl
13778       // is non-NULL, it's a definition of the tag declared by
13779       // PrevDecl. If it's NULL, we have a new definition.
13780 
13781     // Otherwise, PrevDecl is not a tag, but was found with tag
13782     // lookup.  This is only actually possible in C++, where a few
13783     // things like templates still live in the tag namespace.
13784     } else {
13785       // Use a better diagnostic if an elaborated-type-specifier
13786       // found the wrong kind of type on the first
13787       // (non-redeclaration) lookup.
13788       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13789           !Previous.isForRedeclaration()) {
13790         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13791         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13792                                                        << Kind;
13793         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13794         Invalid = true;
13795 
13796       // Otherwise, only diagnose if the declaration is in scope.
13797       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13798                                 SS.isNotEmpty() || isMemberSpecialization)) {
13799         // do nothing
13800 
13801       // Diagnose implicit declarations introduced by elaborated types.
13802       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13803         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13804         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13805         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13806         Invalid = true;
13807 
13808       // Otherwise it's a declaration.  Call out a particularly common
13809       // case here.
13810       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13811         unsigned Kind = 0;
13812         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13813         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13814           << Name << Kind << TND->getUnderlyingType();
13815         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13816         Invalid = true;
13817 
13818       // Otherwise, diagnose.
13819       } else {
13820         // The tag name clashes with something else in the target scope,
13821         // issue an error and recover by making this tag be anonymous.
13822         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13823         notePreviousDefinition(PrevDecl, NameLoc);
13824         Name = nullptr;
13825         Invalid = true;
13826       }
13827 
13828       // The existing declaration isn't relevant to us; we're in a
13829       // new scope, so clear out the previous declaration.
13830       Previous.clear();
13831     }
13832   }
13833 
13834 CreateNewDecl:
13835 
13836   TagDecl *PrevDecl = nullptr;
13837   if (Previous.isSingleResult())
13838     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13839 
13840   // If there is an identifier, use the location of the identifier as the
13841   // location of the decl, otherwise use the location of the struct/union
13842   // keyword.
13843   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13844 
13845   // Otherwise, create a new declaration. If there is a previous
13846   // declaration of the same entity, the two will be linked via
13847   // PrevDecl.
13848   TagDecl *New;
13849 
13850   bool IsForwardReference = false;
13851   if (Kind == TTK_Enum) {
13852     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13853     // enum X { A, B, C } D;    D should chain to X.
13854     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13855                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13856                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13857 
13858     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13859       StdAlignValT = cast<EnumDecl>(New);
13860 
13861     // If this is an undefined enum, warn.
13862     if (TUK != TUK_Definition && !Invalid) {
13863       TagDecl *Def;
13864       if (!EnumUnderlyingIsImplicit &&
13865           (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13866           cast<EnumDecl>(New)->isFixed()) {
13867         // C++0x: 7.2p2: opaque-enum-declaration.
13868         // Conflicts are diagnosed above. Do nothing.
13869       }
13870       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13871         Diag(Loc, diag::ext_forward_ref_enum_def)
13872           << New;
13873         Diag(Def->getLocation(), diag::note_previous_definition);
13874       } else {
13875         unsigned DiagID = diag::ext_forward_ref_enum;
13876         if (getLangOpts().MSVCCompat)
13877           DiagID = diag::ext_ms_forward_ref_enum;
13878         else if (getLangOpts().CPlusPlus)
13879           DiagID = diag::err_forward_ref_enum;
13880         Diag(Loc, DiagID);
13881 
13882         // If this is a forward-declared reference to an enumeration, make a
13883         // note of it; we won't actually be introducing the declaration into
13884         // the declaration context.
13885         if (TUK == TUK_Reference)
13886           IsForwardReference = true;
13887       }
13888     }
13889 
13890     if (EnumUnderlying) {
13891       EnumDecl *ED = cast<EnumDecl>(New);
13892       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13893         ED->setIntegerTypeSourceInfo(TI);
13894       else
13895         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13896       ED->setPromotionType(ED->getIntegerType());
13897     }
13898   } else {
13899     // struct/union/class
13900 
13901     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13902     // struct X { int A; } D;    D should chain to X.
13903     if (getLangOpts().CPlusPlus) {
13904       // FIXME: Look for a way to use RecordDecl for simple structs.
13905       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13906                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13907 
13908       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13909         StdBadAlloc = cast<CXXRecordDecl>(New);
13910     } else
13911       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13912                                cast_or_null<RecordDecl>(PrevDecl));
13913   }
13914 
13915   // C++11 [dcl.type]p3:
13916   //   A type-specifier-seq shall not define a class or enumeration [...].
13917   if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
13918       TUK == TUK_Definition) {
13919     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13920       << Context.getTagDeclType(New);
13921     Invalid = true;
13922   }
13923 
13924   if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
13925       DC->getDeclKind() == Decl::Enum) {
13926     Diag(New->getLocation(), diag::err_type_defined_in_enum)
13927       << Context.getTagDeclType(New);
13928     Invalid = true;
13929   }
13930 
13931   // Maybe add qualifier info.
13932   if (SS.isNotEmpty()) {
13933     if (SS.isSet()) {
13934       // If this is either a declaration or a definition, check the
13935       // nested-name-specifier against the current context. We don't do this
13936       // for explicit specializations, because they have similar checking
13937       // (with more specific diagnostics) in the call to
13938       // CheckMemberSpecialization, below.
13939       if (!isMemberSpecialization &&
13940           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13941           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13942         Invalid = true;
13943 
13944       New->setQualifierInfo(SS.getWithLocInContext(Context));
13945       if (TemplateParameterLists.size() > 0) {
13946         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13947       }
13948     }
13949     else
13950       Invalid = true;
13951   }
13952 
13953   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13954     // Add alignment attributes if necessary; these attributes are checked when
13955     // the ASTContext lays out the structure.
13956     //
13957     // It is important for implementing the correct semantics that this
13958     // happen here (in ActOnTag). The #pragma pack stack is
13959     // maintained as a result of parser callbacks which can occur at
13960     // many points during the parsing of a struct declaration (because
13961     // the #pragma tokens are effectively skipped over during the
13962     // parsing of the struct).
13963     if (TUK == TUK_Definition) {
13964       AddAlignmentAttributesForRecord(RD);
13965       AddMsStructLayoutForRecord(RD);
13966     }
13967   }
13968 
13969   if (ModulePrivateLoc.isValid()) {
13970     if (isMemberSpecialization)
13971       Diag(New->getLocation(), diag::err_module_private_specialization)
13972         << 2
13973         << FixItHint::CreateRemoval(ModulePrivateLoc);
13974     // __module_private__ does not apply to local classes. However, we only
13975     // diagnose this as an error when the declaration specifiers are
13976     // freestanding. Here, we just ignore the __module_private__.
13977     else if (!SearchDC->isFunctionOrMethod())
13978       New->setModulePrivate();
13979   }
13980 
13981   // If this is a specialization of a member class (of a class template),
13982   // check the specialization.
13983   if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
13984     Invalid = true;
13985 
13986   // If we're declaring or defining a tag in function prototype scope in C,
13987   // note that this type can only be used within the function and add it to
13988   // the list of decls to inject into the function definition scope.
13989   if ((Name || Kind == TTK_Enum) &&
13990       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13991     if (getLangOpts().CPlusPlus) {
13992       // C++ [dcl.fct]p6:
13993       //   Types shall not be defined in return or parameter types.
13994       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13995         Diag(Loc, diag::err_type_defined_in_param_type)
13996             << Name;
13997         Invalid = true;
13998       }
13999     } else if (!PrevDecl) {
14000       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14001     }
14002   }
14003 
14004   if (Invalid)
14005     New->setInvalidDecl();
14006 
14007   // Set the lexical context. If the tag has a C++ scope specifier, the
14008   // lexical context will be different from the semantic context.
14009   New->setLexicalDeclContext(CurContext);
14010 
14011   // Mark this as a friend decl if applicable.
14012   // In Microsoft mode, a friend declaration also acts as a forward
14013   // declaration so we always pass true to setObjectOfFriendDecl to make
14014   // the tag name visible.
14015   if (TUK == TUK_Friend)
14016     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14017 
14018   // Set the access specifier.
14019   if (!Invalid && SearchDC->isRecord())
14020     SetMemberAccessSpecifier(New, PrevDecl, AS);
14021 
14022   if (TUK == TUK_Definition)
14023     New->startDefinition();
14024 
14025   if (Attr)
14026     ProcessDeclAttributeList(S, New, Attr);
14027   AddPragmaAttributes(S, New);
14028 
14029   // If this has an identifier, add it to the scope stack.
14030   if (TUK == TUK_Friend) {
14031     // We might be replacing an existing declaration in the lookup tables;
14032     // if so, borrow its access specifier.
14033     if (PrevDecl)
14034       New->setAccess(PrevDecl->getAccess());
14035 
14036     DeclContext *DC = New->getDeclContext()->getRedeclContext();
14037     DC->makeDeclVisibleInContext(New);
14038     if (Name) // can be null along some error paths
14039       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14040         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14041   } else if (Name) {
14042     S = getNonFieldDeclScope(S);
14043     PushOnScopeChains(New, S, !IsForwardReference);
14044     if (IsForwardReference)
14045       SearchDC->makeDeclVisibleInContext(New);
14046   } else {
14047     CurContext->addDecl(New);
14048   }
14049 
14050   // If this is the C FILE type, notify the AST context.
14051   if (IdentifierInfo *II = New->getIdentifier())
14052     if (!New->isInvalidDecl() &&
14053         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14054         II->isStr("FILE"))
14055       Context.setFILEDecl(New);
14056 
14057   if (PrevDecl)
14058     mergeDeclAttributes(New, PrevDecl);
14059 
14060   // If there's a #pragma GCC visibility in scope, set the visibility of this
14061   // record.
14062   AddPushedVisibilityAttribute(New);
14063 
14064   if (isMemberSpecialization && !New->isInvalidDecl())
14065     CompleteMemberSpecialization(New, Previous);
14066 
14067   OwnedDecl = true;
14068   // In C++, don't return an invalid declaration. We can't recover well from
14069   // the cases where we make the type anonymous.
14070   if (Invalid && getLangOpts().CPlusPlus) {
14071     if (New->isBeingDefined())
14072       if (auto RD = dyn_cast<RecordDecl>(New))
14073         RD->completeDefinition();
14074     return nullptr;
14075   } else {
14076     return New;
14077   }
14078 }
14079 
14080 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14081   AdjustDeclIfTemplate(TagD);
14082   TagDecl *Tag = cast<TagDecl>(TagD);
14083 
14084   // Enter the tag context.
14085   PushDeclContext(S, Tag);
14086 
14087   ActOnDocumentableDecl(TagD);
14088 
14089   // If there's a #pragma GCC visibility in scope, set the visibility of this
14090   // record.
14091   AddPushedVisibilityAttribute(Tag);
14092 }
14093 
14094 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14095                                     SkipBodyInfo &SkipBody) {
14096   if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14097     return false;
14098 
14099   // Make the previous decl visible.
14100   makeMergedDefinitionVisible(SkipBody.Previous);
14101   return true;
14102 }
14103 
14104 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14105   assert(isa<ObjCContainerDecl>(IDecl) &&
14106          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
14107   DeclContext *OCD = cast<DeclContext>(IDecl);
14108   assert(getContainingDC(OCD) == CurContext &&
14109       "The next DeclContext should be lexically contained in the current one.");
14110   CurContext = OCD;
14111   return IDecl;
14112 }
14113 
14114 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14115                                            SourceLocation FinalLoc,
14116                                            bool IsFinalSpelledSealed,
14117                                            SourceLocation LBraceLoc) {
14118   AdjustDeclIfTemplate(TagD);
14119   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14120 
14121   FieldCollector->StartClass();
14122 
14123   if (!Record->getIdentifier())
14124     return;
14125 
14126   if (FinalLoc.isValid())
14127     Record->addAttr(new (Context)
14128                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14129 
14130   // C++ [class]p2:
14131   //   [...] The class-name is also inserted into the scope of the
14132   //   class itself; this is known as the injected-class-name. For
14133   //   purposes of access checking, the injected-class-name is treated
14134   //   as if it were a public member name.
14135   CXXRecordDecl *InjectedClassName
14136     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14137                             Record->getLocStart(), Record->getLocation(),
14138                             Record->getIdentifier(),
14139                             /*PrevDecl=*/nullptr,
14140                             /*DelayTypeCreation=*/true);
14141   Context.getTypeDeclType(InjectedClassName, Record);
14142   InjectedClassName->setImplicit();
14143   InjectedClassName->setAccess(AS_public);
14144   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14145       InjectedClassName->setDescribedClassTemplate(Template);
14146   PushOnScopeChains(InjectedClassName, S);
14147   assert(InjectedClassName->isInjectedClassName() &&
14148          "Broken injected-class-name");
14149 }
14150 
14151 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14152                                     SourceRange BraceRange) {
14153   AdjustDeclIfTemplate(TagD);
14154   TagDecl *Tag = cast<TagDecl>(TagD);
14155   Tag->setBraceRange(BraceRange);
14156 
14157   // Make sure we "complete" the definition even it is invalid.
14158   if (Tag->isBeingDefined()) {
14159     assert(Tag->isInvalidDecl() && "We should already have completed it");
14160     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14161       RD->completeDefinition();
14162   }
14163 
14164   if (isa<CXXRecordDecl>(Tag)) {
14165     FieldCollector->FinishClass();
14166   }
14167 
14168   // Exit this scope of this tag's definition.
14169   PopDeclContext();
14170 
14171   if (getCurLexicalContext()->isObjCContainer() &&
14172       Tag->getDeclContext()->isFileContext())
14173     Tag->setTopLevelDeclInObjCContainer();
14174 
14175   // Notify the consumer that we've defined a tag.
14176   if (!Tag->isInvalidDecl())
14177     Consumer.HandleTagDeclDefinition(Tag);
14178 }
14179 
14180 void Sema::ActOnObjCContainerFinishDefinition() {
14181   // Exit this scope of this interface definition.
14182   PopDeclContext();
14183 }
14184 
14185 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14186   assert(DC == CurContext && "Mismatch of container contexts");
14187   OriginalLexicalContext = DC;
14188   ActOnObjCContainerFinishDefinition();
14189 }
14190 
14191 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14192   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14193   OriginalLexicalContext = nullptr;
14194 }
14195 
14196 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14197   AdjustDeclIfTemplate(TagD);
14198   TagDecl *Tag = cast<TagDecl>(TagD);
14199   Tag->setInvalidDecl();
14200 
14201   // Make sure we "complete" the definition even it is invalid.
14202   if (Tag->isBeingDefined()) {
14203     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14204       RD->completeDefinition();
14205   }
14206 
14207   // We're undoing ActOnTagStartDefinition here, not
14208   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14209   // the FieldCollector.
14210 
14211   PopDeclContext();
14212 }
14213 
14214 // Note that FieldName may be null for anonymous bitfields.
14215 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14216                                 IdentifierInfo *FieldName,
14217                                 QualType FieldTy, bool IsMsStruct,
14218                                 Expr *BitWidth, bool *ZeroWidth) {
14219   // Default to true; that shouldn't confuse checks for emptiness
14220   if (ZeroWidth)
14221     *ZeroWidth = true;
14222 
14223   // C99 6.7.2.1p4 - verify the field type.
14224   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14225   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14226     // Handle incomplete types with specific error.
14227     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14228       return ExprError();
14229     if (FieldName)
14230       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14231         << FieldName << FieldTy << BitWidth->getSourceRange();
14232     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14233       << FieldTy << BitWidth->getSourceRange();
14234   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14235                                              UPPC_BitFieldWidth))
14236     return ExprError();
14237 
14238   // If the bit-width is type- or value-dependent, don't try to check
14239   // it now.
14240   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14241     return BitWidth;
14242 
14243   llvm::APSInt Value;
14244   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14245   if (ICE.isInvalid())
14246     return ICE;
14247   BitWidth = ICE.get();
14248 
14249   if (Value != 0 && ZeroWidth)
14250     *ZeroWidth = false;
14251 
14252   // Zero-width bitfield is ok for anonymous field.
14253   if (Value == 0 && FieldName)
14254     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14255 
14256   if (Value.isSigned() && Value.isNegative()) {
14257     if (FieldName)
14258       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14259                << FieldName << Value.toString(10);
14260     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14261       << Value.toString(10);
14262   }
14263 
14264   if (!FieldTy->isDependentType()) {
14265     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14266     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14267     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14268 
14269     // Over-wide bitfields are an error in C or when using the MSVC bitfield
14270     // ABI.
14271     bool CStdConstraintViolation =
14272         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14273     bool MSBitfieldViolation =
14274         Value.ugt(TypeStorageSize) &&
14275         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14276     if (CStdConstraintViolation || MSBitfieldViolation) {
14277       unsigned DiagWidth =
14278           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14279       if (FieldName)
14280         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14281                << FieldName << (unsigned)Value.getZExtValue()
14282                << !CStdConstraintViolation << DiagWidth;
14283 
14284       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14285              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14286              << DiagWidth;
14287     }
14288 
14289     // Warn on types where the user might conceivably expect to get all
14290     // specified bits as value bits: that's all integral types other than
14291     // 'bool'.
14292     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14293       if (FieldName)
14294         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14295             << FieldName << (unsigned)Value.getZExtValue()
14296             << (unsigned)TypeWidth;
14297       else
14298         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14299             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14300     }
14301   }
14302 
14303   return BitWidth;
14304 }
14305 
14306 /// ActOnField - Each field of a C struct/union is passed into this in order
14307 /// to create a FieldDecl object for it.
14308 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14309                        Declarator &D, Expr *BitfieldWidth) {
14310   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14311                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14312                                /*InitStyle=*/ICIS_NoInit, AS_public);
14313   return Res;
14314 }
14315 
14316 /// HandleField - Analyze a field of a C struct or a C++ data member.
14317 ///
14318 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14319                              SourceLocation DeclStart,
14320                              Declarator &D, Expr *BitWidth,
14321                              InClassInitStyle InitStyle,
14322                              AccessSpecifier AS) {
14323   if (D.isDecompositionDeclarator()) {
14324     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14325     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14326       << Decomp.getSourceRange();
14327     return nullptr;
14328   }
14329 
14330   IdentifierInfo *II = D.getIdentifier();
14331   SourceLocation Loc = DeclStart;
14332   if (II) Loc = D.getIdentifierLoc();
14333 
14334   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14335   QualType T = TInfo->getType();
14336   if (getLangOpts().CPlusPlus) {
14337     CheckExtraCXXDefaultArguments(D);
14338 
14339     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14340                                         UPPC_DataMemberType)) {
14341       D.setInvalidType();
14342       T = Context.IntTy;
14343       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14344     }
14345   }
14346 
14347   // TR 18037 does not allow fields to be declared with address spaces.
14348   if (T.getQualifiers().hasAddressSpace() ||
14349       T->isDependentAddressSpaceType() ||
14350       T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14351     Diag(Loc, diag::err_field_with_address_space);
14352     D.setInvalidType();
14353   }
14354 
14355   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14356   // used as structure or union field: image, sampler, event or block types.
14357   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14358                           T->isSamplerT() || T->isBlockPointerType())) {
14359     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14360     D.setInvalidType();
14361   }
14362 
14363   DiagnoseFunctionSpecifiers(D.getDeclSpec());
14364 
14365   if (D.getDeclSpec().isInlineSpecified())
14366     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14367         << getLangOpts().CPlusPlus1z;
14368   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14369     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14370          diag::err_invalid_thread)
14371       << DeclSpec::getSpecifierName(TSCS);
14372 
14373   // Check to see if this name was declared as a member previously
14374   NamedDecl *PrevDecl = nullptr;
14375   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
14376   LookupName(Previous, S);
14377   switch (Previous.getResultKind()) {
14378     case LookupResult::Found:
14379     case LookupResult::FoundUnresolvedValue:
14380       PrevDecl = Previous.getAsSingle<NamedDecl>();
14381       break;
14382 
14383     case LookupResult::FoundOverloaded:
14384       PrevDecl = Previous.getRepresentativeDecl();
14385       break;
14386 
14387     case LookupResult::NotFound:
14388     case LookupResult::NotFoundInCurrentInstantiation:
14389     case LookupResult::Ambiguous:
14390       break;
14391   }
14392   Previous.suppressDiagnostics();
14393 
14394   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14395     // Maybe we will complain about the shadowed template parameter.
14396     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14397     // Just pretend that we didn't see the previous declaration.
14398     PrevDecl = nullptr;
14399   }
14400 
14401   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14402     PrevDecl = nullptr;
14403 
14404   bool Mutable
14405     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14406   SourceLocation TSSL = D.getLocStart();
14407   FieldDecl *NewFD
14408     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14409                      TSSL, AS, PrevDecl, &D);
14410 
14411   if (NewFD->isInvalidDecl())
14412     Record->setInvalidDecl();
14413 
14414   if (D.getDeclSpec().isModulePrivateSpecified())
14415     NewFD->setModulePrivate();
14416 
14417   if (NewFD->isInvalidDecl() && PrevDecl) {
14418     // Don't introduce NewFD into scope; there's already something
14419     // with the same name in the same scope.
14420   } else if (II) {
14421     PushOnScopeChains(NewFD, S);
14422   } else
14423     Record->addDecl(NewFD);
14424 
14425   return NewFD;
14426 }
14427 
14428 /// \brief Build a new FieldDecl and check its well-formedness.
14429 ///
14430 /// This routine builds a new FieldDecl given the fields name, type,
14431 /// record, etc. \p PrevDecl should refer to any previous declaration
14432 /// with the same name and in the same scope as the field to be
14433 /// created.
14434 ///
14435 /// \returns a new FieldDecl.
14436 ///
14437 /// \todo The Declarator argument is a hack. It will be removed once
14438 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14439                                 TypeSourceInfo *TInfo,
14440                                 RecordDecl *Record, SourceLocation Loc,
14441                                 bool Mutable, Expr *BitWidth,
14442                                 InClassInitStyle InitStyle,
14443                                 SourceLocation TSSL,
14444                                 AccessSpecifier AS, NamedDecl *PrevDecl,
14445                                 Declarator *D) {
14446   IdentifierInfo *II = Name.getAsIdentifierInfo();
14447   bool InvalidDecl = false;
14448   if (D) InvalidDecl = D->isInvalidType();
14449 
14450   // If we receive a broken type, recover by assuming 'int' and
14451   // marking this declaration as invalid.
14452   if (T.isNull()) {
14453     InvalidDecl = true;
14454     T = Context.IntTy;
14455   }
14456 
14457   QualType EltTy = Context.getBaseElementType(T);
14458   if (!EltTy->isDependentType()) {
14459     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14460       // Fields of incomplete type force their record to be invalid.
14461       Record->setInvalidDecl();
14462       InvalidDecl = true;
14463     } else {
14464       NamedDecl *Def;
14465       EltTy->isIncompleteType(&Def);
14466       if (Def && Def->isInvalidDecl()) {
14467         Record->setInvalidDecl();
14468         InvalidDecl = true;
14469       }
14470     }
14471   }
14472 
14473   // OpenCL v1.2 s6.9.c: bitfields are not supported.
14474   if (BitWidth && getLangOpts().OpenCL) {
14475     Diag(Loc, diag::err_opencl_bitfields);
14476     InvalidDecl = true;
14477   }
14478 
14479   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14480   // than a variably modified type.
14481   if (!InvalidDecl && T->isVariablyModifiedType()) {
14482     bool SizeIsNegative;
14483     llvm::APSInt Oversized;
14484 
14485     TypeSourceInfo *FixedTInfo =
14486       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14487                                                     SizeIsNegative,
14488                                                     Oversized);
14489     if (FixedTInfo) {
14490       Diag(Loc, diag::warn_illegal_constant_array_size);
14491       TInfo = FixedTInfo;
14492       T = FixedTInfo->getType();
14493     } else {
14494       if (SizeIsNegative)
14495         Diag(Loc, diag::err_typecheck_negative_array_size);
14496       else if (Oversized.getBoolValue())
14497         Diag(Loc, diag::err_array_too_large)
14498           << Oversized.toString(10);
14499       else
14500         Diag(Loc, diag::err_typecheck_field_variable_size);
14501       InvalidDecl = true;
14502     }
14503   }
14504 
14505   // Fields can not have abstract class types
14506   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14507                                              diag::err_abstract_type_in_decl,
14508                                              AbstractFieldType))
14509     InvalidDecl = true;
14510 
14511   bool ZeroWidth = false;
14512   if (InvalidDecl)
14513     BitWidth = nullptr;
14514   // If this is declared as a bit-field, check the bit-field.
14515   if (BitWidth) {
14516     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14517                               &ZeroWidth).get();
14518     if (!BitWidth) {
14519       InvalidDecl = true;
14520       BitWidth = nullptr;
14521       ZeroWidth = false;
14522     }
14523   }
14524 
14525   // Check that 'mutable' is consistent with the type of the declaration.
14526   if (!InvalidDecl && Mutable) {
14527     unsigned DiagID = 0;
14528     if (T->isReferenceType())
14529       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14530                                         : diag::err_mutable_reference;
14531     else if (T.isConstQualified())
14532       DiagID = diag::err_mutable_const;
14533 
14534     if (DiagID) {
14535       SourceLocation ErrLoc = Loc;
14536       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14537         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14538       Diag(ErrLoc, DiagID);
14539       if (DiagID != diag::ext_mutable_reference) {
14540         Mutable = false;
14541         InvalidDecl = true;
14542       }
14543     }
14544   }
14545 
14546   // C++11 [class.union]p8 (DR1460):
14547   //   At most one variant member of a union may have a
14548   //   brace-or-equal-initializer.
14549   if (InitStyle != ICIS_NoInit)
14550     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14551 
14552   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14553                                        BitWidth, Mutable, InitStyle);
14554   if (InvalidDecl)
14555     NewFD->setInvalidDecl();
14556 
14557   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14558     Diag(Loc, diag::err_duplicate_member) << II;
14559     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14560     NewFD->setInvalidDecl();
14561   }
14562 
14563   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14564     if (Record->isUnion()) {
14565       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14566         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14567         if (RDecl->getDefinition()) {
14568           // C++ [class.union]p1: An object of a class with a non-trivial
14569           // constructor, a non-trivial copy constructor, a non-trivial
14570           // destructor, or a non-trivial copy assignment operator
14571           // cannot be a member of a union, nor can an array of such
14572           // objects.
14573           if (CheckNontrivialField(NewFD))
14574             NewFD->setInvalidDecl();
14575         }
14576       }
14577 
14578       // C++ [class.union]p1: If a union contains a member of reference type,
14579       // the program is ill-formed, except when compiling with MSVC extensions
14580       // enabled.
14581       if (EltTy->isReferenceType()) {
14582         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14583                                     diag::ext_union_member_of_reference_type :
14584                                     diag::err_union_member_of_reference_type)
14585           << NewFD->getDeclName() << EltTy;
14586         if (!getLangOpts().MicrosoftExt)
14587           NewFD->setInvalidDecl();
14588       }
14589     }
14590   }
14591 
14592   // FIXME: We need to pass in the attributes given an AST
14593   // representation, not a parser representation.
14594   if (D) {
14595     // FIXME: The current scope is almost... but not entirely... correct here.
14596     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14597 
14598     if (NewFD->hasAttrs())
14599       CheckAlignasUnderalignment(NewFD);
14600   }
14601 
14602   // In auto-retain/release, infer strong retension for fields of
14603   // retainable type.
14604   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14605     NewFD->setInvalidDecl();
14606 
14607   if (T.isObjCGCWeak())
14608     Diag(Loc, diag::warn_attribute_weak_on_field);
14609 
14610   NewFD->setAccess(AS);
14611   return NewFD;
14612 }
14613 
14614 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14615   assert(FD);
14616   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14617 
14618   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14619     return false;
14620 
14621   QualType EltTy = Context.getBaseElementType(FD->getType());
14622   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14623     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14624     if (RDecl->getDefinition()) {
14625       // We check for copy constructors before constructors
14626       // because otherwise we'll never get complaints about
14627       // copy constructors.
14628 
14629       CXXSpecialMember member = CXXInvalid;
14630       // We're required to check for any non-trivial constructors. Since the
14631       // implicit default constructor is suppressed if there are any
14632       // user-declared constructors, we just need to check that there is a
14633       // trivial default constructor and a trivial copy constructor. (We don't
14634       // worry about move constructors here, since this is a C++98 check.)
14635       if (RDecl->hasNonTrivialCopyConstructor())
14636         member = CXXCopyConstructor;
14637       else if (!RDecl->hasTrivialDefaultConstructor())
14638         member = CXXDefaultConstructor;
14639       else if (RDecl->hasNonTrivialCopyAssignment())
14640         member = CXXCopyAssignment;
14641       else if (RDecl->hasNonTrivialDestructor())
14642         member = CXXDestructor;
14643 
14644       if (member != CXXInvalid) {
14645         if (!getLangOpts().CPlusPlus11 &&
14646             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14647           // Objective-C++ ARC: it is an error to have a non-trivial field of
14648           // a union. However, system headers in Objective-C programs
14649           // occasionally have Objective-C lifetime objects within unions,
14650           // and rather than cause the program to fail, we make those
14651           // members unavailable.
14652           SourceLocation Loc = FD->getLocation();
14653           if (getSourceManager().isInSystemHeader(Loc)) {
14654             if (!FD->hasAttr<UnavailableAttr>())
14655               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14656                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14657             return false;
14658           }
14659         }
14660 
14661         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14662                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14663                diag::err_illegal_union_or_anon_struct_member)
14664           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14665         DiagnoseNontrivial(RDecl, member);
14666         return !getLangOpts().CPlusPlus11;
14667       }
14668     }
14669   }
14670 
14671   return false;
14672 }
14673 
14674 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14675 ///  AST enum value.
14676 static ObjCIvarDecl::AccessControl
14677 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14678   switch (ivarVisibility) {
14679   default: llvm_unreachable("Unknown visitibility kind");
14680   case tok::objc_private: return ObjCIvarDecl::Private;
14681   case tok::objc_public: return ObjCIvarDecl::Public;
14682   case tok::objc_protected: return ObjCIvarDecl::Protected;
14683   case tok::objc_package: return ObjCIvarDecl::Package;
14684   }
14685 }
14686 
14687 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14688 /// in order to create an IvarDecl object for it.
14689 Decl *Sema::ActOnIvar(Scope *S,
14690                                 SourceLocation DeclStart,
14691                                 Declarator &D, Expr *BitfieldWidth,
14692                                 tok::ObjCKeywordKind Visibility) {
14693 
14694   IdentifierInfo *II = D.getIdentifier();
14695   Expr *BitWidth = (Expr*)BitfieldWidth;
14696   SourceLocation Loc = DeclStart;
14697   if (II) Loc = D.getIdentifierLoc();
14698 
14699   // FIXME: Unnamed fields can be handled in various different ways, for
14700   // example, unnamed unions inject all members into the struct namespace!
14701 
14702   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14703   QualType T = TInfo->getType();
14704 
14705   if (BitWidth) {
14706     // 6.7.2.1p3, 6.7.2.1p4
14707     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14708     if (!BitWidth)
14709       D.setInvalidType();
14710   } else {
14711     // Not a bitfield.
14712 
14713     // validate II.
14714 
14715   }
14716   if (T->isReferenceType()) {
14717     Diag(Loc, diag::err_ivar_reference_type);
14718     D.setInvalidType();
14719   }
14720   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14721   // than a variably modified type.
14722   else if (T->isVariablyModifiedType()) {
14723     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14724     D.setInvalidType();
14725   }
14726 
14727   // Get the visibility (access control) for this ivar.
14728   ObjCIvarDecl::AccessControl ac =
14729     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14730                                         : ObjCIvarDecl::None;
14731   // Must set ivar's DeclContext to its enclosing interface.
14732   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14733   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14734     return nullptr;
14735   ObjCContainerDecl *EnclosingContext;
14736   if (ObjCImplementationDecl *IMPDecl =
14737       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14738     if (LangOpts.ObjCRuntime.isFragile()) {
14739     // Case of ivar declared in an implementation. Context is that of its class.
14740       EnclosingContext = IMPDecl->getClassInterface();
14741       assert(EnclosingContext && "Implementation has no class interface!");
14742     }
14743     else
14744       EnclosingContext = EnclosingDecl;
14745   } else {
14746     if (ObjCCategoryDecl *CDecl =
14747         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14748       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14749         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14750         return nullptr;
14751       }
14752     }
14753     EnclosingContext = EnclosingDecl;
14754   }
14755 
14756   // Construct the decl.
14757   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14758                                              DeclStart, Loc, II, T,
14759                                              TInfo, ac, (Expr *)BitfieldWidth);
14760 
14761   if (II) {
14762     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14763                                            ForRedeclaration);
14764     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14765         && !isa<TagDecl>(PrevDecl)) {
14766       Diag(Loc, diag::err_duplicate_member) << II;
14767       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14768       NewID->setInvalidDecl();
14769     }
14770   }
14771 
14772   // Process attributes attached to the ivar.
14773   ProcessDeclAttributes(S, NewID, D);
14774 
14775   if (D.isInvalidType())
14776     NewID->setInvalidDecl();
14777 
14778   // In ARC, infer 'retaining' for ivars of retainable type.
14779   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14780     NewID->setInvalidDecl();
14781 
14782   if (D.getDeclSpec().isModulePrivateSpecified())
14783     NewID->setModulePrivate();
14784 
14785   if (II) {
14786     // FIXME: When interfaces are DeclContexts, we'll need to add
14787     // these to the interface.
14788     S->AddDecl(NewID);
14789     IdResolver.AddDecl(NewID);
14790   }
14791 
14792   if (LangOpts.ObjCRuntime.isNonFragile() &&
14793       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14794     Diag(Loc, diag::warn_ivars_in_interface);
14795 
14796   return NewID;
14797 }
14798 
14799 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14800 /// class and class extensions. For every class \@interface and class
14801 /// extension \@interface, if the last ivar is a bitfield of any type,
14802 /// then add an implicit `char :0` ivar to the end of that interface.
14803 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14804                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14805   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14806     return;
14807 
14808   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14809   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14810 
14811   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14812     return;
14813   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14814   if (!ID) {
14815     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14816       if (!CD->IsClassExtension())
14817         return;
14818     }
14819     // No need to add this to end of @implementation.
14820     else
14821       return;
14822   }
14823   // All conditions are met. Add a new bitfield to the tail end of ivars.
14824   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14825   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14826 
14827   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14828                               DeclLoc, DeclLoc, nullptr,
14829                               Context.CharTy,
14830                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14831                                                                DeclLoc),
14832                               ObjCIvarDecl::Private, BW,
14833                               true);
14834   AllIvarDecls.push_back(Ivar);
14835 }
14836 
14837 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14838                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14839                        SourceLocation RBrac, AttributeList *Attr) {
14840   assert(EnclosingDecl && "missing record or interface decl");
14841 
14842   // If this is an Objective-C @implementation or category and we have
14843   // new fields here we should reset the layout of the interface since
14844   // it will now change.
14845   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14846     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14847     switch (DC->getKind()) {
14848     default: break;
14849     case Decl::ObjCCategory:
14850       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14851       break;
14852     case Decl::ObjCImplementation:
14853       Context.
14854         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14855       break;
14856     }
14857   }
14858 
14859   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14860 
14861   // Start counting up the number of named members; make sure to include
14862   // members of anonymous structs and unions in the total.
14863   unsigned NumNamedMembers = 0;
14864   if (Record) {
14865     for (const auto *I : Record->decls()) {
14866       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14867         if (IFD->getDeclName())
14868           ++NumNamedMembers;
14869     }
14870   }
14871 
14872   // Verify that all the fields are okay.
14873   SmallVector<FieldDecl*, 32> RecFields;
14874 
14875   bool ObjCFieldLifetimeErrReported = false;
14876   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14877        i != end; ++i) {
14878     FieldDecl *FD = cast<FieldDecl>(*i);
14879 
14880     // Get the type for the field.
14881     const Type *FDTy = FD->getType().getTypePtr();
14882 
14883     if (!FD->isAnonymousStructOrUnion()) {
14884       // Remember all fields written by the user.
14885       RecFields.push_back(FD);
14886     }
14887 
14888     // If the field is already invalid for some reason, don't emit more
14889     // diagnostics about it.
14890     if (FD->isInvalidDecl()) {
14891       EnclosingDecl->setInvalidDecl();
14892       continue;
14893     }
14894 
14895     // C99 6.7.2.1p2:
14896     //   A structure or union shall not contain a member with
14897     //   incomplete or function type (hence, a structure shall not
14898     //   contain an instance of itself, but may contain a pointer to
14899     //   an instance of itself), except that the last member of a
14900     //   structure with more than one named member may have incomplete
14901     //   array type; such a structure (and any union containing,
14902     //   possibly recursively, a member that is such a structure)
14903     //   shall not be a member of a structure or an element of an
14904     //   array.
14905     if (FDTy->isFunctionType()) {
14906       // Field declared as a function.
14907       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14908         << FD->getDeclName();
14909       FD->setInvalidDecl();
14910       EnclosingDecl->setInvalidDecl();
14911       continue;
14912     } else if (FDTy->isIncompleteArrayType() && Record &&
14913                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14914                 ((getLangOpts().MicrosoftExt ||
14915                   getLangOpts().CPlusPlus) &&
14916                  (i + 1 == Fields.end() || Record->isUnion())))) {
14917       // Flexible array member.
14918       // Microsoft and g++ is more permissive regarding flexible array.
14919       // It will accept flexible array in union and also
14920       // as the sole element of a struct/class.
14921       unsigned DiagID = 0;
14922       if (Record->isUnion())
14923         DiagID = getLangOpts().MicrosoftExt
14924                      ? diag::ext_flexible_array_union_ms
14925                      : getLangOpts().CPlusPlus
14926                            ? diag::ext_flexible_array_union_gnu
14927                            : diag::err_flexible_array_union;
14928       else if (NumNamedMembers < 1)
14929         DiagID = getLangOpts().MicrosoftExt
14930                      ? diag::ext_flexible_array_empty_aggregate_ms
14931                      : getLangOpts().CPlusPlus
14932                            ? diag::ext_flexible_array_empty_aggregate_gnu
14933                            : diag::err_flexible_array_empty_aggregate;
14934 
14935       if (DiagID)
14936         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14937                                         << Record->getTagKind();
14938       // While the layout of types that contain virtual bases is not specified
14939       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14940       // virtual bases after the derived members.  This would make a flexible
14941       // array member declared at the end of an object not adjacent to the end
14942       // of the type.
14943       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14944         if (RD->getNumVBases() != 0)
14945           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14946             << FD->getDeclName() << Record->getTagKind();
14947       if (!getLangOpts().C99)
14948         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14949           << FD->getDeclName() << Record->getTagKind();
14950 
14951       // If the element type has a non-trivial destructor, we would not
14952       // implicitly destroy the elements, so disallow it for now.
14953       //
14954       // FIXME: GCC allows this. We should probably either implicitly delete
14955       // the destructor of the containing class, or just allow this.
14956       QualType BaseElem = Context.getBaseElementType(FD->getType());
14957       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14958         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14959           << FD->getDeclName() << FD->getType();
14960         FD->setInvalidDecl();
14961         EnclosingDecl->setInvalidDecl();
14962         continue;
14963       }
14964       // Okay, we have a legal flexible array member at the end of the struct.
14965       Record->setHasFlexibleArrayMember(true);
14966     } else if (!FDTy->isDependentType() &&
14967                RequireCompleteType(FD->getLocation(), FD->getType(),
14968                                    diag::err_field_incomplete)) {
14969       // Incomplete type
14970       FD->setInvalidDecl();
14971       EnclosingDecl->setInvalidDecl();
14972       continue;
14973     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14974       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14975         // A type which contains a flexible array member is considered to be a
14976         // flexible array member.
14977         Record->setHasFlexibleArrayMember(true);
14978         if (!Record->isUnion()) {
14979           // If this is a struct/class and this is not the last element, reject
14980           // it.  Note that GCC supports variable sized arrays in the middle of
14981           // structures.
14982           if (i + 1 != Fields.end())
14983             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14984               << FD->getDeclName() << FD->getType();
14985           else {
14986             // We support flexible arrays at the end of structs in
14987             // other structs as an extension.
14988             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14989               << FD->getDeclName();
14990           }
14991         }
14992       }
14993       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14994           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14995                                  diag::err_abstract_type_in_decl,
14996                                  AbstractIvarType)) {
14997         // Ivars can not have abstract class types
14998         FD->setInvalidDecl();
14999       }
15000       if (Record && FDTTy->getDecl()->hasObjectMember())
15001         Record->setHasObjectMember(true);
15002       if (Record && FDTTy->getDecl()->hasVolatileMember())
15003         Record->setHasVolatileMember(true);
15004     } else if (FDTy->isObjCObjectType()) {
15005       /// A field cannot be an Objective-c object
15006       Diag(FD->getLocation(), diag::err_statically_allocated_object)
15007         << FixItHint::CreateInsertion(FD->getLocation(), "*");
15008       QualType T = Context.getObjCObjectPointerType(FD->getType());
15009       FD->setType(T);
15010     } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15011                Record && !ObjCFieldLifetimeErrReported &&
15012                (!getLangOpts().CPlusPlus || Record->isUnion())) {
15013       // It's an error in ARC or Weak if a field has lifetime.
15014       // We don't want to report this in a system header, though,
15015       // so we just make the field unavailable.
15016       // FIXME: that's really not sufficient; we need to make the type
15017       // itself invalid to, say, initialize or copy.
15018       QualType T = FD->getType();
15019       if (T.hasNonTrivialObjCLifetime()) {
15020         SourceLocation loc = FD->getLocation();
15021         if (getSourceManager().isInSystemHeader(loc)) {
15022           if (!FD->hasAttr<UnavailableAttr>()) {
15023             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15024                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15025           }
15026         } else {
15027           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15028             << T->isBlockPointerType() << Record->getTagKind();
15029         }
15030         ObjCFieldLifetimeErrReported = true;
15031       }
15032     } else if (getLangOpts().ObjC1 &&
15033                getLangOpts().getGC() != LangOptions::NonGC &&
15034                Record && !Record->hasObjectMember()) {
15035       if (FD->getType()->isObjCObjectPointerType() ||
15036           FD->getType().isObjCGCStrong())
15037         Record->setHasObjectMember(true);
15038       else if (Context.getAsArrayType(FD->getType())) {
15039         QualType BaseType = Context.getBaseElementType(FD->getType());
15040         if (BaseType->isRecordType() &&
15041             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15042           Record->setHasObjectMember(true);
15043         else if (BaseType->isObjCObjectPointerType() ||
15044                  BaseType.isObjCGCStrong())
15045                Record->setHasObjectMember(true);
15046       }
15047     }
15048     if (Record && FD->getType().isVolatileQualified())
15049       Record->setHasVolatileMember(true);
15050     // Keep track of the number of named members.
15051     if (FD->getIdentifier())
15052       ++NumNamedMembers;
15053   }
15054 
15055   // Okay, we successfully defined 'Record'.
15056   if (Record) {
15057     bool Completed = false;
15058     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15059       if (!CXXRecord->isInvalidDecl()) {
15060         // Set access bits correctly on the directly-declared conversions.
15061         for (CXXRecordDecl::conversion_iterator
15062                I = CXXRecord->conversion_begin(),
15063                E = CXXRecord->conversion_end(); I != E; ++I)
15064           I.setAccess((*I)->getAccess());
15065       }
15066 
15067       if (!CXXRecord->isDependentType()) {
15068         if (CXXRecord->hasUserDeclaredDestructor()) {
15069           // Adjust user-defined destructor exception spec.
15070           if (getLangOpts().CPlusPlus11)
15071             AdjustDestructorExceptionSpec(CXXRecord,
15072                                           CXXRecord->getDestructor());
15073         }
15074 
15075         if (!CXXRecord->isInvalidDecl()) {
15076           // Add any implicitly-declared members to this class.
15077           AddImplicitlyDeclaredMembersToClass(CXXRecord);
15078 
15079           // If we have virtual base classes, we may end up finding multiple
15080           // final overriders for a given virtual function. Check for this
15081           // problem now.
15082           if (CXXRecord->getNumVBases()) {
15083             CXXFinalOverriderMap FinalOverriders;
15084             CXXRecord->getFinalOverriders(FinalOverriders);
15085 
15086             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15087                                              MEnd = FinalOverriders.end();
15088                  M != MEnd; ++M) {
15089               for (OverridingMethods::iterator SO = M->second.begin(),
15090                                             SOEnd = M->second.end();
15091                    SO != SOEnd; ++SO) {
15092                 assert(SO->second.size() > 0 &&
15093                        "Virtual function without overridding functions?");
15094                 if (SO->second.size() == 1)
15095                   continue;
15096 
15097                 // C++ [class.virtual]p2:
15098                 //   In a derived class, if a virtual member function of a base
15099                 //   class subobject has more than one final overrider the
15100                 //   program is ill-formed.
15101                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15102                   << (const NamedDecl *)M->first << Record;
15103                 Diag(M->first->getLocation(),
15104                      diag::note_overridden_virtual_function);
15105                 for (OverridingMethods::overriding_iterator
15106                           OM = SO->second.begin(),
15107                        OMEnd = SO->second.end();
15108                      OM != OMEnd; ++OM)
15109                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
15110                     << (const NamedDecl *)M->first << OM->Method->getParent();
15111 
15112                 Record->setInvalidDecl();
15113               }
15114             }
15115             CXXRecord->completeDefinition(&FinalOverriders);
15116             Completed = true;
15117           }
15118         }
15119       }
15120     }
15121 
15122     if (!Completed)
15123       Record->completeDefinition();
15124 
15125     // We may have deferred checking for a deleted destructor. Check now.
15126     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15127       auto *Dtor = CXXRecord->getDestructor();
15128       if (Dtor && Dtor->isImplicit() &&
15129           ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15130         CXXRecord->setImplicitDestructorIsDeleted();
15131         SetDeclDeleted(Dtor, CXXRecord->getLocation());
15132       }
15133     }
15134 
15135     if (Record->hasAttrs()) {
15136       CheckAlignasUnderalignment(Record);
15137 
15138       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15139         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15140                                            IA->getRange(), IA->getBestCase(),
15141                                            IA->getSemanticSpelling());
15142     }
15143 
15144     // Check if the structure/union declaration is a type that can have zero
15145     // size in C. For C this is a language extension, for C++ it may cause
15146     // compatibility problems.
15147     bool CheckForZeroSize;
15148     if (!getLangOpts().CPlusPlus) {
15149       CheckForZeroSize = true;
15150     } else {
15151       // For C++ filter out types that cannot be referenced in C code.
15152       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15153       CheckForZeroSize =
15154           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15155           !CXXRecord->isDependentType() &&
15156           CXXRecord->isCLike();
15157     }
15158     if (CheckForZeroSize) {
15159       bool ZeroSize = true;
15160       bool IsEmpty = true;
15161       unsigned NonBitFields = 0;
15162       for (RecordDecl::field_iterator I = Record->field_begin(),
15163                                       E = Record->field_end();
15164            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15165         IsEmpty = false;
15166         if (I->isUnnamedBitfield()) {
15167           if (I->getBitWidthValue(Context) > 0)
15168             ZeroSize = false;
15169         } else {
15170           ++NonBitFields;
15171           QualType FieldType = I->getType();
15172           if (FieldType->isIncompleteType() ||
15173               !Context.getTypeSizeInChars(FieldType).isZero())
15174             ZeroSize = false;
15175         }
15176       }
15177 
15178       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15179       // allowed in C++, but warn if its declaration is inside
15180       // extern "C" block.
15181       if (ZeroSize) {
15182         Diag(RecLoc, getLangOpts().CPlusPlus ?
15183                          diag::warn_zero_size_struct_union_in_extern_c :
15184                          diag::warn_zero_size_struct_union_compat)
15185           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15186       }
15187 
15188       // Structs without named members are extension in C (C99 6.7.2.1p7),
15189       // but are accepted by GCC.
15190       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15191         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15192                                diag::ext_no_named_members_in_struct_union)
15193           << Record->isUnion();
15194       }
15195     }
15196   } else {
15197     ObjCIvarDecl **ClsFields =
15198       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15199     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15200       ID->setEndOfDefinitionLoc(RBrac);
15201       // Add ivar's to class's DeclContext.
15202       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15203         ClsFields[i]->setLexicalDeclContext(ID);
15204         ID->addDecl(ClsFields[i]);
15205       }
15206       // Must enforce the rule that ivars in the base classes may not be
15207       // duplicates.
15208       if (ID->getSuperClass())
15209         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15210     } else if (ObjCImplementationDecl *IMPDecl =
15211                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15212       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
15213       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15214         // Ivar declared in @implementation never belongs to the implementation.
15215         // Only it is in implementation's lexical context.
15216         ClsFields[I]->setLexicalDeclContext(IMPDecl);
15217       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15218       IMPDecl->setIvarLBraceLoc(LBrac);
15219       IMPDecl->setIvarRBraceLoc(RBrac);
15220     } else if (ObjCCategoryDecl *CDecl =
15221                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15222       // case of ivars in class extension; all other cases have been
15223       // reported as errors elsewhere.
15224       // FIXME. Class extension does not have a LocEnd field.
15225       // CDecl->setLocEnd(RBrac);
15226       // Add ivar's to class extension's DeclContext.
15227       // Diagnose redeclaration of private ivars.
15228       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15229       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15230         if (IDecl) {
15231           if (const ObjCIvarDecl *ClsIvar =
15232               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15233             Diag(ClsFields[i]->getLocation(),
15234                  diag::err_duplicate_ivar_declaration);
15235             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15236             continue;
15237           }
15238           for (const auto *Ext : IDecl->known_extensions()) {
15239             if (const ObjCIvarDecl *ClsExtIvar
15240                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15241               Diag(ClsFields[i]->getLocation(),
15242                    diag::err_duplicate_ivar_declaration);
15243               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15244               continue;
15245             }
15246           }
15247         }
15248         ClsFields[i]->setLexicalDeclContext(CDecl);
15249         CDecl->addDecl(ClsFields[i]);
15250       }
15251       CDecl->setIvarLBraceLoc(LBrac);
15252       CDecl->setIvarRBraceLoc(RBrac);
15253     }
15254   }
15255 
15256   if (Attr)
15257     ProcessDeclAttributeList(S, Record, Attr);
15258 }
15259 
15260 /// \brief Determine whether the given integral value is representable within
15261 /// the given type T.
15262 static bool isRepresentableIntegerValue(ASTContext &Context,
15263                                         llvm::APSInt &Value,
15264                                         QualType T) {
15265   assert(T->isIntegralType(Context) && "Integral type required!");
15266   unsigned BitWidth = Context.getIntWidth(T);
15267 
15268   if (Value.isUnsigned() || Value.isNonNegative()) {
15269     if (T->isSignedIntegerOrEnumerationType())
15270       --BitWidth;
15271     return Value.getActiveBits() <= BitWidth;
15272   }
15273   return Value.getMinSignedBits() <= BitWidth;
15274 }
15275 
15276 // \brief Given an integral type, return the next larger integral type
15277 // (or a NULL type of no such type exists).
15278 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15279   // FIXME: Int128/UInt128 support, which also needs to be introduced into
15280   // enum checking below.
15281   assert(T->isIntegralType(Context) && "Integral type required!");
15282   const unsigned NumTypes = 4;
15283   QualType SignedIntegralTypes[NumTypes] = {
15284     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15285   };
15286   QualType UnsignedIntegralTypes[NumTypes] = {
15287     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15288     Context.UnsignedLongLongTy
15289   };
15290 
15291   unsigned BitWidth = Context.getTypeSize(T);
15292   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15293                                                         : UnsignedIntegralTypes;
15294   for (unsigned I = 0; I != NumTypes; ++I)
15295     if (Context.getTypeSize(Types[I]) > BitWidth)
15296       return Types[I];
15297 
15298   return QualType();
15299 }
15300 
15301 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15302                                           EnumConstantDecl *LastEnumConst,
15303                                           SourceLocation IdLoc,
15304                                           IdentifierInfo *Id,
15305                                           Expr *Val) {
15306   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15307   llvm::APSInt EnumVal(IntWidth);
15308   QualType EltTy;
15309 
15310   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15311     Val = nullptr;
15312 
15313   if (Val)
15314     Val = DefaultLvalueConversion(Val).get();
15315 
15316   if (Val) {
15317     if (Enum->isDependentType() || Val->isTypeDependent())
15318       EltTy = Context.DependentTy;
15319     else {
15320       SourceLocation ExpLoc;
15321       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15322           !getLangOpts().MSVCCompat) {
15323         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15324         // constant-expression in the enumerator-definition shall be a converted
15325         // constant expression of the underlying type.
15326         EltTy = Enum->getIntegerType();
15327         ExprResult Converted =
15328           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15329                                            CCEK_Enumerator);
15330         if (Converted.isInvalid())
15331           Val = nullptr;
15332         else
15333           Val = Converted.get();
15334       } else if (!Val->isValueDependent() &&
15335                  !(Val = VerifyIntegerConstantExpression(Val,
15336                                                          &EnumVal).get())) {
15337         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15338       } else {
15339         if (Enum->isFixed()) {
15340           EltTy = Enum->getIntegerType();
15341 
15342           // In Obj-C and Microsoft mode, require the enumeration value to be
15343           // representable in the underlying type of the enumeration. In C++11,
15344           // we perform a non-narrowing conversion as part of converted constant
15345           // expression checking.
15346           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15347             if (getLangOpts().MSVCCompat) {
15348               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15349               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15350             } else
15351               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15352           } else
15353             Val = ImpCastExprToType(Val, EltTy,
15354                                     EltTy->isBooleanType() ?
15355                                     CK_IntegralToBoolean : CK_IntegralCast)
15356                     .get();
15357         } else if (getLangOpts().CPlusPlus) {
15358           // C++11 [dcl.enum]p5:
15359           //   If the underlying type is not fixed, the type of each enumerator
15360           //   is the type of its initializing value:
15361           //     - If an initializer is specified for an enumerator, the
15362           //       initializing value has the same type as the expression.
15363           EltTy = Val->getType();
15364         } else {
15365           // C99 6.7.2.2p2:
15366           //   The expression that defines the value of an enumeration constant
15367           //   shall be an integer constant expression that has a value
15368           //   representable as an int.
15369 
15370           // Complain if the value is not representable in an int.
15371           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15372             Diag(IdLoc, diag::ext_enum_value_not_int)
15373               << EnumVal.toString(10) << Val->getSourceRange()
15374               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15375           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15376             // Force the type of the expression to 'int'.
15377             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15378           }
15379           EltTy = Val->getType();
15380         }
15381       }
15382     }
15383   }
15384 
15385   if (!Val) {
15386     if (Enum->isDependentType())
15387       EltTy = Context.DependentTy;
15388     else if (!LastEnumConst) {
15389       // C++0x [dcl.enum]p5:
15390       //   If the underlying type is not fixed, the type of each enumerator
15391       //   is the type of its initializing value:
15392       //     - If no initializer is specified for the first enumerator, the
15393       //       initializing value has an unspecified integral type.
15394       //
15395       // GCC uses 'int' for its unspecified integral type, as does
15396       // C99 6.7.2.2p3.
15397       if (Enum->isFixed()) {
15398         EltTy = Enum->getIntegerType();
15399       }
15400       else {
15401         EltTy = Context.IntTy;
15402       }
15403     } else {
15404       // Assign the last value + 1.
15405       EnumVal = LastEnumConst->getInitVal();
15406       ++EnumVal;
15407       EltTy = LastEnumConst->getType();
15408 
15409       // Check for overflow on increment.
15410       if (EnumVal < LastEnumConst->getInitVal()) {
15411         // C++0x [dcl.enum]p5:
15412         //   If the underlying type is not fixed, the type of each enumerator
15413         //   is the type of its initializing value:
15414         //
15415         //     - Otherwise the type of the initializing value is the same as
15416         //       the type of the initializing value of the preceding enumerator
15417         //       unless the incremented value is not representable in that type,
15418         //       in which case the type is an unspecified integral type
15419         //       sufficient to contain the incremented value. If no such type
15420         //       exists, the program is ill-formed.
15421         QualType T = getNextLargerIntegralType(Context, EltTy);
15422         if (T.isNull() || Enum->isFixed()) {
15423           // There is no integral type larger enough to represent this
15424           // value. Complain, then allow the value to wrap around.
15425           EnumVal = LastEnumConst->getInitVal();
15426           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15427           ++EnumVal;
15428           if (Enum->isFixed())
15429             // When the underlying type is fixed, this is ill-formed.
15430             Diag(IdLoc, diag::err_enumerator_wrapped)
15431               << EnumVal.toString(10)
15432               << EltTy;
15433           else
15434             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15435               << EnumVal.toString(10);
15436         } else {
15437           EltTy = T;
15438         }
15439 
15440         // Retrieve the last enumerator's value, extent that type to the
15441         // type that is supposed to be large enough to represent the incremented
15442         // value, then increment.
15443         EnumVal = LastEnumConst->getInitVal();
15444         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15445         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15446         ++EnumVal;
15447 
15448         // If we're not in C++, diagnose the overflow of enumerator values,
15449         // which in C99 means that the enumerator value is not representable in
15450         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15451         // permits enumerator values that are representable in some larger
15452         // integral type.
15453         if (!getLangOpts().CPlusPlus && !T.isNull())
15454           Diag(IdLoc, diag::warn_enum_value_overflow);
15455       } else if (!getLangOpts().CPlusPlus &&
15456                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15457         // Enforce C99 6.7.2.2p2 even when we compute the next value.
15458         Diag(IdLoc, diag::ext_enum_value_not_int)
15459           << EnumVal.toString(10) << 1;
15460       }
15461     }
15462   }
15463 
15464   if (!EltTy->isDependentType()) {
15465     // Make the enumerator value match the signedness and size of the
15466     // enumerator's type.
15467     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15468     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15469   }
15470 
15471   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15472                                   Val, EnumVal);
15473 }
15474 
15475 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15476                                                 SourceLocation IILoc) {
15477   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15478       !getLangOpts().CPlusPlus)
15479     return SkipBodyInfo();
15480 
15481   // We have an anonymous enum definition. Look up the first enumerator to
15482   // determine if we should merge the definition with an existing one and
15483   // skip the body.
15484   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15485                                          ForRedeclaration);
15486   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15487   if (!PrevECD)
15488     return SkipBodyInfo();
15489 
15490   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15491   NamedDecl *Hidden;
15492   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15493     SkipBodyInfo Skip;
15494     Skip.Previous = Hidden;
15495     return Skip;
15496   }
15497 
15498   return SkipBodyInfo();
15499 }
15500 
15501 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15502                               SourceLocation IdLoc, IdentifierInfo *Id,
15503                               AttributeList *Attr,
15504                               SourceLocation EqualLoc, Expr *Val) {
15505   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15506   EnumConstantDecl *LastEnumConst =
15507     cast_or_null<EnumConstantDecl>(lastEnumConst);
15508 
15509   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15510   // we find one that is.
15511   S = getNonFieldDeclScope(S);
15512 
15513   // Verify that there isn't already something declared with this name in this
15514   // scope.
15515   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15516                                          ForRedeclaration);
15517   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15518     // Maybe we will complain about the shadowed template parameter.
15519     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15520     // Just pretend that we didn't see the previous declaration.
15521     PrevDecl = nullptr;
15522   }
15523 
15524   // C++ [class.mem]p15:
15525   // If T is the name of a class, then each of the following shall have a name
15526   // different from T:
15527   // - every enumerator of every member of class T that is an unscoped
15528   // enumerated type
15529   if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15530     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15531                             DeclarationNameInfo(Id, IdLoc));
15532 
15533   EnumConstantDecl *New =
15534     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15535   if (!New)
15536     return nullptr;
15537 
15538   if (PrevDecl) {
15539     // When in C++, we may get a TagDecl with the same name; in this case the
15540     // enum constant will 'hide' the tag.
15541     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15542            "Received TagDecl when not in C++!");
15543     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15544         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15545       if (isa<EnumConstantDecl>(PrevDecl))
15546         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15547       else
15548         Diag(IdLoc, diag::err_redefinition) << Id;
15549       notePreviousDefinition(PrevDecl, IdLoc);
15550       return nullptr;
15551     }
15552   }
15553 
15554   // Process attributes.
15555   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15556   AddPragmaAttributes(S, New);
15557 
15558   // Register this decl in the current scope stack.
15559   New->setAccess(TheEnumDecl->getAccess());
15560   PushOnScopeChains(New, S);
15561 
15562   ActOnDocumentableDecl(New);
15563 
15564   return New;
15565 }
15566 
15567 // Returns true when the enum initial expression does not trigger the
15568 // duplicate enum warning.  A few common cases are exempted as follows:
15569 // Element2 = Element1
15570 // Element2 = Element1 + 1
15571 // Element2 = Element1 - 1
15572 // Where Element2 and Element1 are from the same enum.
15573 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15574   Expr *InitExpr = ECD->getInitExpr();
15575   if (!InitExpr)
15576     return true;
15577   InitExpr = InitExpr->IgnoreImpCasts();
15578 
15579   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15580     if (!BO->isAdditiveOp())
15581       return true;
15582     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15583     if (!IL)
15584       return true;
15585     if (IL->getValue() != 1)
15586       return true;
15587 
15588     InitExpr = BO->getLHS();
15589   }
15590 
15591   // This checks if the elements are from the same enum.
15592   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15593   if (!DRE)
15594     return true;
15595 
15596   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15597   if (!EnumConstant)
15598     return true;
15599 
15600   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15601       Enum)
15602     return true;
15603 
15604   return false;
15605 }
15606 
15607 namespace {
15608 struct DupKey {
15609   int64_t val;
15610   bool isTombstoneOrEmptyKey;
15611   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15612     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15613 };
15614 
15615 static DupKey GetDupKey(const llvm::APSInt& Val) {
15616   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15617                 false);
15618 }
15619 
15620 struct DenseMapInfoDupKey {
15621   static DupKey getEmptyKey() { return DupKey(0, true); }
15622   static DupKey getTombstoneKey() { return DupKey(1, true); }
15623   static unsigned getHashValue(const DupKey Key) {
15624     return (unsigned)(Key.val * 37);
15625   }
15626   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15627     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15628            LHS.val == RHS.val;
15629   }
15630 };
15631 } // end anonymous namespace
15632 
15633 // Emits a warning when an element is implicitly set a value that
15634 // a previous element has already been set to.
15635 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15636                                         EnumDecl *Enum,
15637                                         QualType EnumType) {
15638   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15639     return;
15640   // Avoid anonymous enums
15641   if (!Enum->getIdentifier())
15642     return;
15643 
15644   // Only check for small enums.
15645   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15646     return;
15647 
15648   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15649   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15650 
15651   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15652   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15653           ValueToVectorMap;
15654 
15655   DuplicatesVector DupVector;
15656   ValueToVectorMap EnumMap;
15657 
15658   // Populate the EnumMap with all values represented by enum constants without
15659   // an initialier.
15660   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15661     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15662 
15663     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15664     // this constant.  Skip this enum since it may be ill-formed.
15665     if (!ECD) {
15666       return;
15667     }
15668 
15669     if (ECD->getInitExpr())
15670       continue;
15671 
15672     DupKey Key = GetDupKey(ECD->getInitVal());
15673     DeclOrVector &Entry = EnumMap[Key];
15674 
15675     // First time encountering this value.
15676     if (Entry.isNull())
15677       Entry = ECD;
15678   }
15679 
15680   // Create vectors for any values that has duplicates.
15681   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15682     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15683     if (!ValidDuplicateEnum(ECD, Enum))
15684       continue;
15685 
15686     DupKey Key = GetDupKey(ECD->getInitVal());
15687 
15688     DeclOrVector& Entry = EnumMap[Key];
15689     if (Entry.isNull())
15690       continue;
15691 
15692     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15693       // Ensure constants are different.
15694       if (D == ECD)
15695         continue;
15696 
15697       // Create new vector and push values onto it.
15698       ECDVector *Vec = new ECDVector();
15699       Vec->push_back(D);
15700       Vec->push_back(ECD);
15701 
15702       // Update entry to point to the duplicates vector.
15703       Entry = Vec;
15704 
15705       // Store the vector somewhere we can consult later for quick emission of
15706       // diagnostics.
15707       DupVector.push_back(Vec);
15708       continue;
15709     }
15710 
15711     ECDVector *Vec = Entry.get<ECDVector*>();
15712     // Make sure constants are not added more than once.
15713     if (*Vec->begin() == ECD)
15714       continue;
15715 
15716     Vec->push_back(ECD);
15717   }
15718 
15719   // Emit diagnostics.
15720   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15721                                   DupVectorEnd = DupVector.end();
15722        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15723     ECDVector *Vec = *DupVectorIter;
15724     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15725 
15726     // Emit warning for one enum constant.
15727     ECDVector::iterator I = Vec->begin();
15728     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15729       << (*I)->getName() << (*I)->getInitVal().toString(10)
15730       << (*I)->getSourceRange();
15731     ++I;
15732 
15733     // Emit one note for each of the remaining enum constants with
15734     // the same value.
15735     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15736       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15737         << (*I)->getName() << (*I)->getInitVal().toString(10)
15738         << (*I)->getSourceRange();
15739     delete Vec;
15740   }
15741 }
15742 
15743 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15744                              bool AllowMask) const {
15745   assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
15746   assert(ED->isCompleteDefinition() && "expected enum definition");
15747 
15748   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15749   llvm::APInt &FlagBits = R.first->second;
15750 
15751   if (R.second) {
15752     for (auto *E : ED->enumerators()) {
15753       const auto &EVal = E->getInitVal();
15754       // Only single-bit enumerators introduce new flag values.
15755       if (EVal.isPowerOf2())
15756         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15757     }
15758   }
15759 
15760   // A value is in a flag enum if either its bits are a subset of the enum's
15761   // flag bits (the first condition) or we are allowing masks and the same is
15762   // true of its complement (the second condition). When masks are allowed, we
15763   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15764   //
15765   // While it's true that any value could be used as a mask, the assumption is
15766   // that a mask will have all of the insignificant bits set. Anything else is
15767   // likely a logic error.
15768   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15769   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15770 }
15771 
15772 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15773                          Decl *EnumDeclX,
15774                          ArrayRef<Decl *> Elements,
15775                          Scope *S, AttributeList *Attr) {
15776   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15777   QualType EnumType = Context.getTypeDeclType(Enum);
15778 
15779   if (Attr)
15780     ProcessDeclAttributeList(S, Enum, Attr);
15781 
15782   if (Enum->isDependentType()) {
15783     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15784       EnumConstantDecl *ECD =
15785         cast_or_null<EnumConstantDecl>(Elements[i]);
15786       if (!ECD) continue;
15787 
15788       ECD->setType(EnumType);
15789     }
15790 
15791     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15792     return;
15793   }
15794 
15795   // TODO: If the result value doesn't fit in an int, it must be a long or long
15796   // long value.  ISO C does not support this, but GCC does as an extension,
15797   // emit a warning.
15798   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15799   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15800   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15801 
15802   // Verify that all the values are okay, compute the size of the values, and
15803   // reverse the list.
15804   unsigned NumNegativeBits = 0;
15805   unsigned NumPositiveBits = 0;
15806 
15807   // Keep track of whether all elements have type int.
15808   bool AllElementsInt = true;
15809 
15810   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15811     EnumConstantDecl *ECD =
15812       cast_or_null<EnumConstantDecl>(Elements[i]);
15813     if (!ECD) continue;  // Already issued a diagnostic.
15814 
15815     const llvm::APSInt &InitVal = ECD->getInitVal();
15816 
15817     // Keep track of the size of positive and negative values.
15818     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15819       NumPositiveBits = std::max(NumPositiveBits,
15820                                  (unsigned)InitVal.getActiveBits());
15821     else
15822       NumNegativeBits = std::max(NumNegativeBits,
15823                                  (unsigned)InitVal.getMinSignedBits());
15824 
15825     // Keep track of whether every enum element has type int (very commmon).
15826     if (AllElementsInt)
15827       AllElementsInt = ECD->getType() == Context.IntTy;
15828   }
15829 
15830   // Figure out the type that should be used for this enum.
15831   QualType BestType;
15832   unsigned BestWidth;
15833 
15834   // C++0x N3000 [conv.prom]p3:
15835   //   An rvalue of an unscoped enumeration type whose underlying
15836   //   type is not fixed can be converted to an rvalue of the first
15837   //   of the following types that can represent all the values of
15838   //   the enumeration: int, unsigned int, long int, unsigned long
15839   //   int, long long int, or unsigned long long int.
15840   // C99 6.4.4.3p2:
15841   //   An identifier declared as an enumeration constant has type int.
15842   // The C99 rule is modified by a gcc extension
15843   QualType BestPromotionType;
15844 
15845   bool Packed = Enum->hasAttr<PackedAttr>();
15846   // -fshort-enums is the equivalent to specifying the packed attribute on all
15847   // enum definitions.
15848   if (LangOpts.ShortEnums)
15849     Packed = true;
15850 
15851   if (Enum->isFixed()) {
15852     BestType = Enum->getIntegerType();
15853     if (BestType->isPromotableIntegerType())
15854       BestPromotionType = Context.getPromotedIntegerType(BestType);
15855     else
15856       BestPromotionType = BestType;
15857 
15858     BestWidth = Context.getIntWidth(BestType);
15859   }
15860   else if (NumNegativeBits) {
15861     // If there is a negative value, figure out the smallest integer type (of
15862     // int/long/longlong) that fits.
15863     // If it's packed, check also if it fits a char or a short.
15864     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15865       BestType = Context.SignedCharTy;
15866       BestWidth = CharWidth;
15867     } else if (Packed && NumNegativeBits <= ShortWidth &&
15868                NumPositiveBits < ShortWidth) {
15869       BestType = Context.ShortTy;
15870       BestWidth = ShortWidth;
15871     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15872       BestType = Context.IntTy;
15873       BestWidth = IntWidth;
15874     } else {
15875       BestWidth = Context.getTargetInfo().getLongWidth();
15876 
15877       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15878         BestType = Context.LongTy;
15879       } else {
15880         BestWidth = Context.getTargetInfo().getLongLongWidth();
15881 
15882         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15883           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15884         BestType = Context.LongLongTy;
15885       }
15886     }
15887     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15888   } else {
15889     // If there is no negative value, figure out the smallest type that fits
15890     // all of the enumerator values.
15891     // If it's packed, check also if it fits a char or a short.
15892     if (Packed && NumPositiveBits <= CharWidth) {
15893       BestType = Context.UnsignedCharTy;
15894       BestPromotionType = Context.IntTy;
15895       BestWidth = CharWidth;
15896     } else if (Packed && NumPositiveBits <= ShortWidth) {
15897       BestType = Context.UnsignedShortTy;
15898       BestPromotionType = Context.IntTy;
15899       BestWidth = ShortWidth;
15900     } else if (NumPositiveBits <= IntWidth) {
15901       BestType = Context.UnsignedIntTy;
15902       BestWidth = IntWidth;
15903       BestPromotionType
15904         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15905                            ? Context.UnsignedIntTy : Context.IntTy;
15906     } else if (NumPositiveBits <=
15907                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15908       BestType = Context.UnsignedLongTy;
15909       BestPromotionType
15910         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15911                            ? Context.UnsignedLongTy : Context.LongTy;
15912     } else {
15913       BestWidth = Context.getTargetInfo().getLongLongWidth();
15914       assert(NumPositiveBits <= BestWidth &&
15915              "How could an initializer get larger than ULL?");
15916       BestType = Context.UnsignedLongLongTy;
15917       BestPromotionType
15918         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15919                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15920     }
15921   }
15922 
15923   // Loop over all of the enumerator constants, changing their types to match
15924   // the type of the enum if needed.
15925   for (auto *D : Elements) {
15926     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15927     if (!ECD) continue;  // Already issued a diagnostic.
15928 
15929     // Standard C says the enumerators have int type, but we allow, as an
15930     // extension, the enumerators to be larger than int size.  If each
15931     // enumerator value fits in an int, type it as an int, otherwise type it the
15932     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15933     // that X has type 'int', not 'unsigned'.
15934 
15935     // Determine whether the value fits into an int.
15936     llvm::APSInt InitVal = ECD->getInitVal();
15937 
15938     // If it fits into an integer type, force it.  Otherwise force it to match
15939     // the enum decl type.
15940     QualType NewTy;
15941     unsigned NewWidth;
15942     bool NewSign;
15943     if (!getLangOpts().CPlusPlus &&
15944         !Enum->isFixed() &&
15945         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15946       NewTy = Context.IntTy;
15947       NewWidth = IntWidth;
15948       NewSign = true;
15949     } else if (ECD->getType() == BestType) {
15950       // Already the right type!
15951       if (getLangOpts().CPlusPlus)
15952         // C++ [dcl.enum]p4: Following the closing brace of an
15953         // enum-specifier, each enumerator has the type of its
15954         // enumeration.
15955         ECD->setType(EnumType);
15956       continue;
15957     } else {
15958       NewTy = BestType;
15959       NewWidth = BestWidth;
15960       NewSign = BestType->isSignedIntegerOrEnumerationType();
15961     }
15962 
15963     // Adjust the APSInt value.
15964     InitVal = InitVal.extOrTrunc(NewWidth);
15965     InitVal.setIsSigned(NewSign);
15966     ECD->setInitVal(InitVal);
15967 
15968     // Adjust the Expr initializer and type.
15969     if (ECD->getInitExpr() &&
15970         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15971       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15972                                                 CK_IntegralCast,
15973                                                 ECD->getInitExpr(),
15974                                                 /*base paths*/ nullptr,
15975                                                 VK_RValue));
15976     if (getLangOpts().CPlusPlus)
15977       // C++ [dcl.enum]p4: Following the closing brace of an
15978       // enum-specifier, each enumerator has the type of its
15979       // enumeration.
15980       ECD->setType(EnumType);
15981     else
15982       ECD->setType(NewTy);
15983   }
15984 
15985   Enum->completeDefinition(BestType, BestPromotionType,
15986                            NumPositiveBits, NumNegativeBits);
15987 
15988   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15989 
15990   if (Enum->isClosedFlag()) {
15991     for (Decl *D : Elements) {
15992       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15993       if (!ECD) continue;  // Already issued a diagnostic.
15994 
15995       llvm::APSInt InitVal = ECD->getInitVal();
15996       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15997           !IsValueInFlagEnum(Enum, InitVal, true))
15998         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15999           << ECD << Enum;
16000     }
16001   }
16002 
16003   // Now that the enum type is defined, ensure it's not been underaligned.
16004   if (Enum->hasAttrs())
16005     CheckAlignasUnderalignment(Enum);
16006 }
16007 
16008 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16009                                   SourceLocation StartLoc,
16010                                   SourceLocation EndLoc) {
16011   StringLiteral *AsmString = cast<StringLiteral>(expr);
16012 
16013   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16014                                                    AsmString, StartLoc,
16015                                                    EndLoc);
16016   CurContext->addDecl(New);
16017   return New;
16018 }
16019 
16020 static void checkModuleImportContext(Sema &S, Module *M,
16021                                      SourceLocation ImportLoc, DeclContext *DC,
16022                                      bool FromInclude = false) {
16023   SourceLocation ExternCLoc;
16024 
16025   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16026     switch (LSD->getLanguage()) {
16027     case LinkageSpecDecl::lang_c:
16028       if (ExternCLoc.isInvalid())
16029         ExternCLoc = LSD->getLocStart();
16030       break;
16031     case LinkageSpecDecl::lang_cxx:
16032       break;
16033     }
16034     DC = LSD->getParent();
16035   }
16036 
16037   while (isa<LinkageSpecDecl>(DC))
16038     DC = DC->getParent();
16039 
16040   if (!isa<TranslationUnitDecl>(DC)) {
16041     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16042                           ? diag::ext_module_import_not_at_top_level_noop
16043                           : diag::err_module_import_not_at_top_level_fatal)
16044         << M->getFullModuleName() << DC;
16045     S.Diag(cast<Decl>(DC)->getLocStart(),
16046            diag::note_module_import_not_at_top_level) << DC;
16047   } else if (!M->IsExternC && ExternCLoc.isValid()) {
16048     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16049       << M->getFullModuleName();
16050     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16051   }
16052 }
16053 
16054 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16055                                            SourceLocation ModuleLoc,
16056                                            ModuleDeclKind MDK,
16057                                            ModuleIdPath Path) {
16058   assert(getLangOpts().ModulesTS &&
16059          "should only have module decl in modules TS");
16060 
16061   // A module implementation unit requires that we are not compiling a module
16062   // of any kind. A module interface unit requires that we are not compiling a
16063   // module map.
16064   switch (getLangOpts().getCompilingModule()) {
16065   case LangOptions::CMK_None:
16066     // It's OK to compile a module interface as a normal translation unit.
16067     break;
16068 
16069   case LangOptions::CMK_ModuleInterface:
16070     if (MDK != ModuleDeclKind::Implementation)
16071       break;
16072 
16073     // We were asked to compile a module interface unit but this is a module
16074     // implementation unit. That indicates the 'export' is missing.
16075     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16076       << FixItHint::CreateInsertion(ModuleLoc, "export ");
16077     break;
16078 
16079   case LangOptions::CMK_ModuleMap:
16080     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16081     return nullptr;
16082   }
16083 
16084   // FIXME: Most of this work should be done by the preprocessor rather than
16085   // here, in order to support macro import.
16086 
16087   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16088   // modules, the dots here are just another character that can appear in a
16089   // module name.
16090   std::string ModuleName;
16091   for (auto &Piece : Path) {
16092     if (!ModuleName.empty())
16093       ModuleName += ".";
16094     ModuleName += Piece.first->getName();
16095   }
16096 
16097   // FIXME: If we've already seen a module-declaration, report an error.
16098 
16099   // If a module name was explicitly specified on the command line, it must be
16100   // correct.
16101   if (!getLangOpts().CurrentModule.empty() &&
16102       getLangOpts().CurrentModule != ModuleName) {
16103     Diag(Path.front().second, diag::err_current_module_name_mismatch)
16104         << SourceRange(Path.front().second, Path.back().second)
16105         << getLangOpts().CurrentModule;
16106     return nullptr;
16107   }
16108   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16109 
16110   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16111   Module *Mod;
16112 
16113   assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
16114 
16115   switch (MDK) {
16116   case ModuleDeclKind::Module: {
16117     // We can't have parsed or imported a definition of this module or parsed a
16118     // module map defining it already.
16119     if (auto *M = Map.findModule(ModuleName)) {
16120       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16121       if (M->DefinitionLoc.isValid())
16122         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16123       else if (const auto *FE = M->getASTFile())
16124         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16125             << FE->getName();
16126       return nullptr;
16127     }
16128 
16129     // Create a Module for the module that we're defining.
16130     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16131                                            ModuleScopes.front().Module);
16132     assert(Mod && "module creation should not fail");
16133     break;
16134   }
16135 
16136   case ModuleDeclKind::Partition:
16137     // FIXME: Check we are in a submodule of the named module.
16138     return nullptr;
16139 
16140   case ModuleDeclKind::Implementation:
16141     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16142         PP.getIdentifierInfo(ModuleName), Path[0].second);
16143     Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16144                                        /*IsIncludeDirective=*/false);
16145     if (!Mod)
16146       return nullptr;
16147     break;
16148   }
16149 
16150   // Switch from the global module to the named module.
16151   ModuleScopes.back().Module = Mod;
16152   VisibleModules.setVisible(Mod, ModuleLoc);
16153 
16154   // From now on, we have an owning module for all declarations we see.
16155   // However, those declarations are module-private unless explicitly
16156   // exported.
16157   auto *TU = Context.getTranslationUnitDecl();
16158   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16159   TU->setLocalOwningModule(Mod);
16160 
16161   // FIXME: Create a ModuleDecl.
16162   return nullptr;
16163 }
16164 
16165 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16166                                    SourceLocation ImportLoc,
16167                                    ModuleIdPath Path) {
16168   Module *Mod =
16169       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16170                                    /*IsIncludeDirective=*/false);
16171   if (!Mod)
16172     return true;
16173 
16174   VisibleModules.setVisible(Mod, ImportLoc);
16175 
16176   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16177 
16178   // FIXME: we should support importing a submodule within a different submodule
16179   // of the same top-level module. Until we do, make it an error rather than
16180   // silently ignoring the import.
16181   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16182   // warn on a redundant import of the current module?
16183   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16184       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16185     Diag(ImportLoc, getLangOpts().isCompilingModule()
16186                         ? diag::err_module_self_import
16187                         : diag::err_module_import_in_implementation)
16188         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16189 
16190   SmallVector<SourceLocation, 2> IdentifierLocs;
16191   Module *ModCheck = Mod;
16192   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16193     // If we've run out of module parents, just drop the remaining identifiers.
16194     // We need the length to be consistent.
16195     if (!ModCheck)
16196       break;
16197     ModCheck = ModCheck->Parent;
16198 
16199     IdentifierLocs.push_back(Path[I].second);
16200   }
16201 
16202   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16203   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
16204                                           Mod, IdentifierLocs);
16205   if (!ModuleScopes.empty())
16206     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16207   TU->addDecl(Import);
16208   return Import;
16209 }
16210 
16211 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16212   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16213   BuildModuleInclude(DirectiveLoc, Mod);
16214 }
16215 
16216 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16217   // Determine whether we're in the #include buffer for a module. The #includes
16218   // in that buffer do not qualify as module imports; they're just an
16219   // implementation detail of us building the module.
16220   //
16221   // FIXME: Should we even get ActOnModuleInclude calls for those?
16222   bool IsInModuleIncludes =
16223       TUKind == TU_Module &&
16224       getSourceManager().isWrittenInMainFile(DirectiveLoc);
16225 
16226   bool ShouldAddImport = !IsInModuleIncludes;
16227 
16228   // If this module import was due to an inclusion directive, create an
16229   // implicit import declaration to capture it in the AST.
16230   if (ShouldAddImport) {
16231     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16232     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16233                                                      DirectiveLoc, Mod,
16234                                                      DirectiveLoc);
16235     if (!ModuleScopes.empty())
16236       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16237     TU->addDecl(ImportD);
16238     Consumer.HandleImplicitImportDecl(ImportD);
16239   }
16240 
16241   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16242   VisibleModules.setVisible(Mod, DirectiveLoc);
16243 }
16244 
16245 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16246   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16247 
16248   ModuleScopes.push_back({});
16249   ModuleScopes.back().Module = Mod;
16250   if (getLangOpts().ModulesLocalVisibility)
16251     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16252 
16253   VisibleModules.setVisible(Mod, DirectiveLoc);
16254 
16255   // The enclosing context is now part of this module.
16256   // FIXME: Consider creating a child DeclContext to hold the entities
16257   // lexically within the module.
16258   if (getLangOpts().trackLocalOwningModule()) {
16259     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16260       cast<Decl>(DC)->setModuleOwnershipKind(
16261           getLangOpts().ModulesLocalVisibility
16262               ? Decl::ModuleOwnershipKind::VisibleWhenImported
16263               : Decl::ModuleOwnershipKind::Visible);
16264       cast<Decl>(DC)->setLocalOwningModule(Mod);
16265     }
16266   }
16267 }
16268 
16269 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16270   if (getLangOpts().ModulesLocalVisibility) {
16271     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16272     // Leaving a module hides namespace names, so our visible namespace cache
16273     // is now out of date.
16274     VisibleNamespaceCache.clear();
16275   }
16276 
16277   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
16278          "left the wrong module scope");
16279   ModuleScopes.pop_back();
16280 
16281   // We got to the end of processing a local module. Create an
16282   // ImportDecl as we would for an imported module.
16283   FileID File = getSourceManager().getFileID(EomLoc);
16284   SourceLocation DirectiveLoc;
16285   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16286     // We reached the end of a #included module header. Use the #include loc.
16287     assert(File != getSourceManager().getMainFileID() &&
16288            "end of submodule in main source file");
16289     DirectiveLoc = getSourceManager().getIncludeLoc(File);
16290   } else {
16291     // We reached an EOM pragma. Use the pragma location.
16292     DirectiveLoc = EomLoc;
16293   }
16294   BuildModuleInclude(DirectiveLoc, Mod);
16295 
16296   // Any further declarations are in whatever module we returned to.
16297   if (getLangOpts().trackLocalOwningModule()) {
16298     // The parser guarantees that this is the same context that we entered
16299     // the module within.
16300     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16301       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16302       if (!getCurrentModule())
16303         cast<Decl>(DC)->setModuleOwnershipKind(
16304             Decl::ModuleOwnershipKind::Unowned);
16305     }
16306   }
16307 }
16308 
16309 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16310                                                       Module *Mod) {
16311   // Bail if we're not allowed to implicitly import a module here.
16312   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16313       VisibleModules.isVisible(Mod))
16314     return;
16315 
16316   // Create the implicit import declaration.
16317   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16318   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16319                                                    Loc, Mod, Loc);
16320   TU->addDecl(ImportD);
16321   Consumer.HandleImplicitImportDecl(ImportD);
16322 
16323   // Make the module visible.
16324   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16325   VisibleModules.setVisible(Mod, Loc);
16326 }
16327 
16328 /// We have parsed the start of an export declaration, including the '{'
16329 /// (if present).
16330 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16331                                  SourceLocation LBraceLoc) {
16332   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16333 
16334   // C++ Modules TS draft:
16335   //   An export-declaration shall appear in the purview of a module other than
16336   //   the global module.
16337   if (ModuleScopes.empty() ||
16338       ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit)
16339     Diag(ExportLoc, diag::err_export_not_in_module_interface);
16340 
16341   //   An export-declaration [...] shall not contain more than one
16342   //   export keyword.
16343   //
16344   // The intent here is that an export-declaration cannot appear within another
16345   // export-declaration.
16346   if (D->isExported())
16347     Diag(ExportLoc, diag::err_export_within_export);
16348 
16349   CurContext->addDecl(D);
16350   PushDeclContext(S, D);
16351   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16352   return D;
16353 }
16354 
16355 /// Complete the definition of an export declaration.
16356 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16357   auto *ED = cast<ExportDecl>(D);
16358   if (RBraceLoc.isValid())
16359     ED->setRBraceLoc(RBraceLoc);
16360 
16361   // FIXME: Diagnose export of internal-linkage declaration (including
16362   // anonymous namespace).
16363 
16364   PopDeclContext();
16365   return D;
16366 }
16367 
16368 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16369                                       IdentifierInfo* AliasName,
16370                                       SourceLocation PragmaLoc,
16371                                       SourceLocation NameLoc,
16372                                       SourceLocation AliasNameLoc) {
16373   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16374                                          LookupOrdinaryName);
16375   AsmLabelAttr *Attr =
16376       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16377 
16378   // If a declaration that:
16379   // 1) declares a function or a variable
16380   // 2) has external linkage
16381   // already exists, add a label attribute to it.
16382   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16383     if (isDeclExternC(PrevDecl))
16384       PrevDecl->addAttr(Attr);
16385     else
16386       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16387           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16388   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16389   } else
16390     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16391 }
16392 
16393 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16394                              SourceLocation PragmaLoc,
16395                              SourceLocation NameLoc) {
16396   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16397 
16398   if (PrevDecl) {
16399     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16400   } else {
16401     (void)WeakUndeclaredIdentifiers.insert(
16402       std::pair<IdentifierInfo*,WeakInfo>
16403         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16404   }
16405 }
16406 
16407 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16408                                 IdentifierInfo* AliasName,
16409                                 SourceLocation PragmaLoc,
16410                                 SourceLocation NameLoc,
16411                                 SourceLocation AliasNameLoc) {
16412   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16413                                     LookupOrdinaryName);
16414   WeakInfo W = WeakInfo(Name, NameLoc);
16415 
16416   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16417     if (!PrevDecl->hasAttr<AliasAttr>())
16418       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16419         DeclApplyPragmaWeak(TUScope, ND, W);
16420   } else {
16421     (void)WeakUndeclaredIdentifiers.insert(
16422       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16423   }
16424 }
16425 
16426 Decl *Sema::getObjCDeclContext() const {
16427   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16428 }
16429